概念
邏輯回歸是一種用于分類問題的機器學習算法,而梯度下降是優化算法,用于更新模型參數以最小化損失函數。在邏輯回歸中,我們使用梯度下降算法來找到最優的模型參數,使得邏輯回歸模型能夠更好地擬合訓練數據。
邏輯回歸中的梯度下降算法的步驟:
偽代碼
初始化參數向量 theta
重復迭代直到收斂或達到最大迭代次數:計算模型預測值 h_theta(x)計算損失函數 J(theta)計算梯度 ?J(theta)/?theta更新參數 theta: theta := theta - learning_rate * gradient
代碼實現
import numpy as npdef sigmoid(z):return 1 / (1 + np.exp(-z))def compute_loss(X, y, theta):m = len(y)h = sigmoid(X.dot(theta))loss = (-1/m) * np.sum(y * np.log(h) + (1 - y) * np.log(1 - h))return lossdef gradient_descent(X, y, theta, learning_rate, num_iterations):m = len(y)losses = []for _ in range(num_iterations):h = sigmoid(X.dot(theta))gradient = X.T.dot(h - y) / mtheta -= learning_rate * gradientloss = compute_loss(X, y, theta)losses.append(loss)return theta, losses# 生成一些模擬數據
np.random.seed(42)
X = np.random.randn(100, 2)
X = np.hstack((np.ones((X.shape[0], 1)), X))
theta_true = np.array([1, 2, 3])
y = (X.dot(theta_true) + np.random.randn(100) * 0.2) > 0# 初始化參數和超參數
theta = np.zeros(X.shape[1])
learning_rate = 0.01
num_iterations = 1000# 執行梯度下降
theta_optimized, losses = gradient_descent(X, y, theta, learning_rate, num_iterations)# 打印優化后的參數
print("優化后的參數:", theta_optimized)# 繪制損失函數下降曲線
import matplotlib.pyplot as plt
plt.plot(losses)
plt.xlabel('迭代次數')
plt.ylabel('損失')
plt.title('損失函數下降曲線')
plt.show()