多项式回归(波士顿房价预测)
导入模块
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
%matplotlib inline
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')
获取数据
在《代码-普通线性回归》的时候说到特征LSTAT和标记MEDV有最高的相关性,但是它们之间并不是线性关系,因此这次尝试使用多项式回归拟合它们之间的关系。
df = pd.read_csv('housing-data.txt', sep='\s+', header=0)
X = df[['LSTAT']].values
y = df['MEDV'].values
训练模型
# 增加二次方,即二项式回归
quadratic = PolynomialFeatures(degree=2)
# 增加三次方,即三项式回归
cubic = PolynomialFeatures(degree=3)
# 训练二项式和三项式回归得到二次方和三次方的X
X_quad = quadratic.fit_transform(X)
X_cubic = cubic.fit_transform(X)
# 增加x轴坐标点
X_fit = np.arange(X.min(), X.max(), 1)[:, np.newaxis]
lr = LinearRegression()
# 线性回归
lr.fit(X, y)
lr_predict = lr.predict(X_fit)
# 计算线性回归的R2值
lr_r2 = r2_score(y, lr.predict(X))
# 二项式回归
lr = lr.fit(X_quad, y)
quad_predict = lr.predict(quadratic.fit_transform(X_fit))
# 计算二项式回归的R2值
quadratic_r2 = r2_score(y, lr.predict(X_quad))
# 三项式回归
lr = lr.fit(X_cubic, y)
cubic_predict = lr.predict(cubic.fit_transform(X_fit))
# 计算三项式回归的R2值
cubic_r2 = r2_score(y, lr.predict(X_cubic))
print(lr.score(X_cubic, y))
print(cubic_r2)
0.6578476405895719
0.6578476405895719