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

我想用火炬训练一个分类器。然而,当我向模型提供训练数据时,我遇到了训练方面的问题。 我在 y_pred = model(X_trainTensor)上得到这个错误:

RuntimeError: 预期的标量类型为 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
211155 次浏览

参考资料来自 这个 Github 问题

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

因此,解决方案是将 y_pred = model(X_trainTensor)改为 y_pred = model(X_trainTensor.float())

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

你也可以做 model.double(),就像@Paddy 建议的那样 .

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

我希望问题出现了,因为您的数据类型是 torch.float64

您可以在设置数据时避免这种情况,正如其他答案中所解释的那样,或者使模型类型也与您的数据相同。即使用 float64或 float32。

对于 debug,输出 objec.dtype 并检查一致性。

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

在转换为 Tensor之前,请尝试这样做

X_train = X_train.astype(np.float32)

尝试使用: Target = target.float () # target 是 error 的名称

让我们这样做:

df['target'] = df['target'].astype(np.float32)

还有 X 功能

试试这个例子:

from sentence_transformers import SentenceTransformer, util
import numpy as np
import torch


a = np.array([0, 1,2])
b = [[0, 1,2], [4, 5,6], [7,8,9]]


bb = np.zeros((3,3))
for i in range(0, len(b)):
bb[i,:] = np.array(b[i])




a = torch.from_numpy(a)
b = torch.from_numpy(bb)


a= a.float()
b = b.float()


cosine_scores = util.pytorch_cos_sim(b, a)
print(cosine_scores)

火炬新手。出于某种原因,使用所需的数据类型调用 torch.set_default_dtype()是我在 GoogleColab 上的工作方式。network.double()/network.float()tensor.double()/tensor.float()因某些原因无明显作用。