【问题标题】:如何修复 RuntimeError“标量类型 Float 的预期对象,但参数的标量类型 Double”?
【发布时间】:2019-11-06 12:39:12
【问题描述】:

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

RuntimeError: 标量类型 Float 的预期对象,但参数 #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

【问题讨论】:

  • 它是否告诉您触发运行时错误的代码行?
  • 是的,在我的最后一个代码块中。 y_pred = model(X_trainTensor) 触发它。
  • 我不使用 PyTorch,但你可以使用 model(float(X_trainTensor))
  • 然后我在同一行收到以下错误:ValueError: only one element tensors can be converted to Python scalars
  • 另外,如果我将张量转换为所有浮点数。我收到一个新错误:AttributeError: 'builtin_function_or_method' object has no attribute 'dim'

标签: python neural-network deep-learning classification pytorch


【解决方案1】:

参考来自this github issue

当错误为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

您也可以按照@Paddy 的建议执行model.double() .

【讨论】:

    【解决方案2】:

    我有同样的问题

    已解决

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

    X_train = X_train.astype(np.float32)
    

    【讨论】:

      【解决方案3】:

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

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

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

      为了调试,打印 obj.dtype 并检查一致性。

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          让我们这样做:

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

          也适用于 x 个功能

          【讨论】:

            【解决方案6】:

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

            【讨论】:

              【解决方案7】:

              试试这个例子:

              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)
              

              【讨论】:

                猜你喜欢
                • 2020-06-15
                • 2020-05-31
                • 2021-07-10
                • 1970-01-01
                • 2020-12-02
                • 2020-01-29
                • 2021-09-15
                • 2020-10-21
                • 2020-06-11
                相关资源
                最近更新 更多