概念
通過使用 NumPy 數組來進行矩陣運算,將循環操作向量化。
向量化的好處在于它可以同時處理多個樣本,從而加速計算過程。在實際應用中,尤其是處理大規模數據集時,向量化可以顯著提高代碼的效率。
代碼實現-以邏輯回歸為例
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 batch_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)
m = 100
n = 2
X = np.random.randn(m, n)
X = np.hstack((np.ones((m, 1)), X))
theta_true = np.array([1, 2, 3])
y = (X.dot(theta_true) + np.random.randn(m) * 0.2) > 0# 初始化參數和超參數
theta = np.zeros(X.shape[1])
learning_rate = 0.01
num_iterations = 1000# 執行批量梯度下降(向量化)
theta_optimized, losses = batch_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()