如何修复RuntimeError:预期对象标量类型为Float,但得到标量类型Double的参数?
0 1197
1

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

y_pred = model(X_trainTensor):RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'

这是我的代码的关键部分:

# 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)
)
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
收藏
2021-02-06 15:14 更新 karry •  4554
共 1 个回答
高赞 时间
0

当出现

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)

时, 由于错误消息中显示

xpected object of scalar type Long

因此你也需要

y_trainTensor.long()

Via:https://stackoverflow.com/a/56741419/14964791

收藏
2021-02-06 15:51 更新 anna •  5052