python - 如何修复 RuntimeError“标量类型 Float 的预期对象,但参数的标量类型 Double”?
问题描述
我正在尝试通过 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
解决方案
参考来自这个 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 的建议进行操作。
推荐阅读
- php - 如何在博客编辑页面上显示转义的 html?
- javascript - 鼠标单击时在多个对象上选择 Fabricjs
- youtube - 用于嵌入 2019/2020 的永久流现在链接
- xcode - 尝试在 Xcode 中打开我的反应原生项目以构建 IPA 时文件丢失
- html - 将鼠标悬停在 div 上时,如何触发链接上的多个悬停动作?
- r - “数据和参考应该是同一水平的因素”,在决策树上进行交叉验证
- jquery - 使用 jQuery 将字符串替换为 div 中的 HTML
- c++ - Arduino/C++ 正确使用指针的方法
- c++ - 插入时同时遍历地图,以何种方式不安全
- javascript - 给每个元素一个不同的文本(循环,数组)