邏輯回歸的數學模型
基本模型
邏輯回歸主要用于處理二分類問題。二分類問題對于模型的輸出包含 0 和 1,是一個不連續的值。分類問題的結果一般不能由線性函數求出。這里就需要一個特別的函數來求解,這里引入一個新的函數 Sigmoid 函數,也成為邏輯函數。
h θ ( x ) = g ( θ T x ) z = θ T x g ( z ) = 1 1 + e ? z h_\theta(x) = g(\theta^Tx) \\ z = \theta^Tx \\ g(z) = \frac{1}{1 + e^{-z}} hθ?(x)=g(θTx)z=θTxg(z)=1+e?z1?
這里函數 g ( z ) g(z) g(z) 將任何實數映射到了 ( 0 , 1 ) (0, 1) (0,1) 區間中,從而將任何值函數轉換為適合分類的函數。這里我們將線性回歸模型函數插入到這個函數中形成新的邏輯回歸模型。
如圖所示,轉換后可以看到在 x = 0 x = 0 x=0 處有一個明顯的變化,兩邊的函數值無限接近于 0 和 1,而中間的交界處則根據輸出來判斷如何分類,例如 h θ ( x ) = 0.7 h_\theta(x) = 0.7 hθ?(x)=0.7 則表示有 70% 的概率輸出為 1。
決策邊界
決策邊界(Decision boundary)即為輸出的分界點。二分類問題的輸出是離散的零一分類,也就是說:
h θ ( x ) ≥ 0.5 → y = 1 h θ ( x ) < 0.5 → y = 0 h_\theta(x) \ge 0.5 \rarr y = 1 \\ h_\theta(x) < 0.5 \rarr y = 0 hθ?(x)≥0.5→y=1hθ?(x)<0.5→y=0
那么此處由 Sigmoid 函數的性質可以得到:
θ T x ≥ 0 ? y = 1 θ T x < 0 ? y = 0 \theta^T x \ge 0 \Rightarrow y = 1 \\ \theta^T x < 0 \Rightarrow y = 0 θTx≥0?y=1θTx<0?y=0
那么此處根據輸入 x x x 來判斷輸出從當前值跳變到另一個值的邊界,即為決策邊界。在上面 Sigmoid 函數的實例圖中,假設輸入函數僅是簡單的 z = x z = x z=x,并且認為當 h θ ( x ) ≥ 0.5 h_\theta(x) \ge 0.5 hθ?(x)≥0.5 時,輸出 y = 1 y = 1 y=1,那么可以看到, x = 0 x = 0 x=0? 即為其決策邊界。
在更復雜的情況下,假設
θ T x = θ 0 + θ 1 x 1 + θ 2 x 2 \theta^T x = \theta_0 + \theta_1 x_1 + \theta_2 x_2 θTx=θ0?+θ1?x1?+θ2?x2?
那么通過變形可得到
θ 0 + θ 1 ? x = ? θ 2 ? y y = θ 0 + θ 1 ? x θ 2 \theta_0 + \theta_1 \cdot x = - \theta_2 \cdot y \\ y = \frac{\theta_0 + \theta_1 \cdot x}{\theta_2} θ0?+θ1??x=?θ2??yy=θ2?θ0?+θ1??x?
代價函數
根據模型的代價函數(Cost function)即可根據對當前參數的評估最后找到最優解,邏輯回歸的代價函數定義為:
J ( θ ) = 1 m ∑ i = 1 m C o s t ( h θ ( x ( i ) ) , y ( i ) ) C o s t ( h θ ( x ) , y ) = ? log ? ( h θ ( x ) ) if? y = 1 C o s t ( h θ ( x ) , y ) = ? log ? ( 1 ? h θ ( x ) ) if? y = 0 J(\theta) = \frac{1}{m}\sum^m_{i = 1}\mathrm{Cost}(h_\theta(x^{(i)}), y^{(i)}) \\ \begin{align} &\mathrm{Cost}(h_\theta(x), y) = -\log(h_\theta(x)) & \text{ if } y = 1 \\ &\mathrm{Cost}(h_\theta(x), y) = -\log(1 - h_\theta(x)) & \text{ if } y = 0 \\ \end{align} J(θ)=m1?i=1∑m?Cost(hθ?(x(i)),y(i))?Cost(hθ?(x),y)=?log(hθ?(x))Cost(hθ?(x),y)=?log(1?hθ?(x))??if?y=1?if?y=0??
這里可以看出,當 y = 1 and? h θ ( x ) → 0 y = 1 \text{ and } h_\theta(x) \rarr 0 y=1?and?hθ?(x)→0 時,損失函數的值會趨向于無窮,可以直觀看到損失函數對模型預測與實際值的差距評估。機器學習的主要目標就是要將損失函數降到最低,以求得最優模型。
梯度下降
通過梯度下降(Gradient descent)找到最優解,首先將代價函數轉化為如下形式。不難看出在某一情況時,另一種情況會被化為 0,這樣做的目的是方便編程:
C o s t ( h θ ( x ) , y ) = ? y log ? ( θ ( x ) ) ? ( 1 ? y ) log ? ( 1 ? h θ ( x ) ) \mathrm{Cost}(h_\theta(x), y) = - y \log(\theta(x)) - (1 - y) \log(1 - h_\theta(x)) Cost(hθ?(x),y)=?ylog(θ(x))?(1?y)log(1?hθ?(x))
那么整個代價函數如下:
J ( θ ) = ? 1 m ∑ i = 1 m [ y ( i ) log ? ( h θ ( x ( i ) ) ) + ( 1 ? y ( i ) ) log ? ( 1 ? h θ ( x ( i ) ) ) ] J(\theta) = -\frac{1}{m}\sum_{i = 1}^{m}[y^{(i)}\log(h_\theta(x^{(i)})) + (1 - y^{(i)}) \log(1 - h\theta(x^{(i)}))] J(θ)=?m1?i=1∑m?[y(i)log(hθ?(x(i)))+(1?y(i))log(1?hθ(x(i)))]
則可以求出梯度下降迭代的步驟:
θ j : = θ j ? α ? J ( θ ) ? θ j 即? θ j : = θ j ? α m ∑ i = 1 m ( h θ ( x ( i ) ) ? y ( i ) ) x j ( i ) \theta_j := \theta_j - \alpha\frac{\partial{J(\theta)}}{\partial{\theta_j}} \\ \text{即 } \theta_j := \theta_j - \frac{\alpha}{m}\sum^m_{i = 1}(h_\theta(x^{(i)}) - y^{(i)})x_j^{(i)} θj?:=θj??α?θj??J(θ)?即?θj?:=θj??mα?i=1∑m?(hθ?(x(i))?y(i))xj(i)?
Sklearn 邏輯回歸模型
數據整理
假設有一份學生的成績單和大學錄取的名單,學生們通過兩門考試的兩門分數來被決定是否被錄取。這是一個兩個特征的二分類問題,首先整理一下數據。
data = pd.read_csv('ex2data1.txt', names=['exam1', 'exam2', 'is_admitted'])
print(data.head())# 將數據拆分成是否錄取的兩批,繪制散點
positive = data[data['is_admitted'] == 1]
negative = data[data['is_admitted'] == 0]fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(positive['exam1'], positive['exam2'], s=50, c='b', alpha=0.5, label='Admitted')
ax.scatter(negative['exam1'], negative['exam2'], s=50, c='r', alpha=0.5, label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')
plt.show()
exam1 exam2 admitted
0 34.623660 78.024693 0
1 30.286711 43.894998 0
2 35.847409 72.902198 0
3 60.182599 86.308552 1
4 79.032736 75.344376 1
邏輯回歸模型
這里將從上面讀取的數據傳遞給定義的邏輯回歸的模型,并訓練得到模型參數。
X = data[['exam1', 'exam2']].values
Y = data['is_admitted'].values# 定義并訓練模型
model = LogisticRegression()
model.fit(X, Y)print("Model Coefficients:", model.coef_)
print("Intercept:", model.intercept_)
Model Coefficients: [[0.20535491 0.2005838 ]]
Intercept: [-25.05219314]
驗證
驗證模型的準確性,首先從模型中取出相關參數,即為 θ \theta θ 。這里需要說明一下數學模型中與 Sklearn 邏輯回歸模型的屬性,首先求出決策邊界:
y = θ 0 + θ 1 ? x θ 2 y = \frac{\theta_0 + \theta_1 \cdot x}{\theta_2} y=θ2?θ0?+θ1??x?
這里 θ 0 \theta_0 θ0? 為偏置, θ 1 \theta_1 θ1? 和 θ 2 \theta_2 θ2? 是每個特征的系數。兩者分別對應了兩個屬性。
coef = model.coef_[0]
intercept = model.intercept_[0]
x = np.linspace(30, 100, 1000)
y = -(coef[0] * x + intercept) / coef[1]fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(positive['exam1'], positive['exam2'], s=50, c='b', alpha=0.5, label='Admitted')
ax.scatter(negative['exam1'], negative['exam2'], s=50, c='r', alpha=0.5, label='Not Admitted')
ax.plot(x, y, label='Decision Boundary', c='grey')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')
plt.show()
最后可以看出決策邊界較好的分割了兩類點集。