pytorch 机器学习例子(深度学习例子)

RNN

LSTM

import torch
lstm:torch.nn.LSTM=torch.nn.LSTM(5,3,num_layers=2)
param_ls=list(lstm.named_parameters())
end=True

在这里插入图片描述

import torch
lstm:torch.nn.LSTM=torch.nn.LSTM(input_size=5,hidden_size=3,num_layers=1)
param_ls=list(lstm.named_parameters())
end=True

在这里插入图片描述

mnist lstm

import torch
import torch.nn.functional

IMG_H=28
IMG_W=28
MNIST_CLASS_CNT=10
TRAINING_SAMPLE_CNT=5
learning_rate=0.1

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.lstm_layer_cnt=1
        self.lstm_hidden_size=16
        self.lstm_input_size=IMG_W
        self.lstm=torch.nn.LSTM(input_size=self.lstm_input_size,hidden_size=self.lstm_hidden_size,num_layers=self.lstm_layer_cnt,batch_first=True)
        self.fc = torch.nn.Linear(in_features=self.lstm_hidden_size, out_features=MNIST_CLASS_CNT)

    def forward(self,x):
        batch_size=x.size(0)
        h0=torch.zeros(self.lstm_layer_cnt,batch_size,self.lstm_hidden_size)
        c0 = torch.zeros(self.lstm_layer_cnt, batch_size, self.lstm_hidden_size)
        out,hidden=self.lstm(x,(h0,c0))
        end_out=out[:,-1,:]
        fc_out=self.fc(end_out)
        ŷ = torch.log_softmax(input=fc_out,dim=1)
        return ŷ

x=torch.randn((TRAINING_SAMPLE_CNT,IMG_H,IMG_W),dtype=torch.float)
y=torch.zeros((TRAINING_SAMPLE_CNT),dtype=torch.long)
net=Net()
optimizer=torch.optim.Adam(params=net.parameters(),lr=learning_rate)
print(f"net:{net}")
"""
Net(
  (lstm): LSTM(28, 16, batch_first=True)
  (fc): Linear(in_features=16, out_features=10, bias=True)
)"""

#train:
#forward
ŷ=net(x)
loss:torch.Tensor=torch.nn.functional.nll_loss(input=ŷ,target=y)

#backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
end=True

在这里插入图片描述

GRU

attention

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ziix

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值