【问题标题】:AttributeError: 'str' object has no attribute 'dim' in pytorchAttributeError:“str”对象在 pytorch 中没有属性“dim”
【发布时间】:2021-03-12 17:08:50
【问题描述】:

将模型预测发送到模型时,我在 PyTorch 中得到以下错误输出。有谁知道怎么回事?

以下是我创建的架构模型,在错误输出中,它显示 x = self.fc1(cls_hs) 行中存在问题。

class BERT_Arch(nn.Module):

    def __init__(self, bert):
      
      super(BERT_Arch, self).__init__()

      self.bert = bert 
      
      # dropout layer
      self.dropout = nn.Dropout(0.1)
      
      # relu activation function
      self.relu =  nn.ReLU()

      # dense layer 1
      self.fc1 = nn.Linear(768,512)
      
      # dense layer 2 (Output layer)
      self.fc2 = nn.Linear(512,2)

      #softmax activation function
      self.softmax = nn.LogSoftmax(dim=1)

    #define the forward pass
    def forward(self, sent_id, mask):

      #pass the inputs to the model  
      _, cls_hs = self.bert(sent_id, attention_mask=mask)
      print(mask)
      print(type(mask))
      
      x = self.fc1(cls_hs)

      x = self.relu(x)

      x = self.dropout(x)

      # output layer
      x = self.fc2(x)
      
      # apply softmax activation
      x = self.softmax(x)

      return x
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
   1686         if any([type(t) is not Tensor for t in tens_ops]) and has_torch_function(tens_ops):
   1687             return handle_torch_function(linear, tens_ops, input, weight, bias=bias)
-> 1688     if input == 2 and bias is not None:
   1689         print(input)
   1690         # fused op is marginally faster
AttributeError: 'str' object has no attribute 'dim'

【问题讨论】:

    标签: python python-3.x tensorflow machine-learning bert-language-model


    【解决方案1】:

    如果您使用 transformers==3.0.0,一切都应该正常工作!

    transformers==4.0.0 有一些更新

    要获取transformers==3.0.0,可以使用以下命令:

    !pip install transformers==3.0.0
    

    【讨论】:

      【解决方案2】:

      here 所述,较新的版本返回一个特殊的字典而不是一个元组。您可以更改此行:

        _, cls_hs = self.bert(sent_id, attention_mask=mask)
      

        _, cls_hs = self.bert(sent_id, attention_mask=mask, return_dict=False)
      

      或到

      cls_hs = self.bert(sent_id, attention_mask=mask)[1]
      

      【讨论】:

        【解决方案3】:

        找出原因。这是因为变形金刚的版本升级.. 将我的版本更改为旧版本解决问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-05
          • 1970-01-01
          • 2018-09-10
          • 2021-10-04
          • 2019-12-02
          • 2021-09-25
          相关资源
          最近更新 更多