CONSEGNA

Si considerino i dati \(kc_house_data\) relativi a vendite di abitazioni e si analizzi la relazione tra price e sqft_living tenendo conto, ove ritenuto necessario delle altre caratteristiche delle case. L’obiettivo della seguente analisi è quindi quello di evidenziare delle possibili relazioni tra grandezze mediante la costruzione di un modello di regressione.

IMPORTAZIONE DATI

Importazione e rappresentazione dati:

# dati presi da moodle
load("dati.Rdata")
df<-kc_house_data
attach(df)
tail(df)
##               id       date  price bedrooms bathrooms sqft_living sqft_lot
## 21592 2997800021  2/19/2015 475000        3      2.50        1310     1294
## 21593  263000018  5/21/2014 360000        3      2.50        1530     1131
## 21594 6600060120  2/23/2015 400000        4      2.50        2310     5813
## 21595 1523300141  6/23/2014 402101        2      0.75        1020     1350
## 21596  291310100  1/16/2015 400000        3      2.50        1600     2388
## 21597 1523300157 10/15/2014 325000        2      0.75        1020     1076
##       floors waterfront view condition grade sqft_above sqft_basement yr_built
## 21592      2          0    0         3     8       1180           130     2008
## 21593      3          0    0         3     8       1530             0     2009
## 21594      2          0    0         3     8       2310             0     2014
## 21595      2          0    0         3     7       1020             0     2009
## 21596      2          0    0         3     8       1600             0     2004
## 21597      2          0    0         3     7       1020             0     2008
##       yr_renovated zipcode     lat     long sqft_living15 sqft_lot15
## 21592            0   98116 47.5773 -122.409          1330       1265
## 21593            0   98103 47.6993 -122.346          1530       1509
## 21594            0   98146 47.5107 -122.362          1830       7200
## 21595            0   98144 47.5944 -122.299          1020       2007
## 21596            0   98027 47.5345 -122.069          1410       1287
## 21597            0   98144 47.5941 -122.299          1020       1357
summary(df)
##        id                date               price            bedrooms     
##  Min.   :1.000e+06   Length:21597       Min.   :  78000   Min.   : 1.000  
##  1st Qu.:2.123e+09   Class :character   1st Qu.: 322000   1st Qu.: 3.000  
##  Median :3.905e+09   Mode  :character   Median : 450000   Median : 3.000  
##  Mean   :4.580e+09                      Mean   : 540297   Mean   : 3.373  
##  3rd Qu.:7.309e+09                      3rd Qu.: 645000   3rd Qu.: 4.000  
##  Max.   :9.900e+09                      Max.   :7700000   Max.   :33.000  
##    bathrooms      sqft_living       sqft_lot           floors     
##  Min.   :0.500   Min.   :  370   Min.   :    520   Min.   :1.000  
##  1st Qu.:1.750   1st Qu.: 1430   1st Qu.:   5040   1st Qu.:1.000  
##  Median :2.250   Median : 1910   Median :   7618   Median :1.500  
##  Mean   :2.116   Mean   : 2080   Mean   :  15099   Mean   :1.494  
##  3rd Qu.:2.500   3rd Qu.: 2550   3rd Qu.:  10685   3rd Qu.:2.000  
##  Max.   :8.000   Max.   :13540   Max.   :1651359   Max.   :3.500  
##    waterfront            view          condition        grade       
##  Min.   :0.000000   Min.   :0.0000   Min.   :1.00   Min.   : 3.000  
##  1st Qu.:0.000000   1st Qu.:0.0000   1st Qu.:3.00   1st Qu.: 7.000  
##  Median :0.000000   Median :0.0000   Median :3.00   Median : 7.000  
##  Mean   :0.007547   Mean   :0.2343   Mean   :3.41   Mean   : 7.658  
##  3rd Qu.:0.000000   3rd Qu.:0.0000   3rd Qu.:4.00   3rd Qu.: 8.000  
##  Max.   :1.000000   Max.   :4.0000   Max.   :5.00   Max.   :13.000  
##    sqft_above   sqft_basement       yr_built     yr_renovated    
##  Min.   : 370   Min.   :   0.0   Min.   :1900   Min.   :   0.00  
##  1st Qu.:1190   1st Qu.:   0.0   1st Qu.:1951   1st Qu.:   0.00  
##  Median :1560   Median :   0.0   Median :1975   Median :   0.00  
##  Mean   :1789   Mean   : 291.7   Mean   :1971   Mean   :  84.46  
##  3rd Qu.:2210   3rd Qu.: 560.0   3rd Qu.:1997   3rd Qu.:   0.00  
##  Max.   :9410   Max.   :4820.0   Max.   :2015   Max.   :2015.00  
##     zipcode           lat             long        sqft_living15 
##  Min.   :98001   Min.   :47.16   Min.   :-122.5   Min.   : 399  
##  1st Qu.:98033   1st Qu.:47.47   1st Qu.:-122.3   1st Qu.:1490  
##  Median :98065   Median :47.57   Median :-122.2   Median :1840  
##  Mean   :98078   Mean   :47.56   Mean   :-122.2   Mean   :1987  
##  3rd Qu.:98118   3rd Qu.:47.68   3rd Qu.:-122.1   3rd Qu.:2360  
##  Max.   :98199   Max.   :47.78   Max.   :-121.3   Max.   :6210  
##    sqft_lot15    
##  Min.   :   651  
##  1st Qu.:  5100  
##  Median :  7620  
##  Mean   : 12758  
##  3rd Qu.: 10083  
##  Max.   :871200
library(leaflet)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
colors<-c("yellow","red")
pal<-colorFactor(colors,price)
dfPopup<-df%>%mutate(popup_info=paste("Prezzo della casa: ",price," $","</br>", "Piedratura del soggiorno: ",sqft_living,"</br>","Piedratura del seminterrato: ",sqft_basement,"</br>","Piedratura del lotto: ",sqft_lot,"</br>","Numero di piani : ",floors,"</br>","Numero di bagni per camera: ",bathrooms,"</br>","Numero di camere: ",bedrooms,"</br>","Vista sull'acqua: ",waterfront,"</br>","Data di vendita dell'immobile: ",date,"</br>","Numero di visite: ",view,"</br>","Valutazione: ",grade," ",condition,"</br>","Coordinate: ",lat," ",long,"</br>","Anno di costruzione: ",yr_built,"</br>","Anno del restauro: ",yr_renovated,"</br>"))
leaflet()%>%addTiles()%>%addCircleMarkers(data=dfPopup,lat= ~lat,lng= ~long, radius=~1,color=~pal(price),popup=~popup_info)

DESCRIZIONE DEL DATASET

Il seguente documento tratta l’analisi statistica delle relazioni tra variabili relative ad un dataset composto da 21597 osservazioni (per 21 variabili) relative alle case vendute tra il Maggio 2014 ed il Maggio 2015, nella contea di King, stato di Washington (USA). Si noti che questi dati solo parzialmente la città di Seattle.

Breve descrizione delle 21 variabili (Data type):

Come conseguenza della presenza della variabile \(grade\) nel dataset, basata su un sistema di classificazione specifico per King County, sembra probabile che i dati provengano da una fonte ufficiale. Il fatto invece che sia annessa la variabile \(view\) ci dà un’indicazione sulla provenienza dei dati, suggerendoci che è probabile che i dati provengano da un’ agenzia/società immobiliare. In ogni caso, non c’è alcun motivo per mettere in discussione l’accuratezza generale relativa alla provenienza dei dati, in quanto variabili come prezzi, area ecc. non sembrano essere stati generati randomicamente. Anche per questa ragione, si reputa consono seguire un approccio cauto prima di applicare modelli basati su questo dataset a casi più generali.

PRIMA PARTE

Analizzare la relazione tra la variabile risposta price e la covariata sqft_living

SCELTA DELLA VARIABILE RISPOSTA

Per la scelta della variabile risposta il percorso è imposto, va utilizzata la var. price, ma vanno considerati i seguenti accorgimenti per l’assunzione sul modello parametrico da utilizzare: - Per la costruzione di un modello di regressione lineare, condizione necessaria è che la variabile risposta sia una variabile quantitativa continua con distribuzione normale; - Per un modello glm gamma la var. risposta deve essere quantitativa continua con supporto in R+ e deve assumere la forma funzionale per il glm gamma.

(vedremo in seguito perchè proprio glm gamma)

Per arrivare ai seguenti risultati ci arriveremo tramite delle trasformazioni.

ANALISI ESPLORATIVA DEI DATI

Price variabile quantitativa, riscaliamo la variabile price dividendola per 10^5 per renderla più comprabile in termine di effetto con l’altra variabile.

require(moments)
## Loading required package: moments
summary(price/(10^5))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   0.780   3.220   4.500   5.403   6.450  77.000
# asimmetria positiva o a destra
skewness(price/(10^5))
## [1] 4.023085
hist(price/(10^5),prob=T,breaks=200)

Guardando l’istogramma potremmo pensare di assumere un modello parametrico di tipo gamma per la variabile risposta.

hist(price/(10^5),prob=T,breaks=200)
# i valori sono stati messi casualmente perchè non si ha ancora il modello definitivo
curve(dgamma(x,median(price/(10^5))-0,2.3*(1/(median(price/(10^5))-2.03))),col="red",lwd=2,add=T)

Proviamo ora a seguire un approccio alternativo, consideriamo la trasformazione logaritmica della var. risposta per cercare di risolvere il problema di asimmetria:

# proviamo ora a vedere se riusciamo in alternativa a traformarla per renderla circa normale per stimarci un LM

# lavoriamo sull'asimmetria
c(mean(price/(10^5)),median(price/(10^5)))
## [1] 5.402966 4.500000
c(mean(log(price)),median(log(price)))
## [1] 13.04821 13.01700
# notiamo che la skewness si riduce quasi a zero con la trasformazine logaritmica
c(skewness(price/(10^5)),skewness(log(price)))
## [1] 4.0230852 0.4309742
# qui non serve più dividere per 10^5 per riproporzionare le scale perchè il logaritmo sciaccia già a 0 i valori

