ML实战:线性回归+多项式回归
- 本次实验采用的数据集是sklearn内置的波斯顿房价数据集
代码实现
from sklearn import datasets
from sklearn.linear_model import LinearRegression
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
import sys
np.set_printoptions(suppress=True)#取消科学计数法输出
x=datasets.load_boston().data
y=datasets.load_boston().target
#初始化数据集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)
#拆分成训练集和测试集,测试集占20%
X = np.arange(1, len(y_test) + 1)
#用于画图使用
def showres(y_predict,name=None):
#画图打印结果
plt.figure(figsize=(20,8),dpi=80)
plt.title(name)
plt.plot(X,y_test,label='real',color='red')
plt.scatter(X,y_test,color='blue')
plt.plot(X,y_predict,label='predict',color='green')
plt.scatter(X,y_predict,color='blue')
plt.legend(loc=[1, 0])
#plt.savefig('E:/Python/ml/pic/LinearRegression_'+name+".png")
def linear_poly():
#多项式回归
poly=PolynomialFeatures(degree=2)#设置阶数为2
x_train_poly=poly.fit_transform(x_train)
x_test_poly=poly.fit_transform(x_test)
linear=LinearRegression()
linear.fit(x_train_poly,y_train)
showres(linear.predict(x_test_poly),name='PolynomialFeatures')
def linear():
#线性回归
transfer=StandardScaler()
x_train_standard=transfer.fit_transform(x_train)
x_test_standard=transfer.fit_transform(x_test)
linear=LinearRegression()
linear.fit(x_train_standard,y_train)
showres(linear.predict(x_test_standard),name='LinearRegression')
linear()
linear_poly()
sys.exit(0)
结果
线性回归
多项式回归