polynomial regression

polynomial regression 即多项式线性回归,是处理面对非线性数据但又想对其使用线性算法时的一种数据转换方式,会增加数据的维度,譬如样本数据为x1,x2,那么转换后的样本特征即为x1, x2, x1*x2, x1^2, x2^2

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

#模拟数据行数
m = 100

#模拟数据
X = 6 * np.random.rand(m, 1) - 3
y = 0.5 * X ** 2 + X + 2 + np.random.randn(m, 1)

plt.plot(X, y, 'b.')

d = {1: 'g-', 2: 'r+', 10: 'y*'}
#进行三个阶数的数据升维
for i in d:
    #实例化一个升维对象
    poly_features = PolynomialFeatures(degree=i, include_bias=False)
    #传入数据升维
    X_poly = poly_features.fit_transform(X)

    #实例化一个线性回归对象
    lin_reg = LinearRegression(fit_intercept=True)
    #传入升维的数据进行训练
    lin_reg.fit(X_poly, y)
    #打印w0和w1
    print(lin_reg.intercept_, lin_reg.coef_)

    #预测值
    y_predict = lin_reg.predict(X_poly)
    #绘制预测值
    plt.plot(X_poly[:, 0], y_predict, d[i])

#显示图形
plt.show()

输出结果如下:
[3.61036953] [[1.00258191]]
[2.00571483] [[1.01848704 0.51823898]]
[1.85307569] [[ 0.48269421 0.74063875 1.26271898 0.32872832 -0.58112407 -0.23199038
0.09218806 0.04284833 -0.00476177 -0.00241229]]
绘制图形如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值