gpt4 book ai didi

python - 如何修复 RuntimeError "Expected object of scalar type Float but got scalar type Double for argument"?

转载 作者:太空宇宙 更新时间:2023-11-03 12:35:36 27 4
gpt4 key购买 nike

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

最佳答案

引用来自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 Long 标量类型的对象

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

关于python - 如何修复 RuntimeError "Expected object of scalar type Float but got scalar type Double for argument"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741087/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com