我在学习情感分析,并且我有一个评论的数据框架,需要根据给定的一组词语来评估这些评论,并获取这些词语的权重。不幸的是,当我尝试拟合回归时,收到了以下错误:“ValueError: Found input variables with inconsistent numbers of samples: [11, 133401]”
我错过了什么?CSV文件
import pandasimport sklearnimport numpy as np products = pandas.read_csv('amazon_baby.csv')selected_words=["awesome", "great", "fantastic", "amazing", "love", "horrible", "bad", "terrible", "awful", "wow", "hate"]#忽略所有3星评论products = products[products['rating'] != 3]#积极情感为4星或5星评论products['sentiment'] = products['rating'] >=4#为每个词创建一个单独的列for word in selected_words: products[word]=[len(re.findall(word,x)) for x in products['review'].tolist()]# 定义X和yX = products[selected_words]y = products['sentiment']from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)vect = CountVectorizer()vect.fit(X_train)X_train_dtm = vect.transform(X_train)X_test_dtm = vect.transform(X_test)from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression()logreg.fit(X_train_dtm, y_train) #在这里我得到了错误
回答:
CountVectorizer()
期望接收一个字符串的可迭代对象,并返回表示词语计数的向量。你已经通过for循环实现了这一点,现在正试图将CountVectorizer()
拟合到你选择的词语计数上。
假设你只是想将你选择的词语用作特征
logreg.fit(X_train, y_train)
在没有转换的情况下会没问题。
或者,如果你想使用所有词语作为特征,你可以更改X
以包含完整的评论
X = products['review'].astype(str)
然后拟合CountVectorizer()
,之后使用
logreg.fit(X_train_dtm, y_train)