PyTorch深度学习实践第三集 梯度下降 y=wx

import random

import numpy as np
import matplotlib.pyplot as plt

x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]


def forward(x, w):
    y_p = w * x
    return y_p


def loss(x, y, w):
    y_p = forward(x, w)
    loss_ = (y - y_p) * (y - y_p)
    return loss_


w_list = []
mse_list = []

epoch=100
lr=0.01
w=random.randint(0,10)
epoch_list=range(epoch)
for i in range(epoch):
    l_sum = 0
    grad=0
    w_list.append(w)
    for x, y in zip(x_data, y_data):
        loss_ = loss(x, y, w)
        l_sum += loss_
        grad+=2*x*(x*w-y)
    cost=l_sum / len(x_data)
    grad=grad/len(x_data)
    w=w-lr*grad
    mse_list.append(cost)

plt.plot(epoch_list, mse_list)
plt.show()

你可能感兴趣的:(Pytorch,python,机器学习,人工智能)