利用sklearn 实现线性回归、非线性回归

代码:

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

# 创建虚拟数据
x = np.array(range(30))
temp_y = 10 + 2 * x + x ** 2 + x ** 3
y = temp_y + 1500 * np.random.normal(size=30)  # 添加噪声
x = x.reshape(30, 1)
y = y.reshape(30, 1)

# 线性回归
clf1 = LinearRegression()
clf1.fit(x, y)
y_l = clf1.predict(x)  # 线性回归预测值

# 非线性回归
ployfeat = PolynomialFeatures(degree=3)  # 根据degree的值转换为相应的多项式(非线性回归)
x_p = ployfeat.fit_transform(x)
clf2 = LinearRegression()
clf2.fit(x_p, y)

print("线性回归方程为: y = {} + {}x".format(clf1.intercept_[0],clf1.coef_[0,0]))
print("非线性回归曲线方程为 y = {}+{}x+{}x^2+{}x^3".format(clf2.intercept_[0],clf2.coef_[0,1],clf2.coef_[0,2],clf2.coef_[0,3]))

def f(x):
    return clf2.intercept_[0]+clf2.coef_[0,1]*(x**1)+clf2.coef_[0,2]*(x**2)+clf2.coef_[0,3]*(x**3)
font={"family":"FangSong",'size':12}
matplotlib.rc("font",**font)

plt.plot(x, clf2.predict(x_p),label="非线性回归_调用预测")
plt.plot(x, f(x),label="非线性回归_写函数拟合预测")
plt.plot(x, y_l,label="线性回归")
plt.scatter(x, y,label="数据")
plt.legend()
plt.show()

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
在Python中,可以使用sklearn库中的LinearRegression模型进行非线性回归。首先,需要导入所需的库和模块,如pandas、numpy、matplotlib等。然后,可以使用PolynomialFeatures函数将特征转换为相应的多项式形式,从而实现非线性回归。接下来,使用LinearRegression模型拟合转换后的特征和目标变量。最后,使用预测值进行可视化展示。\[1\] 在sklearn线性回归模型LinearRegression中,可以使用fit()函数拟合模型,并在模型的coef_属性中存储拟合后的相关系数。可以使用predict()函数进行预测。此外,还可以使用mean_squared_error()函数计算均方误差,使用r2_score()函数计算决定系数。\[2\] 在最小二乘法返回的系数中,默认是不会对系数的正负进行限制的。但是在实际问题中,有时需要将相关系数限制为非负值,可以通过设置LinearRegression模型的positive参数为True来实现。\[3\] #### 引用[.reference_title] - *1* [python sklearn 实现线性回归非线性回归](https://blog.csdn.net/weixin_49583390/article/details/120573540)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [机器学习之Python Sklearn——线性回归](https://blog.csdn.net/ljinddlj/article/details/125087428)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清纯世纪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值