1. 程式人生 > >【線性迴歸】波斯頓房價預測

【線性迴歸】波斯頓房價預測

# -*- coding: cp936 -*-
from sklearn.datasets import load_boston
boston=load_boston()

from sklearn.cross_validation import train_test_split
import numpy as np
X=boston.data
y=boston.target

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=33)

#分析迴歸目標的差異
print "The max target value is ", np.max(boston.target)
print "The min target value is ", np.min(boston.target)
print  "The average target value is ", np.mean(boston.target)

from sklearn.preprocessing import StandardScaler
ss_X=StandardScaler()
ss_y=StandardScaler()

X_train=ss_X.fit_transform(X_train)
X_test=ss_X.transform(X_test)
y_train=ss_y.fit_transform(y_train.reshape(-1,1))

y_test=ss_y.transform(y_test.reshape(-1,1))


from sklearn.linear_model import LinearRegression
lr=LinearRegression()

lr.fit(X_train,y_train)

lr_y_predict=lr.predict(X_test)

from sklearn.linear_model import SGDRegressor
sgdr=SGDRegressor()

sgdr.fit(X_train,y_train)
sgdr_y_predict=sgdr.predict(X_test)

print "The value of default mearsurement of LinearRegression is",lr.score(X_test,y_test)

from sklearn.metrics import r2_score,mean_squared_error,mean_absolute_error

print "The value of R_squared of LinearRegression is",r2_score(y_test,lr_y_predict)

print "The mean squared error of LinearRegression is",mean_squared_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(lr_y_predict))

print "The mean absolute error of LinearRegression is",mean_absolute_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(lr_y_predict))

查看回歸係數

print lr.intercept_

print lr.coef_

>>> print lr.intercept_
[  5.46047518e-15]
>>> print lr.coef_
[[-0.11286566  0.1306885   0.01207992  0.09054443 -0.17880511  0.31821979
  -0.01744478 -0.33320158  0.26716638 -0.21737875 -0.20384674  0.05662515
  -0.40794066]]