# lavoriamo sull'Hp. di normalità
summary(log(price))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   11.26   12.68   13.02   13.05   13.38   15.86
# ha le code leggermente troppo pesanti, potremmo ritrovare questo problema in seguito nel modello lm
c(kurtosis(log(price)),kurtosis(rnorm(length(price))))
## [1] 3.690611 2.990063
# lavoriamo sul confronto della funzione di densità
hist(log(price),prob=T,breaks=100)
curve(dnorm(x,mean(log(price)),sd(log(price))),col="blue",lwd=2,add=T)

# testiamo l'Hp. di normalità con degli opportuni test
# il test ks.test potrebbe funzionare meglio in questo caso data l'alta numerosità campionaria
ks.test(log(price),mean(log(price)),sd(log(price)))
## Warning in ks.test.default(log(price), mean(log(price)), sd(log(price))):
## Parameter(s) ignored
## Warning in ks.test.default(log(price), mean(log(price)), sd(log(price))):
## p-value will be approximate in the presence of ties
## 
##  Asymptotic two-sample Kolmogorov-Smirnov test
## 
## data:  log(price) and mean(log(price))
## D = 0.52104, p-value = 0.9489
## alternative hypothesis: two-sided

Concludiamo che la trasformazione logaritmica sembra normalizzare i dati ma non perfettamente. Entrambi i test ci portano ad accettare con una buona significatività l’Hp di normalità.

STUDIO DELLA RELAZIONE CON LA VARIABILE SQFT_LIVING

Analisi della variabile sqft_living

# in termini di relazione lineare la trasformazione più logica è il logaritmo perchè elimina la asimmetria destra e gli da una forma più a campana
c(skewness(sqft_living),skewness(log(sqft_living)))
## [1]  1.47311313 -0.02736007
c(kurtosis(sqft_living),kurtosis(log(sqft_living)))
## [1] 8.250608 2.920702
par(mfrow=c(2,1))
hist(sqft_living,prob=T,breaks=100, xlim = c(0,6000))
hist(log(sqft_living),prob=T,breaks=100)

Studio sulla relazione tra variabili MODELLO LM SEMPLICE

Relazione tra la variabile quantitative e variabile risposta mediante il diagramma di dispersione:

Trasformiamo opportunamente la variabile risposta sqft_living tramite una trasformazione logaritmica per ottenere una relazione più lineare possibile con log(price)

Testiamola la prima soluzione in termini grafici:

cor(log(price),log(sqft_living))
## [1] 0.6748017
# questa relazione sembra tenere le Hp. di linearità ed omoschedasticità dell'LM
plot(log(price)~log(sqft_living),pch=20,xlab="log(sqft_living)", ylab="log(price)", main = "Diagramma di dispersione")

La correlazione positiva sembra confermata dal diagramma di dispersione. Sia l’Hp. di linearità che l’Hp. di omoschedasticità sembrano tenere.

Studio sulla relazione tra variabili MODELLO GLM GAMMA

Trasformiamo opportunamente la variabile risposta sqft_living tramite una trasformazione di scala per ottenere una relazione più lineare possibile con price(10^5).

Testiamola la seconda soluzione in termini grafici:

cor(price/(10^5),sqft_living/(10^3))
## [1] 0.7019173
# questa relazione sembra tenere le Hp. di linearità ed omoschedasticità dell'LM
plot(I(price/(10^5))~I(sqft_living/(10^3)),pch=20,xlab="sqft_living/(10^5)", ylab="price/(10^3)", main = "Diagramma di dispersione")

La correlazione positiva sembra confermata dal diagramma di dispersione. Sembra essere una relazione funzionale tra media e varianza, questo ci fa supporre la necessità di modellare tale relazione tramite un glm.

STIMA DEL MODELLO LM e ANALISI DEI RESIDUI:

Stiamiamo un modello lineare semplice che provi a testare la relazione tra le var.:

fit_LM<-lm(log(price)~log(sqft_living))
summary(fit_LM)
## 
## Call:
## lm(formula = log(price) ~ log(sqft_living))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.10468 -0.29290  0.01251  0.25683  1.32823 
## 
## Coefficients:
##                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      6.723413   0.047145   142.6   <2e-16 ***
## log(sqft_living) 0.837642   0.006234   134.4   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3886 on 21595 degrees of freedom
## Multiple R-squared:  0.4554, Adjusted R-squared:  0.4553 
## F-statistic: 1.805e+04 on 1 and 21595 DF,  p-value: < 2.2e-16

I coefficienti stimati sono significativi, mentre R quadro è ancora molto basso.

Rappresentazione grafica del modello stimato per la media:

require(ggplot2)
## Loading required package: ggplot2
require(smooth)
## Loading required package: smooth
## Loading required package: greybox
## Package "greybox", v1.0.8 loaded.
## This is package "smooth", v3.2.0
plot(ggplot(df,aes(x=log(sqft_living),y=log(price)))+geom_point()+geom_smooth(method='lm'))
## `geom_smooth()` using formula = 'y ~ x'

Sembra stimare abbastanza bene la relazione tra le due variabili, ma non perfettamente.

Analisi dei residui:

plot(fit_LM)

# testiamo l'Hp. di normalità dei residui
hist(rstandard(fit_LM),probability = T, breaks=100, xlab="Model's standardized residuals", main="Histogram of model's standardized residuals")
curve(dnorm(x,0,1),add=T)

# test che sembra più ragionevole
ks.test(rstandard(fit_LM),rnorm(length(price),0,1))
## Warning in ks.test.default(rstandard(fit_LM), rnorm(length(price), 0, 1)):
## p-value will be approximate in the presence of ties
## 
##  Asymptotic two-sample Kolmogorov-Smirnov test
## 
## data:  rstandard(fit_LM) and rnorm(length(price), 0, 1)
## D = 0.026578, p-value = 4.738e-07
## alternative hypothesis: two-sided
# rifiutiamo l'Hp. di normalità dei residui

L’assunzione di omoschedasticità non sembra sussistere per valori estremi, si nota un comportamento di fondo nella varianza del modello.

Anche l’Hp. di normalità dei residui non tiene, lo conferma il test K.-S. sui residui.

Concludiamo che il modello LM stimato non va bene per descrivere la relazione tra price e sqft_living.

PROVIAMO CON UN RELAZIONE CON UN POLINOMIO DI SECONDO GRADO:

Stiamiamo un modello lineare semplice che provi a testare la relazione tra le var.:

fit_LM_Quadratico<-lm(log(price)~log(sqft_living)+I(log(sqft_living)^2))
summary(fit_LM_Quadratico)
## 
## Call:
## lm(formula = log(price) ~ log(sqft_living) + I(log(sqft_living)^2))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.40115 -0.28422  0.01252  0.25854  1.24906 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)           27.43456    0.58694   46.74   <2e-16 ***
## log(sqft_living)      -4.66986    0.15572  -29.99   <2e-16 ***
## I(log(sqft_living)^2)  0.36498    0.01031   35.40   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3778 on 21594 degrees of freedom
## Multiple R-squared:  0.4852, Adjusted R-squared:  0.4852 
## F-statistic: 1.018e+04 on 2 and 21594 DF,  p-value: < 2.2e-16
# miglioramento significativo
anova(fit_LM,fit_LM_Quadratico)
## Analysis of Variance Table
## 
## Model 1: log(price) ~ log(sqft_living)
## Model 2: log(price) ~ log(sqft_living) + I(log(sqft_living)^2)
##   Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
## 1  21595 3261.2                                  
## 2  21594 3082.3  1    178.83 1252.8 < 2.2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

I coefficienti stimati sono significativi, mentre R quadro è ancora molto basso (benchè migliori rispetto al caso precedente).

Sembra stimare abbastanza bene la relazione tra le due variabili, ma non perfettamente.

Analisi dei residui:

plot(fit_LM_Quadratico)

# testiamo l'Hp. di normalità dei residui
hist(rstandard(fit_LM_Quadratico),probability = T, breaks=100, xlab="Model's standardized residuals", main="Histogram of model's standardized residuals")
curve(dnorm(x,0,1),add=T)

# test che sembra più ragionevole
ks.test(rstandard(fit_LM_Quadratico),rnorm(length(price),0,1))
## Warning in ks.test.default(rstandard(fit_LM_Quadratico), rnorm(length(price), :
## p-value will be approximate in the presence of ties
## 
##  Asymptotic two-sample Kolmogorov-Smirnov test
## 
## data:  rstandard(fit_LM_Quadratico) and rnorm(length(price), 0, 1)
## D = 0.025837, p-value = 1.096e-06
## alternative hypothesis: two-sided
# rifiutiamo l'Hp. di normalità dei residui

Il problema nell’assunzione di omoschedasticità sembra essere stato risolto dall’aggiunta dell’effetto parabolico, non si nota un comportamento di fondo nella varianza del modello.

Anche l’Hp. di normalità dei residui invece non tiene ancora, lo conferma il test K.-S. sui residui.

Concludiamo che il modello LM stimato con l’effetto quadrato risolve il problema di eteroschedasticità ma non va bene per descrivere la relazione tra price e sqft_living perchè R quadro corretto è ancora troppo basso e i residui non sembrano avere distribuzione normale.

TOGLIAMO IL PUNTO LEVA

Stiamiamo un modello lineare semplice che provi a testare la relazione tra le var.:

fit_LM_Quadratico_noLeva<-lm(log(price)[-12765]~log(sqft_living)[-12765]+I(log(sqft_living)^2)[-12765])
summary(fit_LM_Quadratico_noLeva)
## 
## Call:
## lm(formula = log(price)[-12765] ~ log(sqft_living)[-12765] + 
##     I(log(sqft_living)^2)[-12765])
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.25942 -0.28453  0.01251  0.25873  1.24854 
## 
## Coefficients:
##                               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                   27.65055    0.58961   46.90   <2e-16 ***
## log(sqft_living)[-12765]      -4.72800    0.15645  -30.22   <2e-16 ***
## I(log(sqft_living)^2)[-12765]  0.36888    0.01036   35.60   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3777 on 21593 degrees of freedom
## Multiple R-squared:  0.4853, Adjusted R-squared:  0.4853 
## F-statistic: 1.018e+04 on 2 and 21593 DF,  p-value: < 2.2e-16
# miglioramento significativo
AIC(fit_LM_Quadratico,fit_LM_Quadratico_noLeva)
## Warning in AIC.default(fit_LM_Quadratico, fit_LM_Quadratico_noLeva): models are
## not all fitted to the same number of observations
##                          df      AIC
## fit_LM_Quadratico         4 19251.14
## fit_LM_Quadratico_noLeva  4 19237.34

