岭回归
数据
#数据
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
x = np.random.uniform(-3,3,size=100)
#在最新版本的sklearn中,所有的数据都应该是二维矩阵,哪怕它只是单独一行或一列。
X = x.reshape(-1,1)
y = 0.5 * x + 3 +np.random.normal(0,1,size=100)
plt.scatter(x,y)#非线性关系
#使用多项式回归
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
def PolynomialRegression(degree):
return Pipeline([('poly',PolynomialFeatures(degree=degree)),
('std_scaler',StandardScaler()),
('lin_reg',LinearRegression())
])
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=666)
from sklearn.metrics import mean_squared_error
poly_reg = PolynomialRegression(degree=20)
poly_reg.fit(X_train,y_train)
y_poly_predict = poly_reg.predict(X_test)
print(mean_squared_error(y_test,y_poly_predict))
167.9401085999025
根据算法画拟合图
def plot_model(model):
X_plot = np.linspace(-3,3,100).reshape(100,1)#不加reshpe则大小为(100,)
y_plot = model.predict(X_plot)
plt.scatter(x,y)
plt.axis([-3,3,0,6])
plt.plot(X_plot[:,0],y_plot,color = 'r')
plot_model(poly_reg)
使用岭回归,a=0.0001
#使用岭回归
from sklearn.linear_model import Ridge
def RidgeRegression(degree,alpha):
return Pipeline([('poly',PolynomialFeatures(degree=degree)),
('std_scaler',StandardScaler()),
('lin_reg',Ridge(alpha = alpha))
])
ridge1_reg = RidgeRegression(20,0.0001)
ridge1_reg.fit(X_train,y_train)
y1_predict = ridge1_reg.predict(X_test)
print(mean_squared_error(y_test,y1_predict))
1.3233492754136291
plot_model(ridge1_reg)
a=1
ridge2_reg = RidgeRegression(20,1)
ridge2_reg.fit(X_train,y_train)
y2_predict = ridge2_reg.predict(X_test)
print(mean_squared_error(y_test,y2_predict))
1.1888759304218461
plot_model(ridge2_reg)
a = 100
ridge2_reg = RidgeRegression(20,100)
ridge2_reg.fit(X_train,y_train)
y2_predict = ridge2_reg.predict(X_test)
print(mean_squared_error(y_test,y2_predict))
plot_model(ridge2_reg)
1.3196456113086197
a非常大所有参数都正则为0了。。。
ridge2_reg = RidgeRegression(20,1000000)#所有的参数都是0
ridge2_reg.fit(X_train,y_train)
y2_predict = ridge2_reg.predict(X_test)
print(mean_squared_error(y_test,y2_predict))
plot_model(ridge2_reg)
1.8404103153255003