Python 如何修复 RuntimeError“标量类型 Float 的预期对象但参数为 Double 的标量类型”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56741087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:37:49  来源:igfitidea点击:

How to fix RuntimeError "Expected object of scalar type Float but got scalar type Double for argument"?

pythonneural-networkdeep-learningclassificationpytorch

提问by Shawn Zhang

I'm trying to train a classifier via PyTorch. However, I am experiencing problems with training when I feed the model with training data. I get this error on y_pred = model(X_trainTensor):

我正在尝试通过 PyTorch 训练分类器。但是,当我为模型提供训练数据时,我遇到了训练问题。我收到此错误y_pred = model(X_trainTensor)

RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'

运行时错误:标量类型 Float 的预期对象,但参数 #4 'mat1' 的标量类型为 Double

Here are key parts of my code:

以下是我的代码的关键部分:

# Hyper-parameters 
D_in = 47  # there are 47 parameters I investigate
H = 33
D_out = 2  # output should be either 1 or 0
# Format and load the data
y = np.array( df['target'] )
X = np.array( df.drop(columns = ['target'], axis = 1) )
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8)  # split training/test data

X_trainTensor = torch.from_numpy(X_train) # convert to tensors
y_trainTensor = torch.from_numpy(y_train)
X_testTensor = torch.from_numpy(X_test)
y_testTensor = torch.from_numpy(y_test)
# Define the model
model = torch.nn.Sequential(
    torch.nn.Linear(D_in, H),
    torch.nn.ReLU(),
    torch.nn.Linear(H, D_out),
    nn.LogSoftmax(dim = 1)
)
# Define the loss function
loss_fn = torch.nn.NLLLoss() 
for i in range(50):
    y_pred = model(X_trainTensor)
    loss = loss_fn(y_pred, y_trainTensor)
    model.zero_grad()
    loss.backward()
    with torch.no_grad():       
        for param in model.parameters():
            param -= learning_rate * param.grad

回答by MilkyWay90

Reference is from this github issue.

参考来自这个 github 问题

When the error is RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1', you would need to use the .float()function since it says Expected object of scalar type Float.

当错误为 时RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1',您将需要使用该.float()函数,因为它说Expected object of scalar type Float

Therefore, the solution is changing y_pred = model(X_trainTensor)to y_pred = model(X_trainTensor.float()).

因此,解决方案正在更改y_pred = model(X_trainTensor)y_pred = model(X_trainTensor.float())

Likewise, when you get another error for loss = loss_fn(y_pred, y_trainTensor), you need y_trainTensor.long()since the error message says Expected object of scalar type Long.

同样,当您收到 另一个错误时loss = loss_fn(y_pred, y_trainTensor),您需要,y_trainTensor.long()因为错误消息说Expected object of scalar type Long

You could also do model.double(), as suggested by @Paddy .

您也可以model.double()按照@Paddy 的建议进行操作。

回答by Shubham Mishra

I had same issue

我有同样的问题

resolved

解决

Before converting to Tensor, try this

在转换为张量之前,试试这个

X_train = X_train.astype(np.float32)

回答by Rohit Choudhary

The issue can be fixed by setting the datatype of input to Double i.e torch.float32

该问题可以通过将输入的数据类型设置为 Double 来解决,即 torch.float32

I hope the issue came because your datatype is torch.float16

我希望这个问题是因为你的数据类型是 torch.float16

回答by Dmitriy Ershov

This issue can also occur if the wrong loss function is selected. For example, if you have regression problem, but you are trying to use cross entropy loss. Then it will be fixed by changing your loss function on MSE

如果选择了错误的损失函数,也会出现此问题。例如,如果您有回归问题,但您正在尝试使用交叉熵损失。然后它将通过更改 MSE 上的损失函数来修复