I coefficienti stimati sono significativi, mentre R quadro è ancora molto basso. Il secondo modello, secondo AIC, sembra leggermente migliore rispetto al precedente.

Sembra stimare abbastanza bene la relazione tra le due variabili, ma non perfettamente.

Analisi dei residui:

plot(fit_LM_Quadratico_noLeva)

# testiamo l'Hp. di normalità dei residui
hist(rstandard(fit_LM_Quadratico_noLeva),probability = T, breaks=100, xlab="Model's standardized residuals", main="Histogram of model's standardized residuals")
curve(dnorm(x,0,1),add=T)

# test che sembra più ragionevole
ks.test(rstandard(fit_LM_Quadratico_noLeva),rnorm(length(price),0,1))
## Warning in ks.test.default(rstandard(fit_LM_Quadratico_noLeva),
## rnorm(length(price), : p-value will be approximate in the presence of ties
## 
##  Asymptotic two-sample Kolmogorov-Smirnov test
## 
## data:  rstandard(fit_LM_Quadratico_noLeva) and rnorm(length(price), 0, 1)
## D = 0.021635, p-value = 8.142e-05
## alternative hypothesis: two-sided
# rifiutiamo l'Hp. di normalità dei residui

Concludiamo il miglior modello LM stimato è \(fit\)\(_\)\(LM\)\(_\)\(Quadratico\)\(_\)\(noLeva\). Ricordiamo che tale modello però non va bene per descrivere la relazione tra price e sqft_living perchè R quadro corretto è ancora troppo basso e i residui non sembrano avere distribuzione normale.

confronto tra i 3 modelli

AIC(fit_LM,fit_LM_Quadratico,fit_LM_Quadratico_noLeva)
## Warning in AIC.default(fit_LM, fit_LM_Quadratico, fit_LM_Quadratico_noLeva):
## models are not all fitted to the same number of observations
##                          df      AIC
## fit_LM                    3 20467.12
## fit_LM_Quadratico         4 19251.14
## fit_LM_Quadratico_noLeva  4 19237.34
BIC(fit_LM,fit_LM_Quadratico,fit_LM_Quadratico_noLeva)
## Warning in BIC.default(fit_LM, fit_LM_Quadratico, fit_LM_Quadratico_noLeva):
## models are not all fitted to the same number of observations
##                          df      BIC
## fit_LM                    3 20491.07
## fit_LM_Quadratico         4 19283.07
## fit_LM_Quadratico_noLeva  4 19269.26

Il modello migliora significativamente con l’aggiunta dell’effetto parabolico/quadratico.

MODELLO GLM GAMMA

Testiamo il possibile modello per le variabili riscalate non trasformate:

fit_Gamma<-glm(I(price/(10^5))~I(sqft_living/(10^3)),data=df,family=Gamma(link="log"))
summary(fit_Gamma)
## 
## Call:
## glm(formula = I(price/(10^5)) ~ I(sqft_living/(10^3)), family = Gamma(link = "log"), 
##     data = df)
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)           0.762975   0.006619   115.3   <2e-16 ***
## I(sqft_living/(10^3)) 0.405759   0.002911   139.4   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for Gamma family taken to be 0.1542546)
## 
##     Null deviance: 6550.9  on 21596  degrees of freedom
## Residual deviance: 3101.3  on 21595  degrees of freedom
## AIC: 86213
## 
## Number of Fisher Scoring iterations: 4

I coefficienti sono significativi e il modello rispetto al modello nullo è significativo.

Analisi dei residui:

plot(fit_Gamma)

# gli standard error sono alti ma perchè ho tante osservazioni

Il grafico del qq-plot ci mostra che l’assunzione di normalità dei residui non è rispettata, notiamo forte asimmetria dx/pos. nel qq-plot per i residui (come riscontrato in precedenza nei dati).

Il modello non sembra rappresentare bene in termini di omoschedasticità nei residui, soprattutto per valori estremi (anche se più plausibile).

Relazione quadratica

Testiamo il possibile modello per le variabili riscalate non trasformate con la relazione quadratica (effetto parabolico):

fit_Gamma_Quadratico<-glm(I(price/(10^5))~I(sqft_living/(10^3))+I((sqft_living/(10^3))^2),data=df,family=Gamma(link="log"))
summary(fit_Gamma_Quadratico)
## 
## Call:
## glm(formula = I(price/(10^5)) ~ I(sqft_living/(10^3)) + I((sqft_living/(10^3))^2), 
##     family = Gamma(link = "log"), data = df)
## 
## Coefficients:
##                            Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                0.687176   0.011054  62.167   <2e-16 ***
## I(sqft_living/(10^3))      0.473875   0.008279  57.237   <2e-16 ***
## I((sqft_living/(10^3))^2) -0.012788   0.001406  -9.095   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for Gamma family taken to be 0.1540905)
## 
##     Null deviance: 6550.9  on 21596  degrees of freedom
## Residual deviance: 3091.9  on 21594  degrees of freedom
## AIC: 86148
## 
## Number of Fisher Scoring iterations: 5
# effetto significativo
anova(fit_Gamma,fit_Gamma_Quadratico)
## Analysis of Deviance Table
## 
## Model 1: I(price/(10^5)) ~ I(sqft_living/(10^3))
## Model 2: I(price/(10^5)) ~ I(sqft_living/(10^3)) + I((sqft_living/(10^3))^2)
##   Resid. Df Resid. Dev Df Deviance
## 1     21595     3101.3            
## 2     21594     3091.9  1   9.3472

I coefficienti sono significativi e il modello rispetto al modello nullo è significativo. Il miglioramento introdotto dall’effetto quadratico è significativo.

Analisi dei residui:

plot(fit_Gamma_Quadratico)

# gli standard error sono alti ma perchè ho tante osservazioni

Il grafico del qq-plot ci mostra che l’assunzione di normalità dei residui non è rispettata, notiamo forte asimmetria dx/pos. nel qq-plot per i residui (come riscontrato in precedenza nei dati).

Relazione quadratica senza il valore anomalo

Testiamo il possibile modello per le variabili riscalate non trasformate con la relazione quadratica (effetto parabolico):

fit_Gamma_Quadratico_noLeva<-glm(I(price/(10^5))[-12765]~I(sqft_living/(10^3))[-12765]+I((sqft_living/(10^3))^2)[-12765],data=df,family=Gamma(link="log"))
summary(fit_Gamma_Quadratico_noLeva)
## 
## Call:
## glm(formula = I(price/(10^5))[-12765] ~ I(sqft_living/(10^3))[-12765] + 
##     I((sqft_living/(10^3))^2)[-12765], family = Gamma(link = "log"), 
##     data = df)
## 
## Coefficients:
##                                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                        0.695678   0.011584  60.055  < 2e-16 ***
## I(sqft_living/(10^3))[-12765]      0.465877   0.008891  52.399  < 2e-16 ***
## I((sqft_living/(10^3))^2)[-12765] -0.011206   0.001544  -7.259 4.03e-13 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for Gamma family taken to be 0.1540261)
## 
##     Null deviance: 6547.4  on 21595  degrees of freedom
## Residual deviance: 3090.1  on 21593  degrees of freedom
## AIC: 86129
## 
## Number of Fisher Scoring iterations: 4
# effetto significativo
AIC(fit_Gamma_Quadratico,fit_Gamma_Quadratico_noLeva)
## Warning in AIC.default(fit_Gamma_Quadratico, fit_Gamma_Quadratico_noLeva):
## models are not all fitted to the same number of observations
##                             df      AIC
## fit_Gamma_Quadratico         4 86148.45
## fit_Gamma_Quadratico_noLeva  4 86129.38

I coefficienti sono significativi e il modello rispetto al modello nullo è significativo. Il miglioramento introdotto dall’eliminazione dal dataset del valore anomalo è significativo ma non sostanziale.

Analisi dei residui:

plot(fit_Gamma_Quadratico_noLeva) 

# gli standard error sono alti ma perchè ho tante osservazioni

Il grafico del qq-plot ci mostra che l’assunzione di normalità dei residui non è rispettata, notiamo forte asimmetria dx/pos. nel qq-plot per i residui (come riscontrato in precedenza nei dati).

Confronto tra i 3 modelli

AIC(fit_Gamma,fit_Gamma_Quadratico,fit_Gamma_Quadratico_noLeva)
## Warning in AIC.default(fit_Gamma, fit_Gamma_Quadratico,
## fit_Gamma_Quadratico_noLeva): models are not all fitted to the same number of
## observations
##                             df      AIC
## fit_Gamma                    3 86213.20
## fit_Gamma_Quadratico         4 86148.45
## fit_Gamma_Quadratico_noLeva  4 86129.38
BIC(fit_Gamma,fit_Gamma_Quadratico,fit_Gamma_Quadratico_noLeva)
## Warning in BIC.default(fit_Gamma, fit_Gamma_Quadratico,
## fit_Gamma_Quadratico_noLeva): models are not all fitted to the same number of
## observations
##                             df      BIC
## fit_Gamma                    3 86237.14
## fit_Gamma_Quadratico         4 86180.38
## fit_Gamma_Quadratico_noLeva  4 86161.30

REGRESSIONE SEMIPARAMETRICA

MODELLO AM

Abbiamo visto che un struttura polinomiale quadratica spiega meglio i dati per entrambi i modelli, proviamo a generalizzare la relazione polinomiale introducendo una funzione di tipo spline tramite un modello additivo (regressione semiparametrica):

# Modello additivo generalizzato per log(price) caso LM
require(mgcv)
## Loading required package: mgcv
## Loading required package: nlme
## 
## Attaching package: 'nlme'
## The following object is masked from 'package:dplyr':
## 
##     collapse
## This is mgcv 1.9-0. For overview type 'help("mgcv-package")'.
fit_AM<-gam(log(price)~s(log(sqft_living)),data=df)
summary(fit_AM)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living))
## 
## Parametric coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 13.048211   0.002565    5088   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df    F p-value    
## s(log(sqft_living)) 5.545  6.664 3082  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.488   Deviance explained = 48.8%
## GCV = 0.1421  Scale est. = 0.14206   n = 21597

R quadro è ancora basso mentre i coefficienti per intercetta e spline sono significativi.

plot(fit_AM)

# sembra comportarsi sicuramente meglio rispetto al modello LM
gam.check(fit_AM)

