Modelo inicial a estudiar:
\(Ventas=2.939 +0.046*TV + 0.189*Radio-0.001*Newspaper\)
la hipótesis nula dice que no hay relación entre los cambios en el presupuesto de publicidad en TV, radio o periódico y los cambios en las ventas totales. En otras palabras, aumentar el gasto en publicidad en TV y radio está relacionado con un aumento en las ventas. Por ejemplo, por cada $1,000 adicionales gastados en publicidad en TV, se pueden vender 46 unidades más. Del mismo modo, por cada $1,000 adicionales gastados en publicidad en radio, se pueden vender 189 unidades más.
Modelo con el que me quedo: \(Ventas=2.939 +0.046*TV + 0.189*Radio\)
La opción iv). La ecuación es:
\(Salario=b_{0} + b_{1}GPA + b_{2}IQ+b_{3}Nivel + b_{4} (GPA/IQ) + b_{5} ( GPA/Nivel)+ \epsilon\)
Dado que =35, podemos ver que la variable de nivel tiene un impacto significativo en el salario. Además, dado que =-10, la interacción entre GPA y Nivel tiene un efecto negativo. La opción correcta sería iv). Esto se debe a que, aunque la variable de nivel tiene un impacto positivo, la interacción entre GPA y Nivel tiene un efecto negativo. Por lo tanto, la diferencia en salarios entre graduados universitarios y de secundaria depende del nivel de GPA, y los graduados universitarios tienden a obtener más cuando el GPA es lo suficientemente alto.
Para predecir el salario de un graduado universitario con un coeficiente intelectual de 110 y un GPA de 4.0, podemos usar la ecuación de regresión: Salario = Dado que estamos prediciendo para un graduado universitario, podemos simplificar la ecuación:
\(Salario= 50 + 20*GPA + 0.07*IQ + 35*Nivel + 0.01 (GPA/IQ) - 10(GPA/Nivel)\)
Calculado esto se obtiene la predicción del salario para el graduado universitario con las características dadas.
Verdadero. Un coeficiente pequeño para el término de interacción GPA/IQ sugiere que la relación conjunta entre GPA e IQ tiene un impacto limitado en la variable respuesta (salario). En términos prácticos, este coeficiente pequeño indica que la interacción no está contribuyendo significativamente a las variaciones en el salario. La fuerza de la evidencia de un efecto de interacción se evalúa en función del tamaña relativo del coeficiente y su significancia estadística. Si el coeficiente es pequeño y no es estadísticamente significativo, hay poca evidencia de un efecto de interacción sustancial
library(MASS)
library(ISLR2)
##
## Attaching package: 'ISLR2'
## The following object is masked from 'package:MASS':
##
## Boston
#Cargar el conjunto de datos de Carseats
attach(Carseats)
Modelo : \(Sales= b_{0} + b_{1}*Price + b_{2}*Urban + b_{3}*US + \epsilon\)
#Ajustar el modelo de regresión múltiple
modelo<- lm(Sales ~Price + Urban +US, data=Carseats)
modelo
##
## Call:
## lm(formula = Sales ~ Price + Urban + US, data = Carseats)
##
## Coefficients:
## (Intercept) Price UrbanYes USYes
## 13.04347 -0.05446 -0.02192 1.20057
Prince indica que por cada unidad adicional en el precio del producto,
las ventas disminuyen en 0.054459 unidades, manteniendo las otras
constantes. El coeficinete de UrbanYes(-0.021916) indica que si la
tienda está ubicada en un área urbana ( UrbanYes=1)las ventas disminuyen
en 0.021916 unidades en comparación con una ubicada en un área no
urbana(UrbanYes=0), manteniendo las otras variables constantes. El
coeficiente de USYes(1.200573) indica que si el producto esfabricado en
los Estados Unidos (UsYes=1), las ventas aumentan en 1.200573 unidades
en comparación con un producto fabricado fuera de los Estados
Unidos(USYes=0), manteniendolas otras vairbles constantes.
En resumen, el coeficiente de Price nos muestra la influencia del precio en las ventas, mientras que los coeficientes de UrbanYes y UsYes nos dan información sobre cómo la ubicación y el lugar geografico del producto afectan a las ventas
#Obtener resultados del modelo
summary(modelo)
##
## Call:
## lm(formula = Sales ~ Price + Urban + US, data = Carseats)
##
## Residuals:
## Min 1Q Median 3Q Max
## -6.9206 -1.6220 -0.0564 1.5786 7.0581
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 13.043469 0.651012 20.036 < 2e-16 ***
## Price -0.054459 0.005242 -10.389 < 2e-16 ***
## UrbanYes -0.021916 0.271650 -0.081 0.936
## USYes 1.200573 0.259042 4.635 4.86e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.472 on 396 degrees of freedom
## Multiple R-squared: 0.2393, Adjusted R-squared: 0.2335
## F-statistic: 41.52 on 3 and 396 DF, p-value: < 2.2e-16
\(Sales=13,043469-0,054459*Price -
0,021916*UrbanYes + 1,200573*USYes\)
#Obtener resultado para modelo reducido
lm2=lm(Sales~Price+US)
summary(lm2)
##
## Call:
## lm(formula = Sales ~ Price + US)
##
## Residuals:
## Min 1Q Median 3Q Max
## -6.9269 -1.6286 -0.0574 1.5766 7.0515
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 13.03079 0.63098 20.652 < 2e-16 ***
## Price -0.05448 0.00523 -10.416 < 2e-16 ***
## USYes 1.19964 0.25846 4.641 4.71e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.469 on 397 degrees of freedom
## Multiple R-squared: 0.2393, Adjusted R-squared: 0.2354
## F-statistic: 62.43 on 2 and 397 DF, p-value: < 2.2e-16
si tenemos alfa = 0.05, p-valor menor que alfa, se puede rechazar la hipotesis nula y concluir que hay evidencia estadistica de que el predictor tiene un efecto significativo en la variable respuesta.
Modelo que ajusto segun el p-valor obtenido ```
\[sales=13,043469-0,054459*Price+1,200573*UsYes\]
Viendo RSE y \(R^2\) de las regresiones lineales, ambas se ajustan a los datos de manera similar, aunque la regresión lineal del modelo reducido se ajusta un poco mejor.
#Intervalos de confianza
confint(lm2)
## 2.5 % 97.5 %
## (Intercept) 11.79032020 14.27126531
## Price -0.06475984 -0.04419543
## USYes 0.69151957 1.70776632
Intervalos de confianza al 95%
\(b_{0}= (11.79032020, 14.27126531)\)
\(b_{1}=(-0.06475984, -0.4419543)\)
\(b_{2}=(0.69151957, 1.70776632)\)
#valores atipicos
plot(predict(lm2),rstudent(lm2))
par(mfrow=c(2,2))
plot(lm2)

FIGURA 3.1: Gráfica de regresion lineal frente a los residuos
standarizados

FIGURA 3.2: representación de los valores
set.seed(1)
x=rnorm(100)
x
## [1] -0.626453811 0.183643324 -0.835628612 1.595280802 0.329507772
## [6] -0.820468384 0.487429052 0.738324705 0.575781352 -0.305388387
## [11] 1.511781168 0.389843236 -0.621240581 -2.214699887 1.124930918
## [16] -0.044933609 -0.016190263 0.943836211 0.821221195 0.593901321
## [21] 0.918977372 0.782136301 0.074564983 -1.989351696 0.619825748
## [26] -0.056128740 -0.155795507 -1.470752384 -0.478150055 0.417941560
## [31] 1.358679552 -0.102787727 0.387671612 -0.053805041 -1.377059557
## [36] -0.414994563 -0.394289954 -0.059313397 1.100025372 0.763175748
## [41] -0.164523596 -0.253361680 0.696963375 0.556663199 -0.688755695
## [46] -0.707495157 0.364581962 0.768532925 -0.112346212 0.881107726
## [51] 0.398105880 -0.612026393 0.341119691 -1.129363096 1.433023702
## [56] 1.980399899 -0.367221476 -1.044134626 0.569719627 -0.135054604
## [61] 2.401617761 -0.039240003 0.689739362 0.028002159 -0.743273209
## [66] 0.188792300 -1.804958629 1.465554862 0.153253338 2.172611670
## [71] 0.475509529 -0.709946431 0.610726353 -0.934097632 -1.253633400
## [76] 0.291446236 -0.443291873 0.001105352 0.074341324 -0.589520946
## [81] -0.568668733 -0.135178615 1.178086997 -1.523566800 0.593946188
## [86] 0.332950371 1.063099837 -0.304183924 0.370018810 0.267098791
## [91] -0.542520031 1.207867806 1.160402616 0.700213650 1.586833455
## [96] 0.558486426 -1.276592208 -0.573265414 -1.224612615 -0.473400636
eps=rnorm(100, 0, sqrt(0.25))
eps
## [1] -0.310183339 0.021057937 -0.455460824 0.079014386 -0.327292322
## [6] 0.883643635 0.358353738 0.455087115 0.192092679 0.841088040
## [11] -0.317868227 -0.230822365 0.716141119 -0.325348177 -0.103690372
## [16] -0.196403965 -0.159996434 -0.139556651 0.247094166 -0.088665241
## [21] -0.252978731 0.671519413 -0.107289704 -0.089778265 -0.050095371
## [26] 0.356333154 -0.036782202 -0.018817086 -0.340830239 -0.162135136
## [31] 0.030080220 -0.294447243 0.265748096 -0.759197041 0.153278930
## [36] -0.768224912 -0.150488063 -0.264139952 -0.326047390 -0.028448389
## [41] -0.957179713 0.588291656 -0.832486218 -0.231765201 -0.557960053
## [46] -0.375409501 1.043583273 0.008697810 -0.643150265 -0.820302767
## [51] 0.225093551 -0.009279916 -0.159034187 -0.464681074 -0.743730155
## [56] -0.537596148 0.500014402 -0.310633347 -0.692213424 0.934645311
## [61] 0.212550189 -0.119323550 0.529241524 0.443211326 -0.309621524
## [66] 1.103051232 -0.127513515 -0.712247325 -0.072199801 0.103769170
## [71] 1.153989200 0.052901184 0.228499403 -0.038576468 -0.167000421
## [76] -0.017363014 0.393819803 1.037622504 0.513696219 0.603954199
## [81] -0.615661711 0.491947785 0.109962402 -0.733625015 0.260511371
## [86] -0.079377302 0.732293656 -0.383041000 -0.215105877 -0.463054749
## [91] -0.088551981 0.201005890 -0.365874087 0.415186584 -0.604041393
## [96] -0.523992206 0.720578853 -0.507923733 0.205987356 -0.190538026
y=-1+0.5*x + eps
y tiene una longitud de 100*\(b_{0}\) es -1, \(b_{1}\) es 0,5
plot(x,y)

FIGURA 4.1: relacion lineal entre x e y, con pendiente positiva.
lm=lm(y~x)
summary(lm)
##
## Call:
## lm(formula = y ~ x)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.93842 -0.30688 -0.06975 0.26970 1.17309
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.01885 0.04849 -21.010 < 2e-16 ***
## x 0.49947 0.05386 9.273 4.58e-15 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.4814 on 98 degrees of freedom
## Multiple R-squared: 0.4674, Adjusted R-squared: 0.4619
## F-statistic: 85.99 on 1 and 98 DF, p-value: 4.583e-15
Tenemos un contraste de hipótesis:
\(H_{0}: y = 0\) ; \(H_{1}: y =distinto 0\)
RSE = 0.481 ; \(R^2 ajust= 0.462\)
F= 86 grados; p-valor<< 0,00001 valor de p muy pequeño; por lo tanto podemos rechazar la hipótesis nula.
plot(x,y)
abline(-1, 0.5, lwd=3, col=3)
legend(-1, legend=c("modelo","regresión"), col=2:3, lwd=3)

FIGURA 4.2: Graficos de modelo y regresión de la variable dependiente y la variable independiente.
lm.sq=lm(y~x+I(x^2))
summary(lm.sq)
##
## Call:
## lm(formula = y ~ x + I(x^2))
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.98252 -0.31270 -0.06441 0.29014 1.13500
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.97164 0.05883 -16.517 < 2e-16 ***
## x 0.50858 0.05399 9.420 2.4e-15 ***
## I(x^2) -0.05946 0.04238 -1.403 0.164
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.479 on 97 degrees of freedom
## Multiple R-squared: 0.4779, Adjusted R-squared: 0.4672
## F-statistic: 44.4 on 2 and 97 DF, p-value: 2.038e-14
El modelo presenta un RSE un poco mejorado respecto al modelo inicial, aunque el p valor del estadistico sugiere que no hay relación entre y y \(x^2\)
set.seed(1)
eps1 = rnorm (100, 0, 0.125)
x1=rnorm(100)
y1=-1+0.5*x1+eps1
plot(x1,y1)
lm1=lm(y1~x1)
summary(lm1)
##
## Call:
## lm(formula = y1 ~ x1)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.29052 -0.07545 0.00067 0.07288 0.28664
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.98639 0.01129 -87.34 <2e-16 ***
## x1 0.49988 0.01184 42.22 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.1128 on 98 degrees of freedom
## Multiple R-squared: 0.9479, Adjusted R-squared: 0.9474
## F-statistic: 1782 on 1 and 98 DF, p-value: < 2.2e-16

FIGURA 4.3: con la modificación del modelo, podemos ver que disminuye la inclinación.
RSE = 0.1128 y \(R^2_{ajust} = 0.947\)
set.seed(1)
eps2=rnorm(100,0,0.5)
x2=rnorm(100)
y2=-1+0.5*x2+eps2
plot(x2,y2)
lm2=lm(y2~x2)
summary(lm2)
##
## Call:
## lm(formula = y2 ~ x2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.16208 -0.30181 0.00268 0.29152 1.14658
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.94557 0.04517 -20.93 <2e-16 ***
## x2 0.49953 0.04736 10.55 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.4514 on 98 degrees of freedom
## Multiple R-squared: 0.5317, Adjusted R-squared: 0.5269
## F-statistic: 111.2 on 1 and 98 DF, p-value: < 2.2e-16

FIGURA 4.4: El modelo y2, respecto a la variable x2, que vemos que aumenta considerablemente el error observado
RSE = 0.4514, aumento respecto al modelo anterior, y \(R^2_{ajust} = 0.5269\) , el ajuste es menos bueno.
confint(lm)
## 2.5 % 97.5 %
## (Intercept) -1.1150804 -0.9226122
## x 0.3925794 0.6063602
confint(lm1)
## 2.5 % 97.5 %
## (Intercept) -1.008805 -0.9639819
## x1 0.476387 0.5233799
confint(lm2)
## 2.5 % 97.5 %
## (Intercept) -1.0352203 -0.8559276
## x2 0.4055479 0.5935197
| x | 0,3926 | 0,6064 |
| x1 | 0,4764 | 0,5234 |
| x2 | 0,4055 | 0,5935 |
Los intervalos de cada uno de los modelos estan centrados en 0,5, siendo el modelo x1 el más pequeño.
set.seed(1)
x1=runif(100)
x2=0.5*x1+rnorm(100)/10
y=2+2*x1+0.3*x2+rnorm(100)
Modelo : \(y= 2 + 2*x1 + 0.3 x2 + \epsilon\)
\(b_{0}=2\) , \(b_{1}=2\), \(b_{3}=0.3\)
siendo y la variable dependiente.
cor(x1,x2)
## [1] 0.8351212
plot(x1,x2)
La Correlación = 0,8351

FIGURA 5.1.: Grafico de dispersión entre las variables x1 y x2. Correlación lineal positiva. relación directa entre las dos variables.
lm1=lm(y~x1+x2)
summary(lm1)
##
## Call:
## lm(formula = y ~ x1 + x2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.8311 -0.7273 -0.0537 0.6338 2.3359
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.1305 0.2319 9.188 7.61e-15 ***
## x1 1.4396 0.7212 1.996 0.0487 *
## x2 1.0097 1.1337 0.891 0.3754
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.056 on 97 degrees of freedom
## Multiple R-squared: 0.2088, Adjusted R-squared: 0.1925
## F-statistic: 12.8 on 2 and 97 DF, p-value: 1.164e-05
Los coeficientes del modelo son: \(b_{0}=2,1305; b_{1}= 1,4396; b_{2}=1,0097\)
Con un p-valor muy pequeño, menor \(alpha=0.05\), podemos rechazar la hipótesis nula para \(b_{1}\) es p-valor= 0,0487, pero para una hipotesis nula de \(b_{2}\) tiene un p-valor= 0,3754 no rechazamos la hipotesis nula.
lm.x1=lm(y~x1)
summary(lm.x1)
##
## Call:
## lm(formula = y ~ x1)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.89495 -0.66874 -0.07785 0.59221 2.45560
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.1124 0.2307 9.155 8.27e-15 ***
## x1 1.9759 0.3963 4.986 2.66e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.055 on 98 degrees of freedom
## Multiple R-squared: 0.2024, Adjusted R-squared: 0.1942
## F-statistic: 24.86 on 1 and 98 DF, p-value: 2.661e-06
Con un modelo: y= x1
Si podemos rechazar la hipotesis nula, dado que el p-valor es casi 0.
lm.x2=lm(y~x2)
summary(lm.x2)
##
## Call:
## lm(formula = y ~ x2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.62687 -0.75156 -0.03598 0.72383 2.44890
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.3899 0.1949 12.26 < 2e-16 ***
## x2 2.8996 0.6330 4.58 1.37e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.072 on 98 degrees of freedom
## Multiple R-squared: 0.1763, Adjusted R-squared: 0.1679
## F-statistic: 20.98 on 1 and 98 DF, p-value: 1.366e-05
\(H_{0}: B{2}=0\)
Con un modelo: y =x1
\(b_{2}= 2,8996\)
p-valor= 0,0000137, valor muy pequeño
RSE= 1,072. Rechazamos la hipotesis nula.
Tenemos que las variables de forma independiente tienen una relación lineal con la variable dependiente, de forma conjunta la correlación no nos permite verlo con tanta claridad.
x1=c(x1, 0.1)
x2=c(x2, 0.8)
y=c(y,6)
lm3=lm(y~x1+x2)
summary(lm3)
##
## Call:
## lm(formula = y ~ x1 + x2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.73348 -0.69318 -0.05263 0.66385 2.30619
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.2267 0.2314 9.624 7.91e-16 ***
## x1 0.5394 0.5922 0.911 0.36458
## x2 2.5146 0.8977 2.801 0.00614 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.075 on 98 degrees of freedom
## Multiple R-squared: 0.2188, Adjusted R-squared: 0.2029
## F-statistic: 13.72 on 2 and 98 DF, p-value: 5.564e-06
lm4=lm(y~x1)
summary(lm4)
##
## Call:
## lm(formula = y ~ x1)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.8897 -0.6556 -0.0909 0.5682 3.5665
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.2569 0.2390 9.445 1.78e-15 ***
## x1 1.7657 0.4124 4.282 4.29e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.111 on 99 degrees of freedom
## Multiple R-squared: 0.1562, Adjusted R-squared: 0.1477
## F-statistic: 18.33 on 1 and 99 DF, p-value: 4.295e-05
lm5=lm(y~x2)
summary(lm5)
##
## Call:
## lm(formula = y ~ x2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.64729 -0.71021 -0.06899 0.72699 2.38074
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.3451 0.1912 12.264 < 2e-16 ***
## x2 3.1190 0.6040 5.164 1.25e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.074 on 99 degrees of freedom
## Multiple R-squared: 0.2122, Adjusted R-squared: 0.2042
## F-statistic: 26.66 on 1 and 99 DF, p-value: 1.253e-06
par(mfrow=c(2,2))
plot(lm3)
par(mfrow=c(2,2))
plot(lm4)
par(mfrow=c(2,2))
plot(lm5)

FIGURA 5.2: Graficos del modelo y=x1+x2

FIGURA 5.3: Graficos del modelo y=x1

FIGURA 5.4: Gráfico del modelo y=x2
library(boot)
library(ISLR2)
alpha.fn<- function(data, index){
X<-data$X[index]
Y<-data$Y[index]
(var(Y)-cov(X,Y))/(var(X)+var(Y)-2*cov(X,Y))
}
# semilla que generamos
set.seed(7)
alpha.fn(Portfolio, sample(100, 100, replace=T))
## [1] 0.5385326
alpha.fn(Portfolio, 1:100)
## [1] 0.5758321
# Estimacion error standar utilizando bootstrap
boot(Portfolio, alpha.fn, R=1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Portfolio, statistic = alpha.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 0.5758321 0.0007959475 0.08969074
bootstrap_ci <- function(reg, B, Nivel) {
m <- length(coef(reg))
results <- matrix(0, nrow = m, ncol = 3)
for (i in 1:m) {
coef_est <- coef(reg)[i]
bootstrap_est <- numeric(B)
for (j in 1:B) {
bootstrap_data <- reg$data[sample(nrow(reg$data), replace = TRUE), ]
bootstrap_reg <- lm(reg$call$formula, data = bootstrap_data, x = reg$x, y = reg$y)
bootstrap_est[j] <- coef(bootstrap_reg)[i]
}
ci_lower <- quantile(bootstrap_est, 0.5 - Nivel/2)
ci_upper <- quantile(bootstrap_est, 0.5 + Nivel/2)
std_error <- sd(bootstrap_est)
# Almacenar los resultados en la matriz
results[i, ] <- c(std_error, ci_lower, ci_upper)
}
# Imprimir el nivel de los intervalos de confianza calculados
cat("Nivel de los intervalos de confianza calculados:", Nivel, "\n")
# Devolver los resultados
return(results)
}
Bootstrap Statistics : original bias std. error
t1* 0.5758321 0.0007959475 0.08969074
Tabla 6.1.: Resultado del error estandar para el coeficiente de regresión
datos<- read.table("Facturacion.txt", header= TRUE)
modelos<- lm(Facturacion ~Inversion + I(Inversion^2), data=datos)
resumen_modelo<- summary(modelos)
errorst<- resumen_modelo$coef[, 2]
print(errorst)
## (Intercept) Inversion I(Inversion^2)
## 1.10666176 0.61107435 0.07416026
(Intercept) Inversion I(Inversion^2)
1.10666176 0.61107435 0.07416026
Tabla 7.1: Tabla del error estandar del coeficiente por mínimos cuadrados del archivo Facturación.
confianza<- 0.95
intervalos<- confint(modelos, level = confianza)
summary (modelos)
##
## Call:
## lm(formula = Facturacion ~ Inversion + I(Inversion^2), data = datos)
##
## Residuals:
## Min 1Q Median 3Q Max
## -8.541 -1.881 -0.223 1.849 7.402
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 300.85987 1.10666 271.863 < 2e-16 ***
## Inversion 2.42894 0.61107 3.975 9.88e-05 ***
## I(Inversion^2) 1.57550 0.07416 21.245 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.047 on 197 degrees of freedom
## Multiple R-squared: 0.9878, Adjusted R-squared: 0.9877
## F-statistic: 8005 on 2 and 197 DF, p-value: < 2.2e-16
print (intervalos)
## 2.5 % 97.5 %
## (Intercept) 298.677446 303.042295
## Inversion 1.223851 3.634025
## I(Inversion^2) 1.429252 1.721751
2.5 % 97.5 %
(Intercept) 298.677446 303.042295
Inversion 1.223851 3.634025
I(Inversion^2) 1.429252 1.721751
Tabla 7.2: Tabla de Intervalos de Confianza al nivel 0.95% para el modelo cuadrático.
library(MASS)
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08205 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio lstat
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 1.73
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.: 6.95
## Median : 5.000 Median :330.0 Median :19.05 Median :11.36
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :12.65
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:16.95
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :37.97
## medv
## Min. : 5.00
## 1st Qu.:17.02
## Median :21.20
## Mean :22.53
## 3rd Qu.:25.00
## Max. :50.00
set.seed(1)
attach(Boston)
#media
medv.mean=mean(medv)
medv.mean
## [1] 22.53281
Estimación de la media poblacional= 22,53
medv.err = sd(medv)/sqrt(length(medv))
medv.err
## [1] 0.4088611
Error estandar = 0.4088611
boot.1=function(data,index) return(mean(data[index]))
library(boot)
bstrap=boot(medv, boot.1, 1000)
bstrap
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot.1, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.007650791 0.4106622
Bootstrap Statistics : original bias std. error t1*
22.53281 0.007650791 0.4106622
Tabla 8.1: Estimadores del error estandar de la estimacion de la media el bootstrap.
El Error standar es muy similar al del apartado b.
t.test(medv)
##
## One Sample t-test
##
## data: medv
## t = 55.111, df = 505, p-value < 2.2e-16
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
## 21.72953 23.33608
## sample estimates:
## mean of x
## 22.53281
c(bstrap$t0 - 2*0.4119,bstrap$t0+2*0.4119)
## [1] 21.70901 23.35661
Intervalo Confianza 95% ( 21.70901 , 23.35661)
Estimación mediana = 21.2
medv.med = median(medv)
medv.med
## [1] 21.2
boot.2=function(data,index) return(median(data[index]))
boot(medv,boot.2,1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot.2, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 -0.0386 0.3770241
Bootstrap Statistics : original bias std. error
t1* 21.2 -0.0386 0.3770241
Tabla 8.2: Estimador del error estandar del bootstrap
La Mediana es 21,2
El error standar es 0,3770241
medv.10 = quantile(medv, c(0.1))
medv.10
## 10%
## 12.75
10% 12.75
boot.10 = function(data, index) return(quantile(data[index], c(0.1)))
boot(medv,boot.10,1000)
##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = medv, statistic = boot.10, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.0186 0.4925766
Bootstrap Statistics : original bias std. error
t1* 12.75 0.0186 0.4925766
Tabla 8.3: Estimador del error estandar usando bootstrap.
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
##
## Attaching package: 'lattice'
## The following object is masked from 'package:boot':
##
## melanoma
library(class)
datos <- read.table("Facturacion.txt", header = TRUE)
top_data=head(datos)
knitr::kable(top_data, caption="Tabla 9.1. Seis primeras filas del fichero *Facturacion.txt*.")
| Facturacion | Inversion |
|---|---|
| 347.0013 | 4.984389 |
| 349.1075 | 4.998096 |
| 350.8726 | 4.662743 |
| 378.8111 | 6.428102 |
| 379.3420 | 6.247677 |
| 311.3389 | 1.993349 |
names(datos)=c("x","y")
x.lab=c("Inversion")
y.lab=c("Facturacion")
par(mfrow=c(1,1))
plot(y~x ,data=datos, pch=19, xlab=x.lab, ylab=y.lab, cex.lab=1.5, maim="")
## Warning in plot.window(...): "maim" is not a graphical parameter
## Warning in plot.xy(xy, type, ...): "maim" is not a graphical parameter
## Warning in axis(side = side, at = at, labels = labels, ...): "maim" is not a
## graphical parameter
## Warning in axis(side = side, at = at, labels = labels, ...): "maim" is not a
## graphical parameter
## Warning in box(...): "maim" is not a graphical parameter
## Warning in title(...): "maim" is not a graphical parameter
x.vec=seq(10,80,length=1000)
legend("topleft","Funcion de regresión verdadera",lty=1,col="red",lwd=2,cex=1.5)

Figura 9.1: Representación gráfica de la función de regresión verdadera.
reg1knn=knnreg(y~x, data=datos, k=1)
reg5knn=knnreg(y~x, data=datos, k=5)
reg10knn=knnreg(y~x, data=datos, k=10)
reg50knn=knnreg(y~x, data=datos, k=50)
x.vec2=x=seq(10,100,length=1000)
New.data=data.frame(x=x.vec2)
par(mfrow=c(2,2))
plot(y~x,data=datos, pch = 19,xlab=x.lab,ylab=y.lab,cex.lab=1.5,main="KNN, K=1")
plot(y~x,data=datos, pch = 19,xlab=x.lab,ylab=y.lab,main="KNN, K=5")
plot(y~x,data=datos, pch = 19,xlab=x.lab,ylab=y.lab,main="KNN, K=10")
plot(y~x,data=datos, pch = 19,xlab=x.lab,ylab=y.lab,main="KNN, K=50")

Figura 9.2: Datos y función de regresión estimada con el método KNN para distintos valores de k.
En cada uno de los casos las curvas son muy similares, aunque podemos dislumbrarque es un poco más amplia segun aumenta, el tamaño de la muestra no permite apreciar detalles de la variación.
predict(reg1knn,data.frame(x=c(5)))
## [1] 1.14185
predict(reg5knn,data.frame(x=c(5)))
## [1] 1.178188
predict(reg10knn,data.frame(x=c(5)))
## [1] 1.229829
predict(reg50knn,data.frame(x=c(5)))
## [1] 1.737756
| Método k | Predicción |
|---|---|
| k=1 | 1.14185 |
| k=5 | 1.178188 |
| k=10 | 1.229829 |
| k=50 | 1.737756 |
Tabla 9.1: Tabla donde se recoge la predicción de la media anual con una inversion de 5 millones en los 4 modelos estimados.
Este ese el planteamiento en R.
R2_modelos=c(summary.reg1knn\(r.squared, summary.reg5knn\)r.squared, summary.reg10knn\(r.squared, summary.reg50knn\)r.squared)
MSE_modelos=c(mean((reg1knn\(fitted-Facturacion\)Inversion)^2), mean((reg5knn\(fitted-Facturacion\)Inversion)^2), mean((reg10knn\(fitted-Facturacion\)Inversion)^2), mean((reg50knn\(fitted-Facturacion\)Inversion)^2))
MAE_modelos=c(mean(abs(reg1knn\(fitted-Facturacion\)Inversion)), mean(abs(reg5knn\(fitted-Facturacion\)Inversion)), mean(abs(reg10knn\(fitted-Facturacion\)Inversion)), mean(abs(reg50knn\(fitted-Facturacion\)Inversion)))