微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

参考来自这个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的建议进行操作。

解决方法

我正在尝试通过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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。