【问题标题】:With BERT Text Classification, ValueError: too many dimensions 'str' error occuring使用 BERT 文本分类,ValueError: too many dimensions 'str' 发生错误
【发布时间】:2021-01-20 07:12:09
【问题描述】:

尝试使用 BERT 模型对文本的情感进行分类,但得到 ValueError : too many dimensions 'str'

这是训练数据值的DataFrame;所以它们是 train_labels

0   notr
1   notr
2   notr
3   negative
4   notr
... ...
854 positive
855 notr
856 notr
857 notr
858 positive

并且有产生错误的代码

train_seq = torch.tensor(tokens_train['input_ids'])
train_mask = torch.tensor(tokens_train['attention_mask'])
train_y = torch.tensor(train_labels.tolist())

At train_y = torch.tensor(train_labels.tolist()); 出现错误: ValueError: too many dimensions 'str'

你能帮我吗enter image description here

enter image description here

【问题讨论】:

    标签: python tensor text-classification bert-language-model mlp


    【解决方案1】:

    我遇到了同样的问题: 这对我有用,我想您需要在阅读 csv 后在代码开头执行此操作: df['labels'] = df['labels'].replace(['negative','notr','positive'],[0,1,2])

    然后从这些标签中拆分以进行训练和测试。

    【讨论】:

    • 也可以写:df['labels'] = df['labels'].replace({'negative':0, 'notr':1, 'positive':2})
    【解决方案2】:

    原因

    问题是您在 torch.tensor() 中传递了一个字符串列表 (str),它只接受数值列表(整数、浮点数等)。

    解决方案

    所以我建议您在将字符串标签传递给 torch.tensor() 之前将其转换为整数值。

    实施

    以下代码可能会对您有所帮助

    # a temporary list to store the string labels
    temp_list = train_labels.tolist()
    
    # dictionary that maps integer to its string value 
    label_dict = {}
    
    # list to store integer labels 
    int_labels = []
    
    for i in range(len(temp_list)):
        label_dict[i] = temp_list[i]
        int_labels.append(i)
    

    现在将此 int_labels 传递给 torch.tensor 并将其用作标签。

    train_y = torch.tensor(int_labels)
    

    当您想查看任何整数的相应字符串标签时,只需使用 label_dict 字典。

    【讨论】:

      【解决方案3】:

      假设您使用的是拥抱脸,

      你需要使用?数据集

      python
      from datasets import ClassLabel
      
      c2l = ClassLabel(num_classes=2, names=['spam', 'ham'])
      
      labels = ["spam", "ham", "ham"]
      
      [c2l.str2int(label) for label in labels ]
      # [0, 1, 1]
      

      更多参考: https://discuss.huggingface.co/t/converting-string-label-to-int/2816

      【讨论】:

        【解决方案4】:

        谢谢,确实转换成整数了,但是分类有问题;

        0
        0   positive
        1   negative
        2   positive
        3   notr
        4   positive
        ... ...
        4002    notr
        4003    positive
        4004    positive
        4005    notr
        4006    negative
        

        Frame 有这些数据,在转换为 int 之后,

        0   0
        1   1
        2   2
        3   3
        4   4
        ... ...
        4002    4002
        4003    4003
        4004    4004
        4005    4005
        4006    4006
        

        就这样了,我需要的是所有的正数、中性和负数,表示为 0 表示 neg-1 表示中性 - 2 表示 pos

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-23
          • 2020-04-01
          • 2021-12-31
          • 2019-02-01
          • 1970-01-01
          • 2021-07-02
          • 1970-01-01
          • 2016-12-09
          相关资源
          最近更新 更多