代码实现
import numpy as np
def 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 loss
def compute_gradient(X, y, theta):
m = len(y)
h = sigmoid(X.dot(theta))
gradient = X.T.dot(h - y) / m
return gradient
def batch_gradient_descent(X, y, theta, learning_rate, num_iterations):
m = len(y)
losses = []
for _ in range(num_iterations):
gradient = compute_gradient(X, y, theta)
theta -= learning_rate * gradient
loss = 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()
我们首先定义了 compute_gradient 函数,它计算梯度向量。然后,在 batch_gradient_descent 函数中使用向量化的梯度计算,从而避免了循环操作。
这种向量化的梯度计算方法可以有效地处理多个样本,从而提高代码的性能。