1. 程式人生 > >Python sklearn 庫中嶺迴歸的簡略使用方法

Python sklearn 庫中嶺迴歸的簡略使用方法

import numpy as np # 快速操作結構陣列的工具
import matplotlib.pyplot as plt  # 視覺化繪製
from sklearn.linear_model import RidgeCV  # Ridge嶺迴歸,RidgeCV帶有廣義交叉驗證的嶺迴歸
from sklearn.preprocessing import PolynomialFeatures  # 使資料具有多項式特徵


# 生成資料
x = np.arange(-2, 2, 0.1)
y = -x**3 + 2*x**2 - 3*x + 1 + np.random.rand()*2

x = x.reshape((40, 1))

# 加入多項式特徵,否則預設為一次
poly_reg = PolynomialFeatures(4)  # 最高為4次
x_train = poly_reg.fit_transform(x)

# 宣告模型 訓練模型
Rid_model = RidgeCV(alphas=[0.1, 0.5, 1, 10])
Rid_model.fit(x_train, y)

# 形成新資料
x_2 = np.arange(-5, 5, 0.1)
y_result = -x_2**3 + 2*x_2**2 - 3*x_2 + 1  # 希望得到的預期結果

# 使用模型預測
x_2 = x_2.reshape((100, 1))
x_pre = poly_reg.fit_transform(x_2)
y_predict = Rid_model.predict(x_pre)  # 預測結果

# 繪製散點圖
plt.scatter(x_2, y_result, marker='x', color='blue')
plt.scatter(x, y, marker='x', color='green')
plt.plot(x_2, y_predict, c='r')

# 繪製x軸和y軸座標
plt.xlabel("x")
plt.ylabel("y")

# 顯示圖形
plt.show()

執行結果如下:

可以看到,擬合曲線(紅色)和期望影象(藍色的點)大致相同。