## 
## Method: GCV   Optimizer: magic
## Smoothing parameter selection converged after 6 iterations.
## The RMS GCV score gradient at convergence was 9.376831e-07 .
## The Hessian was positive definite.
## Model rank =  10 / 10 
## 
## Basis dimension (k) checking results. Low p-value (k-index<1) may
## indicate that k is too low, especially if edf is close to k'.
## 
##                       k'  edf k-index p-value
## s(log(sqft_living)) 9.00 5.54       1    0.41

Il modello sembra comportarsi meglio in termini di omoschedasticità e normalità dei residui. Da questi grafici non riusciamo ad interpretare bene però quanto sia migliorato, proviamo con un confronto tramite GCV:

fit_AM_Quadratico<-gam(log(price)~s(log(sqft_living))+I(log(sqft_living)^2),data=df)
summary(fit_AM_Quadratico)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + I(log(sqft_living)^2)
## 
## Parametric coefficients:
##                       Estimate Std. Error t value Pr(>|t|)  
## (Intercept)             0.7501     6.2112   0.121   0.9039  
## I(log(sqft_living)^2)   0.2150     0.1086   1.980   0.0477 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df     F p-value    
## s(log(sqft_living)) 5.492   6.55 153.5  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.488   Deviance explained = 48.8%
## GCV = 0.1421  Scale est. = 0.14206   n = 21597
AIC(fit_AM,fit_AM_Quadratico)
##                         df      AIC
## fit_AM            7.544847 19151.00
## fit_AM_Quadratico 8.491684 19151.71
BIC(fit_AM,fit_AM_Quadratico)
##                         df      BIC
## fit_AM            7.544847 19211.21
## fit_AM_Quadratico 8.491684 19219.47
fit_AM$gcv.ubre
##    GCV.Cp 
## 0.1420997
fit_AM_Quadratico$gcv.ubre
##    GCV.Cp 
## 0.1421044

Il modella con la spline scelta dall’algoritmo spiega molto meglio in quanto riduce l’MSE della funzione rispetto ai dati.

MODELLO GAM

fit_GAM<-gam(I(price/(10^5))~s(I(sqft_living/(10^3))),data=df,family=Gamma(link="log"))
summary(fit_GAM)
## 
## Family: Gamma 
## Link function: log 
## 
## Formula:
## I(price/(10^5)) ~ s(I(sqft_living/(10^3)))
## 
## Parametric coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 1.606551   0.002663   603.3   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                            edf Ref.df    F p-value    
## s(I(sqft_living/(10^3))) 8.514  8.913 2181  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.549   Deviance explained =   53%
## GCV = 0.14266  Scale est. = 0.15316   n = 21597

R quadro del GAM è più alto di quello dell’AM.

Analisi dei residui:

plot(fit_GAM)

# sembra comportarsi sicuramente meglio rispetto al modello LM
gam.check(fit_GAM)

## 
## Method: GCV   Optimizer: outer newton
## full convergence after 5 iterations.
## Gradient range [2.478194e-07,2.478194e-07]
## (score 0.142656 & scale 0.1531622).
## Hessian positive definite, eigenvalue range [5.401977e-06,5.401977e-06].
## Model rank =  10 / 10 
## 
## Basis dimension (k) checking results. Low p-value (k-index<1) may
## indicate that k is too low, especially if edf is close to k'.
## 
##                            k'  edf k-index p-value
## s(I(sqft_living/(10^3))) 9.00 8.51    0.98     0.4

Nonostante il summary del GAM sia migliore, l’Hp. di normalità degli errori viene spiegata meglio nell’AM, analogo discorso per l’omoschedasticità dei residui.

Anche qui possiamo testare la differenza con il GLM con effetto quadratico della covariata:

fit_GAM_Quadratico<-gam(I(price/(10^5))~I(sqft_living/(10^3))+I((sqft_living/(10^3))^2),data=df,family=Gamma(link="log"))
summary(fit_GAM_Quadratico)
## 
## Family: Gamma 
## Link function: log 
## 
## Formula:
## I(price/(10^5)) ~ I(sqft_living/(10^3)) + I((sqft_living/(10^3))^2)
## 
## Parametric coefficients:
##                            Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                0.687188   0.011054  62.168   <2e-16 ***
## I(sqft_living/(10^3))      0.473864   0.008279  57.236   <2e-16 ***
## I((sqft_living/(10^3))^2) -0.012785   0.001406  -9.094   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## 
## R-sq.(adj) =  0.514   Deviance explained = 52.8%
## GCV = 0.14321  Scale est. = 0.15409   n = 21597
AIC(fit_GAM,fit_GAM_Quadratico)
##                         df      AIC
## fit_GAM            10.5143 86155.94
## fit_GAM_Quadratico  4.0000 86244.69
BIC(fit_GAM,fit_GAM_Quadratico)
##                         df      BIC
## fit_GAM            10.5143 86239.85
## fit_GAM_Quadratico  4.0000 86276.61
fit_GAM$gcv.ubre
##   GCV.Cp 
## 0.142656
fit_GAM_Quadratico$gcv.ubre
##    GCV.Cp 
## 0.1432052

Notiamo che il modello migliora con la spline

CONFRONTO TRA I 2 MODELLI CONLUSIVI

# il primo ha il GCV più basso quindi sono portato in linea di principio a prediligere il modello additivo generalizzato
fit_AM$gcv.ubre
##    GCV.Cp 
## 0.1420997
fit_GAM$gcv.ubre
##   GCV.Cp 
## 0.142656
AIC(fit_AM,fit_GAM)
##                df      AIC
## fit_AM   7.544847 19151.00
## fit_GAM 10.514301 86155.94
BIC(fit_AM,fit_GAM)
##                df      BIC
## fit_AM   7.544847 19211.21
## fit_GAM 10.514301 86239.85

Concludiamo per GCV, AIC e BIC che siamo portati a preferire il modello \(fit_AM\) come miglior modello tra quelli fittati per studiare la relazione tra la variabile \(price\) e la variabile \(sqft_living\).

Il modello può ancora essere migliorato, nel proseguo del progetto si cercherà di trovare il miglior modello introducendo le variabili a disposizione.

AGGIUNTA DI ESPLICATIVE AL MODELLO

SISTEMAZIONE DEI DATI, ANALISI ESPLORATIVA e ANALISI DELLA RELAZIONE CON LA VARIABILE RISPOSTA

# tolgo id perchè non è informativa
names(df)
##  [1] "id"            "date"          "price"         "bedrooms"     
##  [5] "bathrooms"     "sqft_living"   "sqft_lot"      "floors"       
##  [9] "waterfront"    "view"          "condition"     "grade"        
## [13] "sqft_above"    "sqft_basement" "yr_built"      "yr_renovated" 
## [17] "zipcode"       "lat"           "long"          "sqft_living15"
## [21] "sqft_lot15"
df<-df[,-1]
# tolgo zip perchè non è informativa
names(df)
##  [1] "date"          "price"         "bedrooms"      "bathrooms"    
##  [5] "sqft_living"   "sqft_lot"      "floors"        "waterfront"   
##  [9] "view"          "condition"     "grade"         "sqft_above"   
## [13] "sqft_basement" "yr_built"      "yr_renovated"  "zipcode"      
## [17] "lat"           "long"          "sqft_living15" "sqft_lot15"
df<-df[,-16]

# camere da letto
bedrooms<-factor(bedrooms,ordered = is.ordered(bedrooms))
barplot(table(bedrooms)/length(bedrooms))

# sembra esserci una relazione crescente
boxplot(log(price)~bedrooms)

# bagni
bathrooms<-factor(bathrooms,ordered = is.ordered(bathrooms))
barplot(table(bathrooms)/length(bathrooms))

# sembra esserci una relazione crescente
boxplot(log(price)~bathrooms)

# sqft lot richiede una trasformazione logaritmica per renderlo osservabile causa forte asimmetria
hist(log(sqft_lot),prob=T,breaks=200)

# non si riesce ad intuire bene ad occhio una relazione di correlazione positiva marcata
plot(log(price)~log(sqft_lot))

# a conferma:
cor(log(price),log(sqft_lot))
## [1] 0.1382607
# scarsa correlazione positiva, quasi incorrelate
cor(price,sqft_lot)
## [1] 0.08987622
# piani qualitativa
floors<-factor(floors,ordered = is.ordered(floors))
barplot(table(floors)/length(floors))

# fino a 3 sembra esserci una relazione di correlazione positiva leggermente marcata
plot(log(price)~floors)

# vista mare dicotomica
waterfront<-factor(waterfront,ordered = is.ordered(waterfront))
pie(table(waterfront)/length(waterfront),col=c("lightblue","orange"))

barplot(table(waterfront)/length(waterfront))

# numero di visite: le variabili da aggiungere al modello sarebbero tantissime quindi la approssimiamo a quantitativa
hist(table(view),prob=T,breaks=200)

plot(log(price)~view)

cor(log(price),view)
## [1] 0.3466351
# condizioni
condition<-factor(condition,ordered = is.ordered(condition))
pie(table(condition)/length(condition),col=c("lightblue","orange","red","green","brown"))

barplot(table(condition)/length(condition))

plot(log(price)~condition)

# condizioni della casa valutate in ordine crescente
grade<-factor(grade,ordered = is.ordered(grade))
pie(table(grade)/length(grade),col=c("lightblue","orange","red","green","brown","blue","grey"))

barplot(table(grade)/length(grade))

plot(log(price)~grade)

# sqft above (penso sia il tetto) più simmetrica e comparabile in termini di effetto
hist(log(sqft_above),prob=T,breaks=200)

plot(log(price)~log(sqft_above))

cor(log(price),log(sqft_above))
## [1] 0.5860128
# sqft basement (penso sia le fondamenta) ora è asimmetrica a destra ma sempre meglio di quello schifo di prima, volendo la si può sistemare ancora
# proviamo a compattare con la radice perchè ci sono troppi dati con degli zeri e non va bene 
hist((sqft_basement/(10^2)),prob=T,breaks=200)

plot(log(price)~I(sqft_basement/(10^2)))

cor(log(price),(sqft_basement/(10^2)))
## [1] 0.3169204
# anni dalla costruzione
max(yr_built)
## [1] 2015
yr_built<-(2015-yr_built)
hist(yr_built,prob=T,breaks = 200)

plot(log(price)~yr_built)

