sklearn线性回归完成多次项函数和正弦函数拟合

9 篇文章 0 订阅
3 篇文章 0 订阅
本文通过Python的sklearn库展示了如何使用线性回归和多项式特征处理对数据进行拟合。分别展示了二阶、三阶和六阶拟合的效果,并通过 MSE 分析了拟合质量。六阶拟合虽然效果好,但可能存在过拟合风险。
摘要由CSDN通过智能技术生成

这样两个式子,使用sklearn 线性回归进行拟合

y=0.015*x^{3}+0.07*x^{2}+6*x

y=0.5\sin x+2

 

直接上代码

import random
import numpy as np
from sklearn.linear_model import LinearRegression,Ridge
from sklearn.metrics import accuracy_score, mean_squared_error, r2_score,mean_squared_log_error
from sklearn.utils.multiclass import type_of_target
from sklearn.preprocessing import PolynomialFeatures #多项式特征处理
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt
plt.figure()

#data prepare
X = np.linspace(-50,50,100)
# X = np.sin(X)
print(X.shape)
y = 0.015*np.power(X,3)+0.07*np.power(X,2)+6*X+3+np.random.normal(0,100,100)


X = X.reshape(-1,1)
y = y.reshape(-1,1)

#生成N阶多项式
degree = 3
ploy_features = PolynomialFeatures(degree=degree, include_bias=False)
model = LinearRegression(normalize=True) # 线性归回模型实例化,病进行数据标准化
pipline = Pipeline([('ploy_features', ploy_features),('model',model)])
pipline.fit(X,y)
y_predict = pipline.predict(X)
train_score = pipline.score(X,y)
mse = mean_squared_error(y,y_predict)
print(train_score)
print(mse)
print(pipline.get_params())

plt.scatter(X,y, marker='o', c='r')
plt.scatter(X,y_predict,marker='o',c='g')
plt.show()

得到结果:

score :   0.9902512046606555
mse :  7940.310765934783

画图结果:

对于正玄曲线原始数据画图

y=0.5\sin x+2

 

degree定成三阶拟合图

 

 degree定成二阶拟合图

degree定成六阶拟合图,效果非常好,但不知道是不是有点过拟合了、?

 

 话不多说,直接上代码:

import random
import numpy as np
from sklearn.linear_model import LinearRegression,Ridge
from sklearn.metrics import accuracy_score, mean_squared_error, r2_score,mean_squared_log_error
from sklearn.utils.multiclass import type_of_target
from sklearn.preprocessing import PolynomialFeatures #多项式特征处理
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt
plt.figure()

#data prepare
X = np.linspace(-5,5,150)
# X = np.sin(X)
print(X.shape)
y = 0.5*np.sin(X)+np.random.normal(0,0.05,150)


X = X.reshape(-1,1)
y = y.reshape(-1,1)

#生成N阶多项式
degree = 6
ploy_features = PolynomialFeatures(degree=degree, include_bias=False)
model = LinearRegression(normalize=True) # 线性归回模型实例化,病进行数据标准化
pipline = Pipeline([('ploy_features', ploy_features),('model',model)])
pipline.fit(X,y)
y_predict = pipline.predict(X)
train_score = pipline.score(X,y)
mse = mean_squared_error(y,y_predict)
print(train_score)
print(mse)
print(pipline.get_params())

plt.scatter(X,y, marker='o', c='r')
plt.scatter(X,y_predict,marker='o',c='g')
plt.show()

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现拟合分段函数的多元线性回归,可以通过引入分段函数的指示变量来实现。具体来说,可以将自变量按照分段点进行分段,然后对于每个分段引入一个指示变量,表示该自变量是否在该分段内。 例如,假设有两个自变量 X1 和 X2,要拟合两个分段的分段函数,可以将 X1 和 X2 分别按照分段点进行分段,得到四个区间。然后引入四个指示变量,分别表示 X1 和 X2 是否在每个区间内。这样,就可以将分段函数转化为多元线性回归的形式。 在 sklearn 中,可以使用 PolynomialFeatures 类来进行多式特征转换,将自变量转化为多式特征,并引入指示变量。然后使用 LinearRegression 类进行拟合。具体实现可以参考以下示例代码: ```python from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression # 定义分段点 segment_points = [1, 2] # 生成多式特征 poly = PolynomialFeatures(degree=1, include_bias=False) X_poly = poly.fit_transform(X) # 引入指示变量 X_indicator = np.zeros((X.shape[0], len(segment_points) + 1)) for i, p in enumerate(segment_points): X_indicator[:, i] = (X[:, 0] >= p) X_indicator[:, -1] = 1 # 拼接多式特征和指示变量 X_new = np.hstack((X_poly, X_indicator)) # 拟合线性回归模型 reg = LinearRegression().fit(X_new, y) ``` 其中,X 是自变量的样本数据,y 是因变量的样本数据。segment_points 是分段点的列表,degree 是多式特征的次数。最终得到的 X_new 包含了多式特征和指示变量,可以用于拟合线性回归模型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值