【问题标题】:IndexError: index 54 is out of bounds for axis 0 with size 48IndexError:索引 54 超出轴 0 的范围,大小为 48
【发布时间】:2021-08-23 23:32:01
【问题描述】:

我正在尝试获取预测的情绪分数并确定文本是正面的还是负面的。但是在预测值时,我得到一个分数数组序列并引发以下错误。

import json
f = open(("/content/trending_tweets.json"), "r+")
data = f.read()
for x in data.split("\n"):
    strlist = "[" + x + "]"
    datalist = json.loads(strlist)
    for y in datalist:
        f = open('/content/user_lookup_data.json', 'a', encoding='utf-8')
        print(y["user"]["screen_name"])
        screen_name = ('@' + y["user"]["screen_name"])
        file_name ='/content/user_timeline/'  + screen_name + '_tweets.csv'
        user_timeline_data = pd.read_csv(file_name, sep='\t', lineterminator='\n',encoding='latin')
        user_timeline_data = (user_timeline_data['tweet'])
        print(len(user_timeline_data))
        df = pd.DataFrame(columns=['Text', 'Sentiment'])
        for index, row in user_timeline_data.iteritems():
          sequence = tokenizer.texts_to_sequences(row)
          test = pad_sequences(sequence, maxlen=max_len)
          pred = model.predict(test)
          if pred[index] > 0.5:
            df.loc[index, ['Text']] = row
            df.loc[index, ['Sentiment']] = 'Positive'
            print(df.shape)
            print(pred)
          else:
            df.loc[index, ['Text']] = row
            df.loc[index, ['Sentiment']] = 'Negative'
            print(df.shape)
            print(pred)
            
          df.to_csv('sentiment_'+ screen_name +'.csv', index=False)

错误信息

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-68-274fe2f3a8c0> in <module>()
     18           test = pad_sequences(sequence, maxlen=max_len)
     19           pred = model.predict(test)
---> 20           if pred[index] > 0.5:
     21             df.loc[index, ['Text']] = row
     22             df.loc[index, ['Sentiment']] = 'Positive'

IndexError: index 54 is out of bounds for axis 0 with size 48

如果有人可以帮助我,那就太好了

【问题讨论】:

    标签: python pandas dataframe keras sentiment-analysis


    【解决方案1】:

    您在第 20 行使用的 index 变量是 user_timeline_data.iteritems 中行的索引,它不是来自预测的索引。预测很可能是一个只有一个值的数组,因为您只预测一个实例。所以在线更改index

    if pred[index] > 0.5:
    

    if pred[0] > 0.5:
    

    【讨论】:

    • Type pred: shape pred : (142, 1) 并且每一行的形状都会发生变化,例如(132,1),(142,1),(112, 1)然后继续。有 10 个文件 user_timeline_data 每个有 200 行
    • 嗯,这对于循环中的某些迭代可能是正确的,但错误表明它实际上具有大小为 48 的形状 0(因此 (48,1))。关键是,您使用的索引 var 与您的 pred 数组的维度无关。
    • 您应该检查是否得到序列中每个单词的预测,而不是整个句子的 1。也许您将错误的形状传递给预测函数。
    • 我将 sequence = tokenizer.texts_to_sequences(row) 更改为 sequence = tokenizer.texts_to_sequences([row]) 并删除了 if pred 条件中的索引并且它有效。
    • 很高兴,如果答案对您有帮助,请将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 2020-04-24
    • 2016-07-29
    • 2021-07-17
    • 2021-05-24
    • 2018-07-23
    • 2019-03-01
    • 2021-12-07
    相关资源
    最近更新 更多