Python sklearn线性回归实战:从欠拟合到多项式特征与算法对比
本文通过sklearn演示线性回归案例,分析波士顿房价数据的欠拟合问题。介绍如何使用Pipeline构建多项式特征以优化模型,对比不同degree下的训练与测试得分,揭示过拟合风险。最后深入比较梯度下降与正规方程两种求解方式的适用场景与优缺点,为模型选择提供参考。
线性回归基础案例与欠拟合分析
利用一阶线性方程对波士顿房价数据进行预测分析。
所载入的数据随sklearn库一同发布,源自1993年之前收集的506个房屋样本及其价格信息。通过调用load_boston()函数即可加载该数据集。
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import time
from sklearn.linear_model import LinearRegression
boston = load_boston()
X = boston.data
y = boston.target
print("X.shape:{}. y.shape:{}".format(X.shape, y.shape))
print('boston.feature_name:{}'.format(boston.feature_names))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=3)
model = LinearRegression()
start = time.clock()
model.fit(X_train, y_train)
train_score = model.score(X_train, y_train)
cv_score = model.score(X_test, y_test)
print('time used:{0:.6f}; train_score:{1:.6f}, sv_score:{2:.6f}'.format((time.clock()-start),
train_score, cv_score))
代码执行后的输出结果如下所示:
X.shape:(506, 13). y.shape:(506,)
boston.feature_name:['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO'
'B' 'LSTAT']
time used:0.012403; train_score:0.723941, sv_score:0.794958
观察输出可知,测试集上的准确率表现不佳,这通常表明模型存在欠拟合现象。
多项式特征优化与模型选择
尝试使用多项式特征进行线性回归建模。
前述示例中出现的欠拟合情况,反映出模型过于简单,无法充分拟合数据分布。为此,我们引入多项式特征以增加模型的复杂度。
举例说明,若原始特征包含[a, b]两个变量,
当设定degree为2时,生成的多项式特征将扩展为[1, a, b, a^2, ab, b^2]。对于其他degree值,特征扩展方式依此类推。
引入多项式特征实质上增加了数据维度和模型复杂度,从而有助于提升拟合效果。
以下代码利用Pipeline将多项式特征生成与线性回归模型连接,最终测试degree分别为1、2、3时的模型得分。
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import time
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
def polynomial_model(degree=1):
polynomial_features = PolynomialFeatures(degree=degree, include_bias=False)
linear_regression = LinearRegression(normalize=True)
pipeline = Pipeline([('polynomial_features', polynomial_features),
('linear_regression', linear_regression)])
return pipeline
boston = load_boston()
X = boston.data
y = boston.target
print("X.shape:{}. y.shape:{}".format(X.shape, y.shape))
print('boston.feature_name:{}'.format(boston.feature_names))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=3)
for i in range(1,4):
print( 'degree:{}'.format( i ) )
model = polynomial_model(degree=i)
start = time.clock()
model.fit(X_train, y_train)
train_score = model.score(X_train, y_train)
cv_score = model.score(X_test, y_test)
print('time used:{0:.6f}; train_score:{1:.6f}, sv_score:{2:.6f}'.format((time.clock()-start),
train_score, cv_score))
程序运行输出结果如下:
X.shape:(506, 13). y.shape:(506,)
boston.feature_name:['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO'
'B' 'LSTAT']
degree:1
time used:0.003576; train_score:0.723941, sv_score:0.794958
degree:2
time used:0.030123; train_score:0.930547, sv_score:0.860465
degree:3
time used:0.137346; train_score:1.000000, sv_score:-104.429619
结果显示,degree为1的情况与未使用多项式特征时一致。而degree为3时,训练集得分达到1,但测试集得分为负数,这表明模型出现了明显的过拟合。
因此,最终应选择degree为2的模型配置。
尽管二阶多项式模型表现优于一阶,但训练集与测试集之间的得分差距依然较大。这可能源于数据量不足,需要更多数据来进一步提升模型准确度。
梯度下降与正规方程求解对比
对比正规方程解法与梯度下降法。
除了使用梯度下降法逐步逼近最优解外,还可以利用正规方程直接计算出最终的最优解。
参考吴恩达课程中的推导,线性回归的最优解公式为:
theta = (X^T * X)^-1 * X^T * y
实际上,这两种方法各有优劣:
梯度下降法:
缺点:需要手动选择学习率,且需进行多次迭代计算。
优点:当特征值数量庞大(超过1万)时,仍能保持较好的运行速度。
正规方程解法:
优点:无需设置学习率,也无需进行多次迭代。
缺点:需要计算X的转置矩阵及其逆矩阵,时间复杂度为O^3;当特征值数量庞大(超过1万)时,计算速度会显著变慢。
在分类等非线性计算场景中,正规方程解法并不适用,因此梯度下降法的适用范围更为广泛。
以上关于sklearn结合Python的线性回归案例分享完毕,希望能为读者提供有价值的参考,欢迎继续关注与支持。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













