课程请见 《PyTorch深度学习实践》
用numpy适配了一下,均改成了numpy.ndarray类型
# Numpy import numpy # For plotting import matplotlib.pyplot as plt from matplotlib.pyplot import figure def forward(w, x): return x * w def cost(x_cor, y_cor, w): y_hat = forward(w, x_cor) loss = (y_hat - y_cor) ** 2 return loss.sum() / len(x_cor) def gradient(x_cor, y_cor, w): grad = 2 * x_cor * (w * x_cor - y_cor) return grad.sum() / len(x_cor) x_data = numpy.array([1.0, 2.0, 3.0]) y_data = numpy.array([2.0, 4.0, 6.0]) num_epochs = 100 lr = 0.01 w_train = numpy.array([1.0]) epoch_cor = [] loss_cor = [] for epoch in range(num_epochs): mse_loss = cost(x_data, y_data, w_train) loss_cor.append(mse_loss) w_train -= lr * gradient(x_data, y_data, w_train) epoch_cor.append(epoch + 1) plt.figure() plt.plot(epoch_cor, loss_cor, c='b') plt.xlabel('Epoch') plt.ylabel('Cost') plt.show()
最终效果和老师的 一模一样
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)