gpt4 book ai didi

python - RuntimeError : Expected a Tensor of type torch. FloatTensor 但发现序列元素的类型 torch.IntTensor

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:41 24 4
gpt4 key购买 nike

我想用 python 生成一些随机数,并用 pytorch 将其转换为张量。这是我生成随机数并将其转换为张量的代码。

import numpy as np
import torch

P = np.random.uniform(0.5, 1, size=[20, 1])
k = np.random.randint(1, 20, size=[20, 1])
d_k = np.random.uniform(0, np.sqrt(80000), size=[20, 1])

P = torch.from_numpy(P).float()
k = torch.from_numpy(k).int()
d_k = torch.from_numpy(d_k).float()

torch.cat((P, k, d_k), dim=-1)

之后,我收到一些错误,显示:

RuntimeError: Expected a Tensor of type torch.FloatTensor but found a type torch.IntTensor for sequence element 1 in sequence argument at position #1 'tensors'

最佳答案

该错误是因为 k 张量的 dtype 为 torch.int32,而其他张量 Pd_k 为数据类型为torch.float32。但是cat操作要求所有输入张量都具有相同的类型。来自 documentation

torch.cat(tensors, dim=0, out=None) → Tensor

tensors (sequence of Tensors) – any python sequence of tensors of the same type.

解决方案之一是将 k 转换为 float dtype,如下所示:

k = torch.from_numpy(k).float()

关于python - RuntimeError : Expected a Tensor of type torch. FloatTensor 但发现序列元素的类型 torch.IntTensor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54403933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com