pytorch 实现二层神经网络

1.实现二层神经网络 

代码来自https://www.bilibili.com/video/BV12741177Cu?p=1,感谢!!!

import torch
import torch.nn as nn
# 实现两层神经网络

# 1.数据
b,input,hidden,output=64,1000,100,10
x=torch.randn(b,input)
y=torch.randn(b,output)

# 2.构建模型
class TwoLayer(nn.Module):
    def __init__(self,input,hidden,output):
        super(TwoLayer,self).__init__()
        self.linear1=nn.Linear(input,hidden)
        self.relu=nn.ReLU()
        self.linear2=nn.Linear(hidden,output)
       
    def forward(self,x):
        return nn.Sequential(self.linear1,self.relu,self.linear2)(x)    # 注意(x)

model=TwoLayer(input,hidden,output)
# 将模型送到gpu训练,对应的输入也应该放到gpu上
model=model.cuda()
# 此步还可以初始化模型参数   torch.nn.init._normal(model[0].weight)

# 3.设置损失函数和优化器

loss_fn=torch.nn.MSELoss(reduction='sum')

lr=1e-4
optimizer=torch.optim.Adam(model.parameters(),lr)  
# 注意要优化的对象,model.parameters()  ,以及传入学习率   lr

# 4.训练迭代
for i in range(500):
    # 前向传播
    y_pred=model(x.cuda())   # 传入参数要加cuda()

    # 计算损失函数
    loss=loss_fn(y_pred.cuda(),y.cuda())     # 传入参数要加cuda()
    print(i,loss.item())

    # 清空之前的梯度
    optimizer.zero_grad()

    # 损失函数反向传播
    loss.backward()

    # 更新weight,bias
    optimizer.step()

2.优化器

torch.optim.Adam(,)

torch.optim.SGD()

torch.optim.Momentum()

torch.optim.

3.损失函数

torch.nn.MSELoss(reduction='sum')

题外话。。。

2020.6.11 今天小ig 在季后赛 1:3 tes , 0:3 fpx, 0:3 msc, 0:2 we 太难了...

心情复杂,好久没赢过,似乎不知道怎么赢了。

猜你喜欢

转载自blog.csdn.net/qq_40297851/article/details/106698295