簡體   English   中英

RuntimeError: Found dtype Double 但預期 Float - PyTorch

[英]RuntimeError: Found dtype Double but expected Float - PyTorch

我是 pytorch 的新手,我正在使用強化學習為時間序列研究 DQN,我需要對時間序列和一些傳感器讀數進行復雜的觀察,所以我合並了兩個神經網絡,我不確定這是否會破壞我的損失.backward 或其他東西。 我知道有多個標題相同的問題,但沒有一個對我有用,也許我錯過了一些東西。
首先,這是我的網絡:

class DQN(nn.Module):
  def __init__(self, list_shape, score_shape, n_actions):
    super(DQN, self).__init__()

    self.FeatureList =  nn.Sequential(
            nn.Conv1d(list_shape[1], 32, kernel_size=8, stride=4),
            nn.ReLU(),
            nn.Conv1d(32, 64, kernel_size=4, stride=2),
            nn.ReLU(),
            nn.Conv1d(64, 64, kernel_size=3, stride=1),
            nn.ReLU(),
            nn.Flatten()
        )
    
    self.FeatureScore = nn.Sequential(
            nn.Linear(score_shape[1], 512),
            nn.ReLU(),
            nn.Linear(512, 128)
        )
    
    t_list_test = torch.zeros(list_shape)
    t_score_test = torch.zeros(score_shape)
    merge_shape = self.FeatureList(t_list_test).shape[1] + self.FeatureScore(t_score_test).shape[1]
    
    self.FinalNN =  nn.Sequential(
            nn.Linear(merge_shape, 512),
            nn.ReLU(),
            nn.Linear(512, 128),
            nn.ReLU(),
            nn.Linear(128, n_actions),
    )
    
  def forward(self, list, score):
    listOut = self.FeatureList(list)
    scoreOut = self.FeatureScore(score)
    MergedTensor = torch.cat((listOut,scoreOut),1)
    return self.FinalNN(MergedTensor)

我有一個名為 calc_loss 的 function,最后它返回 MSE 損失,如下所示

  print(state_action_values.dtype)
  print(expected_state_action_values.dtype) 
  return nn.MSELoss()(state_action_values, expected_state_action_values)

打印分別顯示 float32 和 float64。
當我運行 loss.backward() 時出現錯誤,如下所示

LEARNING_RATE = 0.01
optimizer = optim.Adam(net.parameters(), lr=LEARNING_RATE)

for i in range(50):
  optimizer.zero_grad()
  loss_v = calc_loss(sample(obs, 500, 200, 64), net, tgt_net)
  print(loss_v.dtype)
  print(loss_v)
  loss_v.backward()
  optimizer.step()

打印 output 如下:
火炬.float64
張量(1887.4831,dtype=torch.float64,grad_fn=)

更新1:
我嘗試使用更簡單的 model,但同樣的問題,當我嘗試將輸入轉換為 Float 時,出現錯誤:

RuntimeError: expected scalar type Double but found Float

是什么讓 model 期望翻倍?

更新 2:
我嘗試在 Torch 導入后在頂部添加以下行,但同樣的問題RuntimeError: Found dtype Double but expected Float

>>> torch.set_default_tensor_type(torch.FloatTensor)

但是當我使用 DoubleTensor 時,我得到: RuntimeError: Input type (torch.FloatTensor) and weight type (torch.DoubleTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor

問題不在於網絡的輸入,而是 MSELoss 的標准,因此在將標准轉換為浮動后它工作正常,如下所示

return nn.MSELoss()(state_action_values.float(), expected_state_action_values.float())

我決定把答案留給像我這樣可能會被卡住並且沒想到會檢查損失標准的數據類型的初學者

暫無
暫無

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

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