繁体   English   中英

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

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

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

RuntimeError:应为标量类型 Float 的 object,但参数 #4 'mat1' 的标量类型为 Double

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

# 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

参考来自这个 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()建议执行model.double()

我有同样的问题

解决

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

X_train = X_train.astype(np.float32)

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

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

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

对于调试,打印 obj.dtype 并检查一致性。

我不知道为什么MilkyWay90没有编写github问题的主要内容,不久您必须对模型进行double。):

model.double()

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

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

让我们这样做:

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)

PyTorch 的新手。出于某种原因,使用所需的数据类型调用torch.set_default_dtype()对我来说在 Google Colab 上很有效。 network.double() / network.float()tensor.double() / tensor.float()由于某种原因没有任何效果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM