2744557306 发表于 2023-11-29 11:30

PyTorch深度学习——梯度下降算法、随机梯度下降算法及实例


根据化简之后的公式,就可以编写代码,对 https://latex.csdn.net/eq?w 进行训练,具体代码如下:import numpy as np
import matplotlib.pyplot as plt

x_data =
y_data =

w = 1.0


def forward(x):
    return x * w


def cost(xs, ys):
    cost = 0
    for x, y in zip(xs, ys):
        y_pred = forward(x)
        cost += (y_pred - y) ** 2
        return cost / len(xs)


def gradient(xs, ys):
    grad = 0
    for x, y in zip(xs, ys):
        grad += 2 * x * (x * w - y)
        return grad / len(xs)


print('训练前的预测', 4, forward(4))

cost_list = []
epoch_list = []
# 开始训练(100次训练)
for epoch in range(150):
    epoch_list.append(epoch)
    cost_val = cost(x_data, y_data)
    cost_list.append(cost_val)
    grad_val = gradient(x_data, y_data)
    w -= 0.1 * grad_val
    print('Epoch:', epoch, 'w=', w, 'loss=', cost_val)

print('训练之后的预测', 4, forward(4))

# 画图

plt.plot(epoch_list, cost_list)
plt.ylabel('Cost')
plt.xlabel('Epoch')
plt.show() 运行截图如图所示:

Epoch是训练次数,Cost是误差,可以看到随着训练次数的增加,误差越来越小,趋近于0.
随机梯度下降算法       随机梯度下降算法与梯度下降算法的不同之处在于,随机梯度下降算法不再计算损失函数之和的导数,而是随机选取任一随机函数计算导数,随机的决定 https://latex.csdn.net/eq?w 下次的变化趋势,具体公式变化如图:
具体代码如下:import numpy as np
import matplotlib.pyplot as plt

x_data =
y_data =

w = 1.0


def forward(x):
    return x * w


def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) ** 2


def gradient(x, y):
    return 2 * x * (x * w - y)


print('训练前的预测', 4, forward(4))

epoch_list = []
loss_list = []
# 开始训练(100次训练)
for epoch in range(100):
    for x, y in zip(x_data, y_data):

        grad = gradient(x, y)
        w -= 0.01 * grad
        l = loss(x, y)
        loss_list.append(l)
        epoch_list.append(epoch)
        print('Epoch:', epoch, 'w=', w, 'loss=', l)

print('训练之后的预测', 4, forward(4))

# 画图
plt.plot(epoch_list, loss_list)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.grid(1)
plt.show()运行截图如图所示


页: [1]
查看完整版本: PyTorch深度学习——梯度下降算法、随机梯度下降算法及实例