神经网络学习笔记9-简单的反向传播和线性回归

tensor在pytorch中是一个非常重要的类型
在这里插入图片描述
在这里插入图片描述
假如需要计算梯度,就将tensor中 requires_grad设为true
在这里插入图片描述
loss是一个张量,在做运算时构建运算图,因此不要直接进行,会将将梯度存入w,当反向传播完成 后,该计算图会被释放
在这里插入图片描述
这里注意一下grad即梯度也是一个tensor类型,要取到data才能做运算

import torch

x_data=[1.0,2.0,3.0]#x
y_data=[2.0,4.0,6.0]#y
w=torch.Tensor([1.0])
w.requires_grad=True

def forward(x):
    return x*w#w是一个tensor,就是梯度

def loss(x,y):
    y_pred=forward(x)
    return (y_pred-y)**2#损失值

print('predict (before training)',4,forward(4).item())
for epoch in range(100):
    for x,y in zip(x_data,y_data):
        l=loss(x,y)
        l.backward()#自动调用偏导
        print('/tgrad:',x,y,w.grad.item())
        w.grad.data.zero_()

    print('progress:',epoch,l.item())

print('predict(after training)',4,forward(4).item())

在这里插入图片描述
线性回归就是一个最简单的只有一个神经元的神经网络

import torch

x_data=torch.tensor([[1.0],[2.0],[3.0]])#x
y_data=torch.tensor([[2.0],[4.0],[6.0]])#y
class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        self.linear=torch.nn.Linear(1,1)

    def forward(self,x):
        y_pred=self.linear(x)
        return y_pred

model=LinearModel()
criterion=torch.nn.MSELoss(size_average=False)
optimistic=torch.optim.SGD(model.parameters(),lr=0.01)
for epoch in range(100):
    y_pred=model(x_data)
    loss=criterion(y_pred,y_data)
    print(epoch,loss.item())

    optimistic.zero_grad()#清除梯度
    loss.backward()#计算梯度
    optimistic.step()#更新参数

print('w=',model.linear.weight.item())
print('b=',model.linear.bias.item())
x_test=torch.Tensor([[4.0]])
y_test=model(x_test)
print('y_pred=',y_test.data)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值