以下是一个使用Python实现的基本梯度下降(Gradient Descent)算法的示例:
# 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
# 定义损失函数
def compute_cost(X, y, theta):
m = len(y)
J = 0
predictions = X.dot(theta)
sqrErrors = (predictions - y) ** 2
J = 1 / (2 * m) * np.sum(sqrErrors)
return J
# 梯度下降算法
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = np.zeros((num_iters, 1))
for i in range(num_iters):
predictions = X.dot(theta)
errors = predictions - y
theta = theta - alpha / m * X.T.dot(errors)
J_history[i] = compute_cost(X, y, theta)
return theta, J_history
# 测试代码
# 随机生成一些数据
x = 2 * np.random.rand(100, 1)
y = 4 + 3 * x + np.random.randn(100, 1)
# 在数据中添加x0=1
X_b = np.c_[np.ones((100, 1)), x]
# 初始化theta
theta = np.random.randn(2, 1)
# 定义迭代次数和学习率
iterations = 1000
learning_rate = 0.1
# 运行梯度下降算法
theta, J_history = gradient_descent(X_b, y, theta, learning_rate, iterations)
# 输出最终结果
print("最终参数值:", theta)
print("损失函数值:", J_history[-1])
# 绘制代价函数曲线
plt.plot(J_history)
plt.xlabel("迭代次数")
plt.ylabel("代价函数")
plt.show()
值得注意的是这里的X
和y
分别代表训练数据的特征(特征矩阵)和目标值(向量),theta
是一个向量,表示待求解的参数向量(或权重向量)。在这个例子中,我们用随机生成的一些数据来测试算法,可以使用该代码模板来解决其他具体的梯度下降问题。
最后感谢大家的支持!希望大家多多点赞
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)