Python Sklearn变量样本数量不一致

我在学习情感分析,并且我有一个评论的数据框架,需要根据给定的一组词语来评估这些评论,并获取这些词语的权重。不幸的是,当我尝试拟合回归时,收到了以下错误:“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) #在这里我得到了错误

enter image description here


回答:

CountVectorizer() 期望接收一个字符串的可迭代对象,并返回表示词语计数的向量。你已经通过for循环实现了这一点,现在正试图将CountVectorizer()拟合到你选择的词语计数上。

假设你只是想将你选择的词语用作特征

logreg.fit(X_train, y_train)

在没有转换的情况下会没问题。

或者,如果你想使用所有词语作为特征,你可以更改X以包含完整的评论

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

然后拟合CountVectorizer(),之后使用

logreg.fit(X_train_dtm, y_train)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注