import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import numpy as np
class ParamData(Dataset):
def __init__(self,file_name):
self.data = torch.Tensor(np.loadtxt(file_name,delimiter = ',')) #first place
def __len__(self):
return self.data.size()[0]
def __getitem__(self,i):
return self.data[i]
class Net(nn.Module):
def __init__(self,in_size,out_size,layer_size=200):
super(Net,self).__init__()
self.layer = nn.Linear(in_size,layer_size)
self.out_layer = nn.Linear(layer_size,out_size)
def forward(self,x):
x = F.relu(self.layer(x))
x = self.out_layer(x)
return x
datafile = 'data1.txt'
net = Net(100,1)
dataset = ParamData(datafile)
n_samples = len(dataset)
#dataset = torch.Tensor(dataset,dtype=torch.double) #second place
#net.float() #thrid place
net.forward(dataset[0]) #fourth place
在文件 data1.txt
中,包含一些数字的 csv 格式文本文件,每个 dataset[i]
是一个大小为100x1的torch.Tensor
对象,数据类型为torch.float64
。错误信息如下:Traceback (most recent call last):
File "Z:\Wrong.py", line 33, in <module>
net.forward(dataset[0])
File "Z:\Wrong.py", line 23, in forward
x = F.relu(self.layer(x))
File "E:\Python38\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
result = self.forward(*input, **kwargs)
File "E:\Python38\lib\site-packages\torch\nn\modules\linear.py", line 87, in forward
return F.linear(input, self.weight, self.bias)
File "E:\Python38\lib\site-packages\torch\nn\functional.py", line 1372, in linear
output = input.matmul(weight.t())
RuntimeError: Expected object of scalar type Double but got scalar type Float for argument #2 'mat2' in call to _th_mm
看起来我应该将dataset
中的数字的dtype更改为torch.double
。我尝试过以下操作:
将第一处的代码更改为
self.data = torch.tensor(np.loadtxt(file_name,delimiter = ','),dtype=torch.double)
将第四处的代码更改为
net.forward(dataset[0].double())
- 取消注释第二或第三处的其中一行
我认为这些是我从类似问题中看到的解决方案,但它们要么会产生新的错误,要么什么都不做。我该怎么办?
更新:所以我通过将第一处更改为以下内容使其工作:
self.data = torch.from_numpy(np.loadtxt(file_name,delimiter = ',')).float()
这很奇怪,因为它恰恰相反于错误提示。这是一个bug吗?我仍然希望有些解释。
.float()
也适用于我。 - tejasvi88