cor(log(price),yr_built)
## [1] -0.08058327
# numerico
yr_renovated<-ifelse(yr_renovated==0,0,max(yr_renovated)-yr_renovated)
hist(yr_renovated,prob=T,breaks = 200)

plot(log(price)~yr_renovated)

cor(log(price),yr_renovated)
## [1] 0.05757177
# traformiamo anche latitudine e longitudine, ottengo una variabile in R+ che volendo potremmo anche trasformare moltiplicando per 10
lat<-(lat-min(lat))
hist(lat,prob=T,breaks=200)

plot(log(price)~lat)

cor(log(price),lat)
## [1] 0.448837
long<-(long-min(long))
hist(long,prob=T,breaks=200)

plot(log(price)~long)

cor(log(price),long)
## [1] 0.05086233
# differenza tra l'anno 2014 e l'anno 2015
sqft_living15.differenza<-c(rep(0,length(sqft_living15)))
for(i in 1:length(sqft_living15)){
  if(sqft_living15[i]==sqft_living[i]){
    sqft_living15.differenza[i]=0
    }
  else{
    sqft_living15.differenza[i]=abs(sqft_living15[i]-sqft_living[i])
    }
}
cor(log(price),sqrt(sqft_living15.differenza))
## [1] 0.2792381
hist(sqrt(sqft_living15.differenza),prob=T,breaks=100)

plot(log(price)~sqrt(sqft_living15.differenza))

# differenza tra l'anno 2014 e 2015
sqft_lot15.differenza<-c(rep(0,length(sqft_lot15)))
for(i in 1:length(sqft_lot15)){
  if(sqft_lot15[i]==sqft_lot[i]){
    sqft_lot15.differenza[i]=0
    }
  else{
    sqft_lot15.differenza[i]=abs(sqft_lot15[i]-sqft_lot[i])
    }
}
cor(log(price),sqrt(sqft_lot15.differenza))
## [1] 0.09432777
hist(sqrt(sqft_lot15.differenza),prob=T,breaks=100)

plot(log(price)~sqrt(sqft_lot15.differenza))

Voglio analizzare se l’Hp. che la var. risposta price è indipendente dal tempo e cioè se le osservazioni sono incorrelate:

# ricodifica delle date
date<-as.Date(date,"%m/%d/%y")
plot(date,log(price))

Non sembrano esserci né un comportamento di fondo né forme di volatility clusters. Si potrebbe approfondire una potenziale analisi della serie storica per evidenziare la presenza di tali effetti ma sarebbe necessario ricodificare i dati per rendere le osservazioni della serie storica equidistanziate. Si noti che è importante testare l’Hp. di incorrelazione negli errori perchè è alla base di ogni procedimento statistica di stima dei modelli adottati in questo elaborato.

STIMA DEL MODELLO

# effetto significativo, migliora leggermente R quadro corretto
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms
## 
## Parametric coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 13.257358   0.012146 1091.47   <2e-16 ***
## bedrooms    -0.062003   0.003521  -17.61   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df    F p-value    
## s(log(sqft_living)) 5.463  6.582 2446  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.495   Deviance explained = 49.5%
## GCV = 0.14011  Scale est. = 0.14006   n = 21597
# effetto significativo, migliora leggermente R quadro corretto
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms
## 
## Parametric coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 13.164882   0.015669 840.168   <2e-16 ***
## bedrooms    -0.065044   0.003529 -18.431   <2e-16 ***
## bathrooms    0.048556   0.005212   9.316   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                      edf Ref.df    F p-value    
## s(log(sqft_living)) 5.43  6.551 1230  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.497   Deviance explained = 49.7%
## GCV = 0.13957  Scale est. = 0.13951   n = 21597
# l'aggiunta della variabile log(sqft_lot) è significativa, il miglioramento su R quadro corretto è leggero ma di impatto maggiore rispetto alle precedenti aggiunte di covariate al modello
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot)
## 
## Parametric coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   13.813341   0.034296 402.770  < 2e-16 ***
## bedrooms      -0.064425   0.003493 -18.445  < 2e-16 ***
## bathrooms      0.018945   0.005344   3.545 0.000394 ***
## log(sqft_lot) -0.065396   0.003085 -21.199  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df    F p-value    
## s(log(sqft_living)) 5.394  6.515 1296  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.507   Deviance explained = 50.7%
## GCV = 0.13672  Scale est. = 0.13666   n = 21597
# l'aggiunta della variabile floors non è molto significativa, né in termini di coefficienti né in termini di miglioramento su R quadro corretto. Decidiamo di tenerla ugualmente perchè in seguito potrebbe rivelarsi significativa per spiegare delle relazioni con altre variabili
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+floors,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     floors
## 
## Parametric coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   13.782963   0.038134 361.433  < 2e-16 ***
## bedrooms      -0.063685   0.003516 -18.110  < 2e-16 ***
## bathrooms      0.015714   0.005633   2.790  0.00528 ** 
## log(sqft_lot) -0.063295   0.003293 -19.222  < 2e-16 ***
## floors         0.010598   0.005827   1.819  0.06896 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                      edf Ref.df    F p-value    
## s(log(sqft_living)) 5.37  6.492 1264  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.507   Deviance explained = 50.7%
## GCV = 0.13671  Scale est. = 0.13665   n = 21597
# si sceglie di non inserire floors nel modello seguendo il principio di parsimonia (R quadro non migliora molto e il coeff. non è molto significativo, non vale la pensa aggiungere le variabili fattorialli)

# sembra migliorare R quadro e la variabile sembra dare coeff significativi
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront
## 
## Parametric coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   13.818116   0.033911 407.485  < 2e-16 ***
## bedrooms      -0.059220   0.003461 -17.112  < 2e-16 ***
## bathrooms      0.018088   0.005286   3.422 0.000623 ***
## log(sqft_lot) -0.068227   0.003052 -22.351  < 2e-16 ***
## waterfront     0.653271   0.029049  22.488  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df    F p-value    
## s(log(sqft_living)) 5.706  6.827 1215  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.518   Deviance explained = 51.9%
## GCV = 0.13361  Scale est. = 0.13354   n = 21597
# view migliora R quadro e la varianzione di R quadro è significativa
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view
## 
## Parametric coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   13.778292   0.033400 412.529  < 2e-16 ***
## bedrooms      -0.053370   0.003413 -15.639  < 2e-16 ***
## bathrooms      0.019975   0.005201   3.841 0.000123 ***
## log(sqft_lot) -0.068691   0.003004 -22.869  < 2e-16 ***
## waterfront     0.337392   0.030956  10.899  < 2e-16 ***
## view           0.096705   0.003635  26.601  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df    F p-value    
## s(log(sqft_living)) 5.482  6.604 1111  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.534   Deviance explained = 53.4%
## GCV = 0.1294  Scale est. = 0.12933   n = 21597
# condition migliora R quadro e coeff signific. Migliora anche GCV.
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition
## 
## Parametric coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   13.551928   0.035023 386.940  < 2e-16 ***
## bedrooms      -0.059366   0.003396 -17.483  < 2e-16 ***
## bathrooms      0.032391   0.005193   6.237 4.53e-10 ***
## log(sqft_lot) -0.072641   0.002984 -24.347  < 2e-16 ***
## waterfront     0.338836   0.030679  11.045  < 2e-16 ***
## view           0.091871   0.003611  25.442  < 2e-16 ***
## condition      0.075355   0.003806  19.801  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df    F p-value    
## s(log(sqft_living)) 5.603  6.726 1123  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.542   Deviance explained = 54.2%
## GCV = 0.1271  Scale est. = 0.12702   n = 21597
# grade: migliora di molto R quadro corretto e coeff signific. Migliora anche GCV.
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade
## 
## Parametric coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   11.959491   0.042898 278.791  < 2e-16 ***
## bedrooms      -0.021789   0.003233  -6.740 1.63e-11 ***
## bathrooms     -0.023359   0.004934  -4.734 2.21e-06 ***
## log(sqft_lot) -0.061471   0.002788 -22.052  < 2e-16 ***
## waterfront     0.367597   0.028603  12.852  < 2e-16 ***
## view           0.079464   0.003373  23.558  < 2e-16 ***
## condition      0.099451   0.003573  27.837  < 2e-16 ***
## grade          0.183306   0.003205  57.195  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df     F p-value    
## s(log(sqft_living)) 5.136  6.253 354.8  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.602   Deviance explained = 60.2%
## GCV = 0.11046  Scale est. = 0.11039   n = 21597
# sqft_above: migliora R quadro corretto leggermente e coeff signific. Migliora anche GCV.
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade+log(sqft_above),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade + log(sqft_above)
## 
## Parametric coefficients:
##                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     12.752554   0.087976 144.955  < 2e-16 ***
## bedrooms        -0.021905   0.003225  -6.792 1.13e-11 ***
## bathrooms       -0.019967   0.004931  -4.049 5.16e-05 ***
## log(sqft_lot)   -0.057446   0.002807 -20.462  < 2e-16 ***
## waterfront       0.376749   0.028546  13.198  < 2e-16 ***
## view             0.074114   0.003405  21.767  < 2e-16 ***
## condition        0.093090   0.003617  25.738  < 2e-16 ***
## grade            0.191847   0.003301  58.110  < 2e-16 ***
## log(sqft_above) -0.118802   0.011509 -10.322  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df     F p-value    
## s(log(sqft_living)) 5.018  6.131 339.5  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.604   Deviance explained = 60.4%
## GCV = 0.10993  Scale est. = 0.10986   n = 21597
# sqft_basement: migliora R quadro corretto leggermente e coeff signific.. Migliora anche GCV.
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade+log(sqft_above)+sqrt(sqft_basement),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade + log(sqft_above) + 
##     sqrt(sqft_basement)
## 
## Parametric coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          9.9090039  0.2763168  35.861  < 2e-16 ***
## bedrooms            -0.0216936  0.0032166  -6.744 1.58e-11 ***
## bathrooms           -0.0250920  0.0049424  -5.077 3.87e-07 ***
## log(sqft_lot)       -0.0551780  0.0028084 -19.648  < 2e-16 ***
## waterfront           0.3850617  0.0284817  13.520  < 2e-16 ***
## view                 0.0689799  0.0034283  20.121  < 2e-16 ***
## condition            0.0926857  0.0036074  25.693  < 2e-16 ***
## grade                0.1918071  0.0032936  58.236  < 2e-16 ***
## log(sqft_above)      0.2555302  0.0363449   7.031 2.12e-12 ***
## sqrt(sqft_basement)  0.0065929  0.0006073  10.856  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                      edf Ref.df     F p-value    
## s(log(sqft_living)) 5.21  6.334 50.45  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.606   Deviance explained = 60.6%
## GCV = 0.10935  Scale est. = 0.10927   n = 21597
# yr_built: migliora R quadro e coeff signific. migliora anche GCV
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade+log(sqft_above)+sqrt(sqft_basement)+yr_built,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade + log(sqft_above) + 
##     sqrt(sqft_basement) + yr_built
## 
## Parametric coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          2.069e+01  3.260e-01  63.454  < 2e-16 ***
## bedrooms            -3.599e-02  3.028e-03 -11.886  < 2e-16 ***
## bathrooms            7.398e-02  4.988e-03  14.831  < 2e-16 ***
## log(sqft_lot)       -5.749e-02  2.635e-03 -21.820  < 2e-16 ***
## waterfront           3.787e-01  2.671e-02  14.182  < 2e-16 ***
## view                 4.889e-02  3.235e-03  15.114  < 2e-16 ***
## condition            3.704e-02  3.533e-03  10.484  < 2e-16 ***
## grade                2.231e-01  3.144e-03  70.958  < 2e-16 ***
## log(sqft_above)      1.847e-01  3.414e-02   5.409 6.42e-08 ***
## sqrt(sqft_basement)  3.256e-03  5.734e-04   5.678 1.38e-08 ***
## yr_built            -5.278e-03  9.676e-05 -54.547  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df    F p-value    
## s(log(sqft_living)) 6.403  7.487 23.7  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.654   Deviance explained = 65.4%
## GCV = 0.096109  Scale est. = 0.096032  n = 21597
# yr_renovated: migliora R quadro e coeff signific. migliora anche GCV
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade+log(sqft_above)+sqrt(sqft_basement)+yr_built+yr_renovated,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade + log(sqft_above) + 
##     sqrt(sqft_basement) + yr_built + yr_renovated
## 
## Parametric coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          2.057e+01  3.319e-01  61.974  < 2e-16 ***
## bedrooms            -3.573e-02  3.031e-03 -11.788  < 2e-16 ***
## bathrooms            7.259e-02  5.043e-03  14.395  < 2e-16 ***
## log(sqft_lot)       -5.753e-02  2.635e-03 -21.836  < 2e-16 ***
## waterfront           3.758e-01  2.675e-02  14.047  < 2e-16 ***
## view                 4.874e-02  3.236e-03  15.063  < 2e-16 ***
## condition            3.818e-02  3.585e-03  10.650  < 2e-16 ***
## grade                2.231e-01  3.144e-03  70.952  < 2e-16 ***
## log(sqft_above)      1.838e-01  3.414e-02   5.382 7.43e-08 ***
## sqrt(sqft_basement)  3.253e-03  5.734e-04   5.673 1.42e-08 ***
## yr_built            -5.217e-03  1.022e-04 -51.047  < 2e-16 ***
## yr_renovated         1.050e-05  5.617e-06   1.870   0.0615 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df     F p-value    
## s(log(sqft_living)) 6.385  7.471 23.83  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.654   Deviance explained = 65.4%
## GCV = 0.096103  Scale est. = 0.096021  n = 21597
# per il principio di parsimonia escludiamo la variabile dal modello, coeff. poco  significativi

