如何修复RuntimeError“标量类型为Float的预期对象,但参数为标量类型为Double"? [英] How to fix RuntimeError "Expected object of scalar type Float but got scalar type Double for argument"?

查看:98
本文介绍了如何修复RuntimeError“标量类型为Float的预期对象,但参数为标量类型为Double"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to train a classifier via PyTorch. However, I am experiencing problems with training when I feed the model with training data. I get this error on y_pred = model(X_trainTensor):

RuntimeError:标量类型为Float的预期对象,但参数#4'mat1'的标量类型为Double

RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'

这是我代码的关键部分:

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

推荐答案

参考来自此github问题.

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

When the error is RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1', you would need to use the .float() function since it says Expected object of scalar type Float.

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

Therefore, the solution is changing y_pred = model(X_trainTensor) to y_pred = model(X_trainTensor.float()).

同样,当您遇到loss = loss_fn(y_pred, y_trainTensor)的另一个错误时,由于错误消息显示Expected object of scalar type Long,因此您需要y_trainTensor.long().

Likewise, when you get another error for loss = loss_fn(y_pred, y_trainTensor), you need y_trainTensor.long() since the error message says Expected object of scalar type Long.

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

You could also do model.double(), as suggested by @Paddy .

这篇关于如何修复RuntimeError“标量类型为Float的预期对象,但参数为标量类型为Double"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