【问题标题】:Python Sklearn variables with inconsistent numbers of samples样本数量不一致的 Python Sklearn 变量
【发布时间】:2019-04-06 16:41:15
【问题描述】:

我正在学习情绪分析,我有一个评论数据框,我必须在给定单词列表的情况下对其进行评估,并获得分配给这些单词的权重。不幸的是,当我尝试拟合回归时,出现以下错误: "ValueError: 发现样本数量不一致的输入变量:[11, 133401]"

我错过了什么? CSV file

import pandas
import sklearn
import numpy as np 

products = pandas.read_csv('amazon_baby.csv')
selected_words=["awesome", "great", "fantastic", "amazing", "love", "horrible", "bad", "terrible", "awful", "wow", "hate"]

#ignore all 3* reviews
products = products[products['rating'] != 3]

#positive sentiment = 4* or 5* reviews
products['sentiment'] = products['rating'] >=4


#create a separate column for each word
for word in selected_words:
   products[word]=[len(re.findall(word,x)) for x in products['review'].tolist()]

# Define X and y
X = products[selected_words]
y = products['sentiment']

from sklearn.feature_extraction.text import CountVectorizer

from sklearn.model_selection import train_test_split

X_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 LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train_dtm, y_train) #here is where I get the error

【问题讨论】:

  • 提供完整的错误信息。
  • @AkshayNevrekar 添加了屏幕截图。希望对您有所帮助。

标签: python machine-learning scikit-learn


【解决方案1】:

CountVectorizer() 需要一个可迭代的字符串并返回表示单词计数的向量。您已经使用 for 循环实现了这一点,现在尝试将 CountVectorizer() 拟合到您所选单词的计数中。

假设您只想将所选单词用作特征

logreg.fit(X_train, y_train)

没有转换就可以了。

或者,如果您想使用所有单词作为功能,您可以更改您的 X 以包含完整评论

X = products['review'].astype(str)

然后适合CountVectorizer()然后使用

logreg.fit(X_train_dtm, y_train)

【讨论】:

  • 工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-11-03
  • 2018-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 2022-08-14
  • 2015-08-29
相关资源
最近更新 更多