# aggiunta di lat
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade+log(sqft_above)+sqrt(sqft_basement)+yr_built+lat,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade + log(sqft_above) + 
##     sqrt(sqft_basement) + yr_built + lat
## 
## Parametric coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         -4.748e+01  7.272e-01 -65.297  < 2e-16 ***
## bedrooms            -2.622e-02  2.498e-03 -10.495  < 2e-16 ***
## bathrooms            6.790e-02  4.110e-03  16.521  < 2e-16 ***
## log(sqft_lot)       -2.030e-02  2.203e-03  -9.217  < 2e-16 ***
## waterfront           3.943e-01  2.202e-02  17.909  < 2e-16 ***
## view                 6.690e-02  2.673e-03  25.030  < 2e-16 ***
## condition            5.834e-02  2.920e-03  19.980  < 2e-16 ***
## grade                1.763e-01  2.632e-03  66.960  < 2e-16 ***
## log(sqft_above)      2.284e-01  2.814e-02   8.117 5.05e-16 ***
## sqrt(sqft_basement)  2.498e-03  4.727e-04   5.286 1.26e-07 ***
## yr_built            -3.434e-03  8.183e-05 -41.960  < 2e-16 ***
## lat                  1.349e+00  1.337e-02 100.883  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df     F p-value    
## s(log(sqft_living)) 5.992  7.109 23.77  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.765   Deviance explained = 76.5%
## GCV = 0.065325  Scale est. = 0.06527   n = 21597
# aggiunta di long (poco correlata)
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade+log(sqft_above)+sqrt(sqft_basement)+yr_built+lat+long,data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade + log(sqft_above) + 
##     sqrt(sqft_basement) + yr_built + lat + long
## 
## Parametric coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         -4.063e+01  2.073e+00 -19.597  < 2e-16 ***
## bedrooms            -2.602e-02  2.498e-03 -10.417  < 2e-16 ***
## bathrooms            6.789e-02  4.109e-03  16.525  < 2e-16 ***
## log(sqft_lot)       -2.329e-02  2.359e-03  -9.872  < 2e-16 ***
## waterfront           3.968e-01  2.202e-02  18.017  < 2e-16 ***
## view                 6.750e-02  2.678e-03  25.211  < 2e-16 ***
## condition            5.796e-02  2.921e-03  19.839  < 2e-16 ***
## grade                1.772e-01  2.646e-03  66.989  < 2e-16 ***
## log(sqft_above)      2.290e-01  2.813e-02   8.140 4.15e-16 ***
## sqrt(sqft_basement)  2.615e-03  4.736e-04   5.520 3.43e-08 ***
## yr_built            -3.533e-03  8.657e-05 -40.817  < 2e-16 ***
## lat                  1.348e+00  1.337e-02 100.879  < 2e-16 ***
## long                 5.422e-02  1.535e-02   3.531 0.000415 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df     F p-value    
## s(log(sqft_living)) 5.951   7.07 23.46  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.765   Deviance explained = 76.5%
## GCV = 0.065293  Scale est. = 0.065236  n = 21597
# aggiunta di sqft_living15.differenza
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade+log(sqft_above)+sqrt(sqft_basement)+yr_built+lat+long+sqrt(sqft_living15.differenza),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade + log(sqft_above) + 
##     sqrt(sqft_basement) + yr_built + lat + long + sqrt(sqft_living15.differenza)
## 
## Parametric coefficients:
##                                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                    -3.840e+01  2.080e+00 -18.461  < 2e-16 ***
## bedrooms                       -2.613e-02  2.492e-03 -10.486  < 2e-16 ***
## bathrooms                       6.582e-02  4.106e-03  16.031  < 2e-16 ***
## log(sqft_lot)                  -2.653e-02  2.376e-03 -11.167  < 2e-16 ***
## waterfront                      3.962e-01  2.197e-02  18.032  < 2e-16 ***
## view                            6.780e-02  2.672e-03  25.377  < 2e-16 ***
## condition                       5.763e-02  2.915e-03  19.771  < 2e-16 ***
## grade                           1.801e-01  2.656e-03  67.825  < 2e-16 ***
## log(sqft_above)                 2.166e-01  2.810e-02   7.708 1.34e-14 ***
## sqrt(sqft_basement)             2.356e-03  4.734e-04   4.977 6.52e-07 ***
## yr_built                       -3.452e-03  8.676e-05 -39.790  < 2e-16 ***
## lat                             1.344e+00  1.334e-02 100.718  < 2e-16 ***
## long                            7.136e-02  1.541e-02   4.629 3.69e-06 ***
## sqrt(sqft_living15.differenza)  1.901e-03  1.893e-04  10.046  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                      edf Ref.df     F p-value    
## s(log(sqft_living)) 6.21  7.313 15.61  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.766   Deviance explained = 76.6%
## GCV = 0.064994  Scale est. = 0.064934  n = 21597
# aggiunta di sqft_lot15.differenza
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+bedrooms+bathrooms+log(sqft_lot)+waterfront+view+condition+grade+log(sqft_above)+sqrt(sqft_basement)+yr_built+lat+long+sqrt(sqft_living15.differenza)+sqrt(sqft_lot15.differenza),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + bedrooms + bathrooms + log(sqft_lot) + 
##     waterfront + view + condition + grade + log(sqft_above) + 
##     sqrt(sqft_basement) + yr_built + lat + long + sqrt(sqft_living15.differenza) + 
##     sqrt(sqft_lot15.differenza)
## 
## Parametric coefficients:
##                                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                    -3.691e+01  2.078e+00 -17.760  < 2e-16 ***
## bedrooms                       -2.377e-02  2.494e-03  -9.532  < 2e-16 ***
## bathrooms                       6.077e-02  4.119e-03  14.754  < 2e-16 ***
## log(sqft_lot)                  -4.540e-02  2.905e-03 -15.629  < 2e-16 ***
## waterfront                      3.952e-01  2.191e-02  18.039  < 2e-16 ***
## view                            6.687e-02  2.665e-03  25.089  < 2e-16 ***
## condition                       5.898e-02  2.909e-03  20.275  < 2e-16 ***
## grade                           1.803e-01  2.648e-03  68.083  < 2e-16 ***
## log(sqft_above)                 2.125e-01  2.802e-02   7.582 3.55e-14 ***
## sqrt(sqft_basement)             2.249e-03  4.721e-04   4.764 1.91e-06 ***
## yr_built                       -3.501e-03  8.662e-05 -40.424  < 2e-16 ***
## lat                             1.340e+00  1.331e-02 100.738  < 2e-16 ***
## long                            7.996e-02  1.539e-02   5.196 2.06e-07 ***
## sqrt(sqft_living15.differenza)  1.760e-03  1.891e-04   9.304  < 2e-16 ***
## sqrt(sqft_lot15.differenza)     4.281e-04  3.814e-05  11.223  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df     F p-value    
## s(log(sqft_living)) 6.196  7.301 17.44  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.767   Deviance explained = 76.7%
## GCV = 0.064623  Scale est. = 0.06456   n = 21597

