簡體   English   中英

如何修復 RuntimeError“預期為標量類型 Float 的 object,但參數為標量類型 Double”?

[英]How to fix RuntimeError "Expected object of scalar type Float but got scalar type Double for argument"?

我正在嘗試通過 PyTorch 訓練分類器。但是,當我向 model 提供訓練數據時,我遇到了訓練問題。 我在y_pred = model(X_trainTensor)上收到此錯誤:

RuntimeError:應為標量類型 Float 的 object,但參數 #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()建議執行model.double()

我有同樣的問題

解決

在轉換為張量之前,試試這個

X_train = X_train.astype(np.float32)

該問題可以通過將輸入的數據類型設置為 Double 來解決,即torch.float32

我希望問題是因為您的數據類型是torch.float64

您可以在設置數據時避免這種情況,如其他答案之一所述,或者使模型類型也與您的數據相同。 即使用 float64 或 float32。

對於調試,打印 obj.dtype 並檢查一致性。

我不知道為什么MilkyWay90沒有編寫github問題的主要內容,不久您必須對模型進行double。):

model.double()

如果選擇了錯誤的損失函數,也會出現此問題。 例如,如果您有回歸問題,但您正在嘗試使用交叉熵損失。 然后它將通過更改 MSE 上的損失函數來修復

嘗試使用: target = target.float() # target 是錯誤的名稱

讓我們這樣做:

df['target'] = df['target'].astype(np.float32)

對於 x 特征也是如此

試試這個例子:

from sentence_transformers import SentenceTransformer, util
import numpy as np
import torch

a = np.array([0, 1,2])
b = [[0, 1,2], [4, 5,6], [7,8,9]]

bb = np.zeros((3,3))
for i in range(0, len(b)):
    bb[i,:] = np.array(b[i])


a = torch.from_numpy(a)
b = torch.from_numpy(bb)

a= a.float()
b = b.float()

cosine_scores = util.pytorch_cos_sim(b, a)
print(cosine_scores)

PyTorch 的新手。出於某種原因,使用所需的數據類型調用torch.set_default_dtype()對我來說在 Google Colab 上很有效。 network.double() / network.float()tensor.double() / tensor.float()由於某種原因沒有任何效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM