python - TfidfVectorizer 将我的数据帧从 799 缩小到 3
问题描述
我有包含文本列的数据框
和多标签值
RepID, RepText, Code 1 这是一个测试。感谢您购买...水果,肉类 2 购买牛奶和香蕉,我也购买...乳制品,水果,其他
这是我的代码
######## df has 1000 records
multilabel_binarizer = MultiLabelBinarizer()
multilabel_binarizer.fit(df['Code'])
y = multilabel_binarizer.transform(df['Code'])
X = df[df.columns.difference(["Code"])]
######## df split into X (RepID, RepText)
######## and y (Code)
xtrain, xval, ytrain, yval = train_test_split(X, y, test_size=0.2, random_state=9)
##### xtrain.shape = (800,3)
##### xval.shape = (200,3)
##### ytrain.shape = (800,1725)
##### yval.shape = (200,1725)
tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=10000)
xtrain_tfidf = tfidf_vectorizer.fit_transform(xtrain)
xval_tfidf = tfidf_vectorizer.transform(xval)
##### But after the code above
##### xtrain_tfidf.shape = (3,3)
##### xval_tfidf.shape = (3,3)
##### ytrain.shape = (800,1725)
##### yval.shape = (200,1725)
##### when means when I do the next line
xval_tfidf.shape
#mdl = LinearRegression()
mdl = LogisticRegression()
#mdl = SVC(gamma='auto', probability=True)
clf = OneVsRestClassifier(mdl)
clf.fit(xtrain_tfidf, ytrain)
我收到这个错误
ValueError: Found input variables with inconsistent numbers of samples: [3, 799]
为什么?为什么在TfidfVectorizer行之后我只得到3 条记录而不是800条记录?
当我试图查看xtrain_tfidf中的内容时,我得到了这个
xtrain_tfidf
Out[56]:
<3x3 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Row format>
解决方案
我找到了原因
我忘记在拆分记录时只选择文本列
xtrain, xval, ytrain, yval = train_test_split(X["RepText"], y, test_size=0.2, random_state=9)
推荐阅读
- sql - 为 sql 库操作制作通用选择函数
- python - 进行输入并运行循环以创建自定义数量的对象
- jquery - 将表单提交的值附加为 url 参数
- java - 如何修复 fastlane 错误:找不到用于签名配置“externalOverride”的密钥库文件“keystore.jks”。?
- redux - 组件会在 react-redux 中使用 useStore 重新渲染吗?
- javascript - 为什么 Bootstrap Spinner 在计算密集型上下文中无法使用
- swift - 等到方法完成
- windows - 使用 FORFILES 指定输出目录
- java - 为什么我收不到arraylist的内容
- css - 当我使用 zoomIn 动画时,元素正在消失