Ora che abbiamo raggiunto un primo modello che può sembrare soddisfacente testiamo la presenza di collinearità per valutare l’aggiunta degli effetti di interazione tra le variabili:

# install.packages("regclass")
require(regclass)
## Loading required package: regclass
## Loading required package: bestglm
## Loading required package: leaps
## Loading required package: VGAM
## Loading required package: stats4
## Loading required package: splines
## 
## Attaching package: 'VGAM'
## The following object is masked from 'package:mgcv':
## 
##     s
## The following objects are masked from 'package:greybox':
## 
##     AICc, dlaplace, nparam, plaplace, qlaplace, rlaplace
## Loading required package: rpart
## Loading required package: randomForest
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
## 
##     margin
## The following object is masked from 'package:dplyr':
## 
##     combine
## Important regclass change from 1.3:
## All functions that had a . in the name now have an _
## all.correlations -> all_correlations, cor.demo -> cor_demo, etc.
require(faraway)
## Loading required package: faraway
## 
## Attaching package: 'faraway'
## The following object is masked from 'package:rpart':
## 
##     solder
## The following objects are masked from 'package:VGAM':
## 
##     hormone, logit, pneumo, prplot
# analisi dei vif per testare la collinearità
vif(fit_AM.updated)
##                       bedrooms                      bathrooms 
##                       1.785298                       3.355676 
##                  log(sqft_lot)                     waterfront 
##                       2.297331                       1.202630 
##                           view                      condition 
##                       1.395580                       1.197851 
##                          grade                log(sqft_above) 
##                       3.228370                      47.925915 
##            sqrt(sqft_basement)                       yr_built 
##                      13.847030                       2.165621 
##                            lat                           long 
##                       1.137060                       1.568746 
## sqrt(sqft_living15.differenza)    sqrt(sqft_lot15.differenza) 
##                       1.417192                       1.669610 
##          s(log(sqft_living)).1          s(log(sqft_living)).2 
##                     180.691022                     179.421621 
##          s(log(sqft_living)).3          s(log(sqft_living)).4 
##                      72.887316                      39.195423 
##          s(log(sqft_living)).5          s(log(sqft_living)).6 
##                      71.501560                      59.298289 
##          s(log(sqft_living)).7          s(log(sqft_living)).8 
##                      75.264689                    1771.619572 
##          s(log(sqft_living)).9 
##                     586.410332

I GVIF sono molto alti, deduciamo che è opportuno aggiungere gli effetti interazione tra le variabili:

# iniziamo ad aggiungere interazioni
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+s(log(sqft_above))+bedrooms*bathrooms+waterfront+condition*grade+view+yr_built+lat*long+sqrt(sqft_basement)*log(sqft_lot)+sqrt(sqft_living15.differenza)*sqrt(sqft_lot15.differenza),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + s(log(sqft_above)) + bedrooms * 
##     bathrooms + waterfront + condition * grade + view + yr_built + 
##     lat * long + sqrt(sqft_basement) * log(sqft_lot) + sqrt(sqft_living15.differenza) * 
##     sqrt(sqft_lot15.differenza)
## 
## Parametric coefficients:
##                                                              Estimate
## (Intercept)                                                 9.807e-03
## bedrooms                                                   -2.062e-02
## bathrooms                                                   5.843e-02
## waterfront                                                  4.002e-01
## condition                                                   4.898e-03
## grade                                                       1.518e-01
## view                                                        6.751e-02
## yr_built                                                   -3.368e-03
## lat                                                         6.107e-01
## long                                                        3.713e-01
## sqrt(sqft_basement)                                         1.371e-02
## log(sqft_lot)                                              -3.568e-02
## sqrt(sqft_living15.differenza)                              2.049e-03
## sqrt(sqft_lot15.differenza)                                 6.055e-04
## bedrooms:bathrooms                                         -4.817e-04
## condition:grade                                             7.660e-03
## lat:long                                                   -5.984e-03
## sqrt(sqft_basement):log(sqft_lot)                          -9.475e-04
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza) -7.944e-06
##                                                            Std. Error t value
## (Intercept)                                                 8.687e-04  11.289
## bedrooms                                                    5.891e-03  -3.499
## bathrooms                                                   9.911e-03   5.895
## waterfront                                                  2.185e-02  18.313
## condition                                                   1.818e-02   0.269
## grade                                                       8.691e-03  17.464
## view                                                        2.676e-03  25.229
## yr_built                                                    8.798e-05 -38.280
## lat                                                         4.093e-02  14.922
## long                                                        5.665e-03  65.551
## sqrt(sqft_basement)                                         1.540e-03   8.903
## log(sqft_lot)                                               3.288e-03 -10.853
## sqrt(sqft_living15.differenza)                              2.113e-04   9.700
## sqrt(sqft_lot15.differenza)                                 6.826e-05   8.870
## bedrooms:bathrooms                                          2.397e-03  -0.201
## condition:grade                                             2.455e-03   3.120
## lat:long                                                    3.556e-04 -16.830
## sqrt(sqft_basement):log(sqft_lot)                           1.616e-04  -5.863
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza)  2.272e-06  -3.496
##                                                            Pr(>|t|)    
## (Intercept)                                                 < 2e-16 ***
## bedrooms                                                   0.000467 ***
## bathrooms                                                  3.79e-09 ***
## waterfront                                                  < 2e-16 ***
## condition                                                  0.787655    
## grade                                                       < 2e-16 ***
## view                                                        < 2e-16 ***
## yr_built                                                    < 2e-16 ***
## lat                                                         < 2e-16 ***
## long                                                        < 2e-16 ***
## sqrt(sqft_basement)                                         < 2e-16 ***
## log(sqft_lot)                                               < 2e-16 ***
## sqrt(sqft_living15.differenza)                              < 2e-16 ***
## sqrt(sqft_lot15.differenza)                                 < 2e-16 ***
## bedrooms:bathrooms                                         0.840754    
## condition:grade                                            0.001814 ** 
## lat:long                                                    < 2e-16 ***
## sqrt(sqft_basement):log(sqft_lot)                          4.60e-09 ***
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza) 0.000473 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df     F  p-value    
## s(log(sqft_living)) 7.333  8.177  4.15 5.28e-05 ***
## s(log(sqft_above))  6.254  7.280 22.64  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Rank: 36/37
## R-sq.(adj) =  0.769   Deviance explained = 76.9%
## GCV = 0.064104  Scale est. = 0.06401   n = 21597
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+s(log(sqft_above))+bedrooms+bathrooms+waterfront+condition*grade+view+yr_built+lat*long+sqrt(sqft_basement)*log(sqft_lot)+sqrt(sqft_living15.differenza)*sqrt(sqft_lot15.differenza),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + s(log(sqft_above)) + bedrooms + 
##     bathrooms + waterfront + condition * grade + view + yr_built + 
##     lat * long + sqrt(sqft_basement) * log(sqft_lot) + sqrt(sqft_living15.differenza) * 
##     sqrt(sqft_lot15.differenza)
## 
## Parametric coefficients:
##                                                              Estimate
## (Intercept)                                                 9.817e-03
## bedrooms                                                   -2.164e-02
## bathrooms                                                   5.652e-02
## waterfront                                                  4.007e-01
## condition                                                   5.185e-03
## grade                                                       1.519e-01
## view                                                        6.750e-02
## yr_built                                                   -3.364e-03
## lat                                                         6.112e-01
## long                                                        3.713e-01
## sqrt(sqft_basement)                                         1.363e-02
## log(sqft_lot)                                              -3.579e-02
## sqrt(sqft_living15.differenza)                              2.052e-03
## sqrt(sqft_lot15.differenza)                                 6.057e-04
## condition:grade                                             7.628e-03
## lat:long                                                   -5.980e-03
## sqrt(sqft_basement):log(sqft_lot)                          -9.318e-04
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza) -7.971e-06
##                                                            Std. Error t value
## (Intercept)                                                 8.687e-04  11.300
## bedrooms                                                    2.494e-03  -8.678
## bathrooms                                                   4.142e-03  13.646
## waterfront                                                  2.185e-02  18.342
## condition                                                   1.818e-02   0.285
## grade                                                       8.686e-03  17.487
## view                                                        2.676e-03  25.221
## yr_built                                                    8.755e-05 -38.429
## lat                                                         4.093e-02  14.933
## long                                                        5.664e-03  65.556
## sqrt(sqft_basement)                                         1.541e-03   8.846
## log(sqft_lot)                                               3.289e-03 -10.882
## sqrt(sqft_living15.differenza)                              2.108e-04   9.732
## sqrt(sqft_lot15.differenza)                                 6.829e-05   8.868
## condition:grade                                             2.456e-03   3.106
## lat:long                                                    3.555e-04 -16.820
## sqrt(sqft_basement):log(sqft_lot)                           1.620e-04  -5.751
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza)  2.273e-06  -3.507
##                                                            Pr(>|t|)    
## (Intercept)                                                 < 2e-16 ***
## bedrooms                                                    < 2e-16 ***
## bathrooms                                                   < 2e-16 ***
## waterfront                                                  < 2e-16 ***
## condition                                                  0.775562    
## grade                                                       < 2e-16 ***
## view                                                        < 2e-16 ***
## yr_built                                                    < 2e-16 ***
## lat                                                         < 2e-16 ***
## long                                                        < 2e-16 ***
## sqrt(sqft_basement)                                         < 2e-16 ***
## log(sqft_lot)                                               < 2e-16 ***
## sqrt(sqft_living15.differenza)                              < 2e-16 ***
## sqrt(sqft_lot15.differenza)                                 < 2e-16 ***
## condition:grade                                            0.001896 ** 
## lat:long                                                    < 2e-16 ***
## sqrt(sqft_basement):log(sqft_lot)                          9.01e-09 ***
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza) 0.000455 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df      F  p-value    
## s(log(sqft_living)) 7.955  8.594  4.656 5.42e-06 ***
## s(log(sqft_above))  6.963  7.896 21.465  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Rank: 35/36
## R-sq.(adj) =  0.769   Deviance explained = 76.9%
## GCV = 0.0641  Scale est. = 0.064005  n = 21597
# proviamo a togliere qualche effetto di interazione
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+s(log(sqft_above))+bedrooms+bathrooms+waterfront+condition+grade+view+yr_built+lat*long+sqrt(sqft_basement)*log(sqft_lot)+sqrt(sqft_living15.differenza)*sqrt(sqft_lot15.differenza),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + s(log(sqft_above)) + bedrooms + 
##     bathrooms + waterfront + condition + grade + view + yr_built + 
##     lat * long + sqrt(sqft_basement) * log(sqft_lot) + sqrt(sqft_living15.differenza) * 
##     sqrt(sqft_lot15.differenza)
## 
## Parametric coefficients:
##                                                              Estimate
## (Intercept)                                                 9.620e-03
## bedrooms                                                   -2.166e-02
## bathrooms                                                   5.682e-02
## waterfront                                                  4.002e-01
## condition                                                   6.089e-02
## grade                                                       1.777e-01
## view                                                        6.774e-02
## yr_built                                                   -3.393e-03
## lat                                                         6.023e-01
## long                                                        3.725e-01
## sqrt(sqft_basement)                                         1.368e-02
## log(sqft_lot)                                              -3.532e-02
## sqrt(sqft_living15.differenza)                              2.039e-03
## sqrt(sqft_lot15.differenza)                                 6.007e-04
## lat:long                                                   -6.054e-03
## sqrt(sqft_basement):log(sqft_lot)                          -9.460e-04
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza) -7.804e-06
##                                                            Std. Error t value
## (Intercept)                                                 8.667e-04  11.100
## bedrooms                                                    2.493e-03  -8.687
## bathrooms                                                   4.139e-03  13.730
## waterfront                                                  2.185e-02  18.316
## condition                                                   2.909e-03  20.932
## grade                                                       2.653e-03  66.958
## view                                                        2.675e-03  25.320
## yr_built                                                    8.717e-05 -38.925
## lat                                                         4.084e-02  14.748
## long                                                        5.648e-03  65.955
## sqrt(sqft_basement)                                         1.540e-03   8.885
## log(sqft_lot)                                               3.285e-03 -10.753
## sqrt(sqft_living15.differenza)                              2.108e-04   9.675
## sqrt(sqft_lot15.differenza)                                 6.826e-05   8.800
## lat:long                                                    3.548e-04 -17.064
## sqrt(sqft_basement):log(sqft_lot)                           1.616e-04  -5.853
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza)  2.271e-06  -3.436
##                                                            Pr(>|t|)    
## (Intercept)                                                 < 2e-16 ***
## bedrooms                                                    < 2e-16 ***
## bathrooms                                                   < 2e-16 ***
## waterfront                                                  < 2e-16 ***
## condition                                                   < 2e-16 ***
## grade                                                       < 2e-16 ***
## view                                                        < 2e-16 ***
## yr_built                                                    < 2e-16 ***
## lat                                                         < 2e-16 ***
## long                                                        < 2e-16 ***
## sqrt(sqft_basement)                                         < 2e-16 ***
## log(sqft_lot)                                               < 2e-16 ***
## sqrt(sqft_living15.differenza)                              < 2e-16 ***
## sqrt(sqft_lot15.differenza)                                 < 2e-16 ***
## lat:long                                                    < 2e-16 ***
## sqrt(sqft_basement):log(sqft_lot)                          4.89e-09 ***
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza) 0.000591 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df      F  p-value    
## s(log(sqft_living)) 8.143  8.710  4.147 3.66e-05 ***
## s(log(sqft_above))  5.547  6.636 24.696  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Rank: 34/35
## R-sq.(adj) =  0.769   Deviance explained = 76.9%
## GCV = 0.064123  Scale est. = 0.064035  n = 21597
# proviamo a togliere e aggiungere qualche interazione
fit_AM.updated<-gam(log(price)~s(log(sqft_living))+s(log(sqft_above))+bedrooms+bathrooms+waterfront+condition+grade+view+lat*long+sqrt(sqft_basement)+yr_built*log(sqft_lot)+sqrt(sqft_living15.differenza)*sqrt(sqft_lot15.differenza),data=df,family=gaussian(link="identity"))
summary(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + s(log(sqft_above)) + bedrooms + 
##     bathrooms + waterfront + condition + grade + view + lat * 
##     long + sqrt(sqft_basement) + yr_built * log(sqft_lot) + sqrt(sqft_living15.differenza) * 
##     sqrt(sqft_lot15.differenza)
## 
## Parametric coefficients:
##                                                              Estimate
## (Intercept)                                                 1.327e-02
## bedrooms                                                   -2.104e-02
## bathrooms                                                   5.710e-02
## waterfront                                                  4.057e-01
## condition                                                   6.179e-02
## grade                                                       1.767e-01
## view                                                        6.874e-02
## lat                                                         7.500e-01
## long                                                        3.070e-01
## sqrt(sqft_basement)                                         5.700e-03
## yr_built                                                   -7.408e-03
## log(sqft_lot)                                              -9.688e-01
## sqrt(sqft_living15.differenza)                              2.190e-03
## sqrt(sqft_lot15.differenza)                                 6.916e-04
## lat:long                                                   -4.849e-03
## yr_built:log(sqft_lot)                                      4.665e-04
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza) -1.019e-05
##                                                            Std. Error t value
## (Intercept)                                                 1.064e-03  12.465
## bedrooms                                                    2.495e-03  -8.435
## bathrooms                                                   4.138e-03  13.796
## waterfront                                                  2.190e-02  18.526
## condition                                                   2.910e-03  21.234
## grade                                                       2.662e-03  66.382
## view                                                        2.678e-03  25.672
## lat                                                         4.795e-02  15.641
## long                                                        1.221e-02  25.149
## sqrt(sqft_basement)                                         6.138e-04   9.286
## yr_built                                                    6.770e-04 -10.942
## log(sqft_lot)                                               1.564e-01  -6.192
## sqrt(sqft_living15.differenza)                              2.090e-04  10.475
## sqrt(sqft_lot15.differenza)                                 6.849e-05  10.098
## lat:long                                                    4.094e-04 -11.845
## yr_built:log(sqft_lot)                                      7.892e-05   5.911
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza)  2.262e-06  -4.505
##                                                            Pr(>|t|)    
## (Intercept)                                                 < 2e-16 ***
## bedrooms                                                    < 2e-16 ***
## bathrooms                                                   < 2e-16 ***
## waterfront                                                  < 2e-16 ***
## condition                                                   < 2e-16 ***
## grade                                                       < 2e-16 ***
## view                                                        < 2e-16 ***
## lat                                                         < 2e-16 ***
## long                                                        < 2e-16 ***
## sqrt(sqft_basement)                                         < 2e-16 ***
## yr_built                                                    < 2e-16 ***
## log(sqft_lot)                                              6.03e-10 ***
## sqrt(sqft_living15.differenza)                              < 2e-16 ***
## sqrt(sqft_lot15.differenza)                                 < 2e-16 ***
## lat:long                                                    < 2e-16 ***
## yr_built:log(sqft_lot)                                     3.44e-09 ***
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza) 6.66e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                       edf Ref.df      F p-value    
## s(log(sqft_living)) 7.698  8.431  7.192  <2e-16 ***
## s(log(sqft_above))  6.484  7.485 25.270  <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Rank: 34/35
## R-sq.(adj) =  0.769   Deviance explained = 76.9%
## GCV = 0.064112  Scale est. = 0.064022  n = 21597

