機器學習——迴歸模型

一、線性迴歸


迴歸的目的是預測數值型的目標值。最直接的辦法是依據輸入寫出一個目標值的計算公式,該公式就是所謂的迴歸方程(regression equation)。求迴歸方程中的迴歸係數的過程就是迴歸。

線性迴歸的幾個特點: 1. 建模速度快,不需要很複雜的計算,在數據量大的情況下依然運行速度很快。 2. 可以根據係數給出每個變量的理解和解釋 3. 對異常值很敏感。

在這裏插入圖片描述

# 代碼表示:linear_model.LinearRegression()

二、嶺迴歸

嶺迴歸實質上就是在線性迴歸的基礎上加了L2正則化項。
在這裏插入圖片描述

領回歸的特點:

  1. 領回歸的假設和最小平方迴歸相同,但是在最小平方迴歸的時候我們假設數據服從高斯分佈使用的是極大似然估計(MLE),在領回歸的時候由於添加了偏差因子,即w的先驗信息,使用的是極大後驗估計(MAP)來得到最終的參數
  2. 沒有特徵選擇功能
# 代碼表示:linear_model.Ridge(0.5) 

三、LASSO迴歸

LASSO迴歸在線性迴歸的基礎上加了L1正則化項。
在這裏插入圖片描述

L1正則化和L2正則化的區別: L1正則化會使得一些權重直接變爲0,L2正則化只是將一些權重的值變的更小。L1跟拉普拉斯有關,L2跟高斯分佈有關。

# 代碼表示:linear_model.Lasso(0.1)
  1. 嶺迴歸和Lasso迴歸之間的差異可以歸結爲L1正則和L2正則之間的差異: 內置的特徵選擇(Built-in feature selection):這是L1範數很有用的一個屬性,L2範數不具有這種特性。因爲L1範數傾向於產生係數。例如,模型中有100個係數,但其中只有10個係數是非零係數,也就是說只有這10個變量是有用的,其他90個都是沒有用的。而L2範數產生非稀疏係數,所以沒有這種屬性。因此可以說Lasso迴歸做了一種參數選擇形式,未被選中的特徵變量對整體的權重爲0。
  2. 稀疏性:指矩陣或向量中只有極少個非零係數。L1範數產生具有零值或具有很少大系數或者非常小的係數的屬性。

四、彈性迴歸網絡

彈性網絡是將L1和L2正則化組合在一起使用。
在這裏插入圖片描述

# 代碼表示:linear_model.ElasticNet(0.5,0.5)

在Lasso和嶺迴歸之間進行權衡的一個實際是運行彈性網絡在循環的情況下繼承嶺迴歸的一些穩定性。 彈性迴歸網絡的優點:

  1. 鼓勵在高度相關變量的情況下的羣體效應,而不像Lasso那樣將其中一些置爲0。當多個特徵和另一個特徵相關的時候彈性網絡非常有用。Lasso傾向於隨機選擇其中一個,而彈性網絡傾向於選擇兩個。
  2. 對所選變量的數量沒有限制。

五、邏輯斯蒂迴歸

邏輯迴歸是加了激活函數sigmoid = 1 / 1+exp(-x),也就是將線性迴歸的結果映射到0到1上。它的本質就是加上了非線性函數,擬合能力更強。
在這裏插入圖片描述

# 代碼表示:linear_model.LogisticRegression()

六、貝葉斯嶺迴歸

在這裏插入圖片描述

# 代碼表示:linear_model.BayesianRidge()

七、核嶺迴歸

在這裏插入圖片描述

import numpy as np
from sklearn.kernel_ridge import KernelRidge
import matplotlib.pyplot as plt
from sklearn.model_selection import GridSearchCV

rng = np.random.RandomState(0)

X = 5 * rng.rand(100, 1)
y = np.sin(X).ravel()

# Add noise to targets
y[::5] += 3 * (0.5 - rng.rand(X.shape[0] // 5))
# kr = KernelRidge(kernel='rbf', gamma=0.4)
kr = KernelRidge(kernel='sigmoid', gamma=0.4)
kr.fit(X, y)
print(kr.best_score_, kr.best_params_)

X_plot = np.linspace(0, 5, 100)
y_kr = kr.predict(X_plot[:, None])

plt.scatter(X, y)
plt.plot(X_plot, y_kr, color="red")
plt.show()

八、超級調參工具(表格搜索法)

利用模塊GridSearchCV,可以找出到模型最優時候的超參數

import numpy as np
from sklearn.kernel_ridge import KernelRidge
import matplotlib.pyplot as plt
from sklearn.model_selection import GridSearchCV

rng = np.random.RandomState(0)

X = 5 * rng.rand(100, 1)
y = np.sin(X).ravel()

# Add noise to targets
y[::5] += 3 * (0.5 - rng.rand(X.shape[0] // 5))

# kr = KernelRidge(kernel='rbf', gamma=0.4)
kr = GridSearchCV(KernelRidge(),
                  param_grid={"kernel": ["rbf", "laplacian", "polynomial", "sigmoid"],
                              "alpha": [1e0, 0.1, 1e-2, 1e-3],
                              "gamma": np.logspace(-2, 2, 5)})
kr.fit(X, y)
# print(kr.best_score_, kr.best_params_)

X_plot = np.linspace(0, 5, 100)
y_kr = kr.predict(X_plot[:, None])

plt.scatter(X, y)
plt.plot(X_plot, y_kr, color="red")
plt.show()

import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR

rng = np.random.RandomState(0)

X = 5 * rng.rand(100, 1)
y = np.sin(X).ravel()

y[::5] += 3 * (0.5 - rng.rand(X.shape[0] // 5))

svr = GridSearchCV(SVR(kernel='rbf'),
                   param_grid={"C": [1e0, 1e1, 1e2, 1e3],
                               "gamma": np.logspace(-2, 2, 5)})
svr.fit(X, y)
print(svr.best_score_, svr.best_params_)

X_plot = np.linspace(0, 5, 100)
y_svr = svr.predict(X_plot[:, None])

plt.scatter(X, y)
plt.plot(X_plot, y_svr, color="red")
plt.show()

九、迴歸的評價方法

在這裏插入圖片描述在這裏插入圖片描述

十、代碼實現

# 普通線性迴歸
from sklearn import linear_model
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, explained_variance_score

np.random.RandomState(0)

x, y = datasets.make_regression(n_samples=500, n_features=1, n_targets=1, noise=10)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)

# 普通線性迴歸
reg = linear_model.LinearRegression()
# 嶺迴歸
# reg = linear_model.Ridge(0.5)
# LASSO迴歸
# reg = linear_model.Lasso(0.1)
# 彈性網絡
# reg = linear_model.ElasticNet(0.5,0.5)
# 邏輯斯蒂迴歸
# reg = linear_model.LogisticRegression()
# 貝葉斯迴歸
# reg = linear_model.BayesianRidge()

reg.fit(x_train, y_train)
# print(reg.coef_, reg.intercept_)

y_pred = reg.predict(x_test)

# 平均絕對誤差
print(mean_absolute_error(y_test, y_pred))
# 均方誤差
print(mean_squared_error(y_test, y_pred))
# R2 評分
print(r2_score(y_test, y_pred))
# explained_variance
print(explained_variance_score(y_test, y_pred))

_x = np.array([-2.5, 2.5])
_y = reg.predict(_x[:,None])

plt.scatter(x_test, y_test)
plt.plot(_x, _y, linewidth=3, color="orange")
plt.show()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章