这样两个式子,使用sklearn 线性回归进行拟合
直接上代码
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
画图结果:
对于正玄曲线原始数据画图
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()