Analisi grafiche del modello finale:

plot(fit_AM.updated)

gam.check(fit_AM.updated)

## 
## Method: GCV   Optimizer: magic
## Smoothing parameter selection converged after 10 iterations.
## The RMS GCV score gradient at convergence was 6.384195e-08 .
## The Hessian was positive definite.
## Model rank =  34 / 35 
## 
## Basis dimension (k) checking results. Low p-value (k-index<1) may
## indicate that k is too low, especially if edf is close to k'.
## 
##                       k'  edf k-index p-value
## s(log(sqft_living)) 9.00 7.70    1.03    1.00
## s(log(sqft_above))  9.00 6.48    0.99    0.17
anova(fit_AM.updated)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## log(price) ~ s(log(sqft_living)) + s(log(sqft_above)) + bedrooms + 
##     bathrooms + waterfront + condition + grade + view + lat * 
##     long + sqrt(sqft_basement) + yr_built * log(sqft_lot) + sqrt(sqft_living15.differenza) * 
##     sqrt(sqft_lot15.differenza)
## 
## Parametric Terms:
##                                                            df       F  p-value
## bedrooms                                                    1   71.15  < 2e-16
## bathrooms                                                   1  190.34  < 2e-16
## waterfront                                                  1  343.22  < 2e-16
## condition                                                   1  450.90  < 2e-16
## grade                                                       1 4406.60  < 2e-16
## view                                                        1  659.03  < 2e-16
## lat                                                         1  244.64  < 2e-16
## long                                                        1  632.49  < 2e-16
## sqrt(sqft_basement)                                         1   86.24  < 2e-16
## yr_built                                                    1  119.72  < 2e-16
## log(sqft_lot)                                               1   38.35 6.03e-10
## sqrt(sqft_living15.differenza)                              1  109.73  < 2e-16
## sqrt(sqft_lot15.differenza)                                 1  101.97  < 2e-16
## lat:long                                                    1  140.31  < 2e-16
## yr_built:log(sqft_lot)                                      1   34.95 3.44e-09
## sqrt(sqft_living15.differenza):sqrt(sqft_lot15.differenza)  1   20.30 6.66e-06
## 
## Approximate significance of smooth terms:
##                       edf Ref.df      F p-value
## s(log(sqft_living)) 7.698  8.431  7.192  <2e-16
## s(log(sqft_above))  6.484  7.485 25.270  <2e-16

Il procedimento potrebbe continuare iterandosi fino a trovare il modello ottimale (controllo i vif elimino e ristimo), per lo scopo dell’elaborato ci si è accontentati di quello modello.

CONCLUSIONE

Per giungere ad un modello finale più preciso in termini di variabilità delle stime dei coefficienti si potrebbero utilizzare delle tecniche di shrinkage (quali le tecniche di regressione Ridge o LASSO) per portare a 0 i coefficienti delle covariate responsabili della multicollinearità nel modello. I 2 metodi proposti sono metodi meno empirici rispetto a quello proposto nello script e portano a risultati più precisi.

detach(df)