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

这样两个式子,使用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

画图结果:

sklearn线性回归完成多次项函数和正弦函数拟合_第1张图片

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

y=0.5\sin x+2

 sklearn线性回归完成多次项函数和正弦函数拟合_第2张图片

degree定成三阶拟合图

sklearn线性回归完成多次项函数和正弦函数拟合_第3张图片

 

 degree定成二阶拟合图

sklearn线性回归完成多次项函数和正弦函数拟合_第4张图片

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

sklearn线性回归完成多次项函数和正弦函数拟合_第5张图片

 

 话不多说,直接上代码:

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()

你可能感兴趣的:(深度学习,算法,Python,sklearn,线性回归,机器学习)