python写出梯度下降的代码

以下是一个使用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()

值得注意的是这里的Xy分别代表训练数据的特征(特征矩阵)和目标值(向量),theta是一个向量,表示待求解的参数向量(或权重向量)。在这个例子中,我们用随机生成的一些数据来测试算法,可以使用该代码模板来解决其他具体的梯度下降问题。

最后感谢大家的支持!希望大家多多点赞🙏🙏🙏

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值