本博客参考书籍:scikit-learn机器学习:常用算法原理及编程实战
我们使用sklearn自带的波士顿房价数据集来预测模型,然后用模型来测算房价
关于load_boston()函数请参考:数据集–load_boston()函数
导入数据集,将数据集进行分割
import time
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
boston=load_boston()
x=boston.data
y=boston.target
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=3)
print(x_train.shape,x_test.shape,y_train.shape,y_test.shape)
>>> (404, 13) (102, 13) (404,) (102,)
创建并训练模型,得出模型的训练集得分和测试集得分
model=LinearRegression()
start=time.time()
model.fit(x_train,y_train)
train_score=model.score(x_train,y_train)
cv_score=model.score(x_test,y_test)
print(time.time()-start,train_score,cv_score)
>>> 0.0038423538208007812 0.7239410298290111 0.7952617563243853
从得分中我们可以看出训练样本评分和测试集样本评分都比较低,这是欠拟合的表现,下面我们对模型进行优化
from sklearn.preprocessing import PolynomialFeatures,StandardScaler
from sklearn.pipeline import Pipeline
def polynomial_model(degree=1):
polynomial_feature=PolynomialFeatures(degree=degree,include_bias=False)
lin=LinearRegression()
pipeline=Pipeline([('ss',StandardScaler()),('pf',polynomial_feature),('lin',lin)])
return pipeline
我们在建立管线pipeline时候向管线中加入了StandardScaler()类,用于将数据集中的数据进行归一化处理,然后加入了PolynomialFeature()类用于向模型中添加多项式特征,以增加模型复杂度,下面我们来看程序的运行结果
model2=polynomial_model(degree=2)
model2.fit(x_train,y_train)
train_score2=model2.score(x_train,y_train)
cv_score2=model2.score(x_test,y_test)
print(train_score2,cv_score2)
>>> 0.9305468799409319 0.8600492818189015
观察两个评分我们看到我们采取的优化措施起效果了!