Thursday, February 25, 2021

Chapter 5 Cross Validation and Bootstrap within Python - An Introduction to Statistical Learning

Chapter 5 Cross Validation and Bootstrap - An Introduction to Statistical Learning
In [3]:
import numpy as np
import pandas as pd
import seaborn as sns; sns.set(style="ticks", color_codes=True)
In [4]:
import random 
In [5]:
random.seed(1)
In [6]:
data=pd.read_csv('data/Auto.csv')
data=data.query('horsepower!="?"')
data.horsepower=data.horsepower.astype(float)
In [7]:
data.info()
#data.describe()
#data
<class 'pandas.core.frame.DataFrame'>
Int64Index: 392 entries, 0 to 396
Data columns (total 9 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   mpg           392 non-null    float64
 1   cylinders     392 non-null    int64  
 2   displacement  392 non-null    float64
 3   horsepower    392 non-null    float64
 4   weight        392 non-null    int64  
 5   acceleration  392 non-null    float64
 6   year          392 non-null    int64  
 7   origin        392 non-null    int64  
 8   name          392 non-null    object 
dtypes: float64(4), int64(4), object(1)
memory usage: 30.6+ KB
In [8]:
sns.pairplot(data)
Out[8]:
<seaborn.axisgrid.PairGrid at 0x1a7d2e70bc8>

The Validation Set Approach

In [9]:
from sklearn.model_selection import train_test_split, cross_val_score
In [10]:
import statsmodels.api as sm
In [11]:
X_train,X_test,Y_train,Y_test=train_test_split(data['horsepower'],data['mpg'],train_size=0.5,random_state=1)
In [12]:
X_train=sm.add_constant(X_train)
X_test=sm.add_constant(X_test)
In [13]:
model=sm.OLS(Y_train.values, X_train.values).fit()
In [14]:
result=model.predict(X_train)
In [15]:
model.summary2()
##model.params
Out[15]:
Model: OLS Adj. R-squared: 0.589
Dependent Variable: y AIC: 1176.2438
Date: 2021-02-25 17:29 BIC: 1182.8000
No. Observations: 196 Log-Likelihood: -586.12
Df Model: 1 F-statistic: 280.5
Df Residuals: 194 Prob (F-statistic): 1.54e-39
R-squared: 0.591 Scale: 23.411
Coef. Std.Err. t P>|t| [0.025 0.975]
const 39.5927 1.0142 39.0366 0.0000 37.5923 41.5931
x1 -0.1565 0.0093 -16.7494 0.0000 -0.1749 -0.1381
Omnibus: 10.071 Durbin-Watson: 1.989
Prob(Omnibus): 0.007 Jarque-Bera (JB): 10.764
Skew: 0.453 Prob(JB): 0.005
Kurtosis: 3.704 Condition No.: 319
In [16]:
np.mean(np.power(Y_train-model.predict(X_train),2))
Out[16]:
23.172322563688425
In [17]:
np.mean(np.power(Y_test-model.predict(X_test),2))
Out[17]:
24.80212062059357
In [18]:
from sklearn.linear_model import LinearRegression
modelLR=LinearRegression().fit(X_train,Y_train)
In [19]:
[modelLR.score(X_train,Y_train),modelLR.score(X_test,Y_test)]
Out[19]:
[0.5911842631021546, 0.6171465759570591]

Cross validationan

In [20]:
from sklearn.base import BaseEstimator, RegressorMixin
import statsmodels.formula.api as smf
import statsmodels.api as sm

class statsmodelWrapper(BaseEstimator, RegressorMixin):
    def __init__(self,sm_class, formula):
        self.sm_class=sm_class
        self.formula=formula
        self.model=None
        self.result=None
        
    def fit(self, data, dummy):
        self.model=self.sm_class(self.formula,data)
        self.result=self.model.fit()
        
    def predict(self,X):
        return self.result.predict(X)
In [21]:
clf=statsmodelWrapper(smf.ols,'mpg~horsepower')
print(cross_val_score(clf, data, data['mpg']))

print(cross_val_score(LinearRegression(),data.mpg.values.reshape(-1,1), data.horsepower.values.reshape(-1,1)))
[ 0.25974614  0.22407146  0.46461149  0.58162628 -0.8530173 ]
[ 0.46476843  0.53280893  0.51880556  0.61093923 -2.0148546 ]
In [ ]:
 
In [22]:
cross_val_score(LinearRegression(),X_train,Y_train,cv=10)
Out[22]:
array([0.51516668, 0.56196179, 0.67685129, 0.46963916, 0.40504475,
       0.6815238 , 0.53331848, 0.79942425, 0.53038482, 0.68772824])

Leave One Out

In [27]:
from sklearn.model_selection import LeaveOneOut

loo=LeaveOneOut()
loo_data=list(loo.split(data))
for train,test in loo_data[:3]:
    print("train:%s\n test:%s"% (train,test))
train:[  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
 379 380 381 382 383 384 385 386 387 388 389 390 391]
 test:[0]
train:[  0   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
 379 380 381 382 383 384 385 386 387 388 389 390 391]
 test:[1]
train:[  0   1   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
 379 380 381 382 383 384 385 386 387 388 389 390 391]
 test:[2]

Bootstraping

In [26]:
from sklearn.utils import resample

N=10000
params=[]
for i in range(N):
    rData=resample(data)
    
    res=smf.ols("mpg~horsepower",rData).fit()
    params.append(res.params)
In [28]:
#from ols 
#const	39.5927	1.0142	39.0366	0.0000	37.5923	41.5931
#x1	-0.1565	0.0093	-16.7494	0.0000	-0.1749	-0.1381
[np.mean(params,axis=0),np.std(params,axis=0)]
Out[28]:
[array([39.97204   , -0.15829978]), array([0.85114726, 0.00736643])]
In [ ]:
 

No comments: