【问题标题】:Is there a way to add a 'sentiment' column after applying CountVectorizer or TfIdfTransformer to a dataframe?将 CountVectorizer 或 TfIdfTransformer 应用于数据帧后,有没有办法添加“情绪”列?
【发布时间】:2020-07-12 16:04:44
【问题描述】:

我正在处理应用商店评论,根据评论中的文字和评论所传达的情绪将它们分类为“0”类或“1”类。

在我的分类步骤中,我将以下方法应用于我的数据框:

def get_sentiment(s):
    vs = analyzer.polarity_scores(s)
    if vs['compound'] >= 0.5:
        return 1
    elif vs['compound'] <= -0.5:
        return -1
    else:
        return 0 
df['sentiment'] = df['review'].apply(get_sentiment)

为简单起见,数据已被标记为“0”或“1”类,但我正在训练模型以分类尚未标记的新实例。简而言之,我正在使用的数据已经被标记。它们位于classification 列中。

然后在我的火车测试拆分方法中执行以下操作:

msg_train, msg_test, label_train, label_test = train_test_split(df.drop('classification', axis=1), df['classification'], test_size=0.3, random_state=42)

所以 X 参数的数据框有 reviewsentiment,而对于 y 参数我只有 classification 我正在训练我的模型。

由于规范化是重复的,为了简单起见,我正在运行这样的管道:

pipeline1 = Pipeline([
    ('bow', CountVectorizer(analyzer=clean_review)),
    ('tfidf', TfidfTransformer()),
    ('classifier', MultinomialNB())
])

其中clean_review函数如下:

def clean_review(sentence):
    no_punc = [c for c in sentence if c not in string.punctuation]
    no_punc = ''.join(no_punc)
    no_stopwords = [w.lower() for w in no_punc.split() if w not in stopwords_set]    
    stemmed_words = [ps.stem(w) for w in no_stopwords]
    return stemmed_words

其中 stopwords_set 是来自 nltk 库的英语停用词集合,ps 来自 nltk 库中的 PortStemmer 模块(用于词干提取)。

我收到以下错误:ValueError: Found input variables with inconsistent numbers of samples: [2, 505]

当我之前搜索此错误时,我发现可能的问题是每个属性的记录数不匹配。我发现情况并非如此。我使用的所有记录的每一列都有值。

其他人可以帮我解释这个错误的含义吗?

我的最终目标是拥有一个将 CountVectorizer 和 TfIdfTransformer 应用于文本的数据框,同时保留每个评论的情绪列。

然后我希望能够在此数据帧上训练 MultinomialNB 分类器并将此模型应用于其他任务。

【问题讨论】:

    标签: python-3.x pandas dataframe scikit-learn


    【解决方案1】:

    我不确定错误是由于什么原因造成的,因为我不知道您的数据框的大小应该是多少。我需要更多信息。错误在哪一行抛出?

    关于您要保留情感列的事实,您可以仅在文本数据上应用 CountVectorizer 和 TfIdfTransformer(顺便说一下,您可以跳过一个步骤并直接应用 TfidfVectorizer),然后在管道中添加另一个转换器将数据框提供给分类器之前的原始情感列。

    【讨论】:

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