RuntimeError: mat1 and mat2 must have the same dtype, but got Long and Float

刘二第十二个视频中

# 序列到序列RNN
import torch
from torch import nn

input_size = 4
hidden_size = 4
batch_size = 1

# 字母列表
idx_char = ['e', 'h', 'l', 'o']
x_data = [1, 0, 2, 2, 3]  # hello
y_data = [3, 1, 2, 3, 2]  # ohlol

# 每个字母的独热编码
one_hot_lookup = [[1, 0, 0, 0],   # e
                  [0, 1, 0, 0],   # h
                  [0, 0, 1, 0],   # l
                  [0, 0, 0, 1]]   # o

x_one_hot = [one_hot_lookup[x] for x in x_data]  # [[0,1,0,0], [1,0,0,0], [0,0,1,0], [0,0,1,0], [0,0,0,1]]
# print(x_one_hot)

inputs = torch.tensor(x_one_hot).reshape(-1, batch_size, input_size)
# print(inputs)

labels = torch.LongTensor(y_data).reshape(-1, 1)
# print(labels)


class Model(nn.Module):
    def __init__(self, input_size, hidden_size, batch_size):
        super().__init__()
        self.batch_size = batch_size
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.rnncell = nn.RNNCell(input_size=self.input_size,
                                  hidden_size=self.hidden_size)

    def forward(self, input, hidden):
        hidden = self.rnncell(input, hidden)
        return hidden

    def init_hidden(self):
        return torch.zeros(self.batch_size, self.hidden_size)


net = Model(input_size, hidden_size, batch_size)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.1)

for epoch in range(15):
    loss = 0
    optimizer.zero_grad()
    hidden = net.init_hidden()
    print('Predict string:', end='')
    for input, label in zip(inputs, labels):
        hidden = net(input, hidden)
        loss += criterion(hidden, label)
        _, idx = hidden.max(dim=1)
        print(idx_char[idx.item()], end='')
    loss.backward()
    optimizer.step()
    print(', Epoch[%d/15] loss=%.4f' % (epoch + 1, loss.item()))


报错: RuntimeError: mat1 and mat2 must have the same dtype, but got Long and Float

  1. 在创建输入 inputs 张量时,添加 .float() 来确保输入数据的类型是浮点数(float),这是因为模型的权重和偏置通常需要浮点数来进行计算。

  2. 在创建标签 labels 张量时,添加了 .long() 来确保标签数据的类型是长整型(long),这是因为 CrossEntropyLoss 需要标签为长整型。

inputs = torch.tensor(x_one_hot).float().reshape(-1, batch_size, input_size)
labels = torch.tensor(y_data).long().reshape(-1, 1)

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值