Pytorch:将 FloatTensor 转换为 DoubleTensor [英] Pytorch: Convert FloatTensor into DoubleTensor
问题描述
我有 2 个 numpy 数组,我将它们转换为张量以使用 TensorDataset 对象.
I have 2 numpy arrays, which I convert into tensors to use the TensorDataset object.
import torch.utils.data as data_utils
X = np.zeros((100,30))
Y = np.zeros((100,30))
train = data_utils.TensorDataset(torch.from_numpy(X).double(), torch.from_numpy(Y))
train_loader = data_utils.DataLoader(train, batch_size=50, shuffle=True)
当我这样做时:
for batch_idx, (data, target) in enumerate(train_loader):
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data) # error occurs here
我收到了以下错误:
TypeError: addmm_ 收到了一个无效的参数组合 - 得到了 (int, int, torch.DoubleTensor, torch.FloatTensor),但需要以下之一:[...]
*(浮动 beta,浮动 alpha,torch.DoubleTensor mat1,torch.DoubleTensor mat2)不匹配,因为某些参数的类型无效:(int, int, torch.DoubleTensor, torch.FloatTensor)
*(浮动 beta,浮动 alpha,torch.SparseDoubleTensor mat1,torch.DoubleTensor mat2)不匹配,因为某些参数的类型无效:(int, int, torch.DoubleTensor, torch.FloatTensor)
TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.DoubleTensor, torch.FloatTensor), but expected one of: [...]
* (float beta, float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2) didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, torch.FloatTensor)
* (float beta, float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2) didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, torch.FloatTensor)
最后一个错误来自:
output.addmm_(0, 1, input, weight.t())
output.addmm_(0, 1, input, weight.t())
正如您在我的代码中看到的,我尝试使用 .double() 转换张量 - 但这不起作用.为什么他将一个数组转换为 FloatTensor 对象,而将另一个数组转换为 DoubleTensor?有什么想法吗?
As you see in my code I tried converting the tensor by using .double() - but this did not work. Why is he casting one array into a FloatTensor object and the other into a DoubleTensor? Any ideas?
推荐答案
您的 numpy
数组是 64 位浮点
,将被转换为 torch.DoubleTensor
标准.现在,如果您将它们与您的模型一起使用,您需要确保您的模型参数也是 Double
.或者你需要确保你的 numpy
数组被转换为 Float
,因为模型参数被标准转换为 float
.
Your numpy
arrays are 64-bit floating point
and will be converted to torch.DoubleTensor
standardly. Now, if you use them with your model, you'll need to make sure that your model parameters are also Double
. Or you need to make sure, that your numpy
arrays are cast as Float
, because model parameters are standardly cast as float
.
因此,请执行以下任一操作:
Hence, do either of the following:
data_utils.TensorDataset(torch.from_numpy(X).float(), torch.from_numpy(Y).float())
或者做:
model.double()
Depeding,如果您想将模型参数、输入和目标转换为 Float
或 Double
.
Depeding, if you want to cast your model parameters, inputs and targets as Float
or as Double
.
这篇关于Pytorch:将 FloatTensor 转换为 DoubleTensor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!