邏輯回歸(Logistic Regression)是一種廣泛應用于分類問題的機器學習算法。盡管名字中帶有“回歸”,但它實際上是一種分類算法,常用于二分類問題。邏輯回歸的核心思想是通過一個線性模型來預測樣本屬于某個類別的概率,然后通過一個閾值將概率轉換為類別標簽。
在本文中,我們將介紹如何使用Python實現梯度下降算法來求解邏輯回歸模型。
邏輯回歸模型的核心是sigmoid函數,它將線性模型的輸出映射到[0, 1]區間,表示樣本屬于正類的概率。sigmoid函數的定義如下:
\[ \sigma(z) = \frac{1}{1 + e^{-z}} \]
其中,\(z\) 是線性模型的輸出:
\[ z = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \dots + \theta_n x_n \]
邏輯回歸的目標是通過優化損失函數來找到最佳的模型參數 \(\theta\)。常用的損失函數是交叉熵損失函數:
\[ 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)}))] \]
其中,\(h_\theta(x)\) 是sigmoid函數,\(y^{(i)}\) 是樣本的真實標簽,\(m\) 是樣本數量。
梯度下降是一種常用的優化算法,通過迭代更新模型參數來最小化損失函數。梯度下降的更新公式如下:
\[ \theta_j := \theta_j - \alpha \frac{\partial J(\theta)}{\partial \theta_j} \]
其中,\(\alpha\) 是學習率,控制參數更新的步長。
對于邏輯回歸,損失函數 \(J(\theta)\) 對參數 \(\theta_j\) 的偏導數為:
\[ \frac{\partial J(\theta)}{\partial \theta_j} = \frac{1}{m} \sum_{i=1}^{m} (h_\theta(x^{(i)}) - y^{(i)}) x_j^{(i)} \]
下面我們使用Python實現梯度下降算法來求解邏輯回歸模型。
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def compute_cost(X, y, theta):
m = len(y)
h = sigmoid(X @ theta)
cost = (-1/m) * np.sum(y * np.log(h) + (1 - y) * np.log(1 - h))
return cost
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
cost_history = []
for i in range(num_iters):
h = sigmoid(X @ theta)
gradient = (1/m) * (X.T @ (h - y))
theta = theta - alpha * gradient
cost = compute_cost(X, y, theta)
cost_history.append(cost)
return theta, cost_history
假設我們有一個簡單的二分類數據集:
X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
y = np.array([0, 0, 1, 1, 1])
# 添加偏置項
X = np.hstack((np.ones((X.shape[0], 1)), X))
# 初始化參數
theta = np.zeros(X.shape[1])
# 設置學習率和迭代次數
alpha = 0.01
num_iters = 1000
theta, cost_history = gradient_descent(X, y, theta, alpha, num_iters)
plt.plot(range(num_iters), cost_history)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.title('Cost Function over Iterations')
plt.show()
def predict(X, theta):
return sigmoid(X @ theta) >= 0.5
predictions = predict(X, theta)
print("Predictions:", predictions)
本文介紹了如何使用Python實現梯度下降算法來求解邏輯回歸模型。我們首先介紹了邏輯回歸的基本原理和梯度下降算法,然后通過Python代碼實現了模型的訓練和預測。通過可視化損失函數的變化,我們可以觀察到模型在訓練過程中逐漸收斂。
邏輯回歸是一種簡單但非常有效的分類算法,廣泛應用于各種實際問題中。通過理解其基本原理并掌握實現方法,可以為后續學習更復雜的機器學習算法打下堅實的基礎。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。