python - 为什么 TfidVectorizer.fit_transform() 会更改我的文本数据的样本和标签数量?
问题描述
我有一个包含 310 个数据的 3 列的数据集。列都是文本。一列是用户在查询表单中输入的文本,第二列是标签(六个标签之一),表示输入属于哪个查询类别。
>>> data.shape
(310 x 3)
KMeans
在我通过算法运行它之前,我正在对我的数据进行以下预处理sklearn.cluster
v = TfidfVectorizer()
vectorized = v.fit_transform(data)
现在,
>>> vectorized.shape
(3,4)
从我正在寻找的地方,我似乎丢失了数据。我不再有我的 310 样品。我相信矢量化的形状是指[n_samples, n_features]
.
为什么样本和特征的值会发生变化?我希望样本数为 310,特征数为 6(我的标记数据的唯一分组数。
解决方案
问题是TfidfVectorizer()
不能一次应用于三列。
根据文档:
fit_transform (self, raw_documents, y=None)
学习词汇和 idf,返回术语-文档矩阵。
这相当于先拟合后变换,但更有效地实现。
参数: raw_documents : iterable
产生 str、unicode 或文件对象的可迭代对象返回: X:稀疏矩阵,[n_samples, n_features]
Tf-idf-weighted document-term 矩阵。
因此,仅适用于单列文本数据时。在您的代码中,它刚刚遍历了列名并为其创建了一个转换。
一个例子来理解,发生了什么:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
data = pd.DataFrame({'col1':['this is first sentence','this one is the second sentence'],
'col2':['this is first sentence','this one is the second sentence'],
'col3':['this is first sentence','this one is the second sentence'] })
vec = TfidfVectorizer()
vec.fit_transform(data).todense()
#
# matrix([[1., 0., 0.],
# [0., 1., 0.],
# [0., 0., 1.]])
vec.get_feature_names()
# ['col1', 'col2', 'col3']
现在,解决方案是您必须将所有三列合并为一列,或者在每列上分别应用矢量化器,然后将它们附加到最后。
方法一
data.loc[:,'full_text'] = data.apply(lambda x: ' '.join(x), axis=1)
vec = TfidfVectorizer()
X = vec.fit_transform(data['full_text']).todense()
print(X.shape)
# (2, 7)
print(vec.get_feature_names())
# ['first', 'is', 'one', 'second', 'sentence', 'the', 'this']
方法二
from scipy.sparse import hstack
import numpy as np
vec={}
X = []
for col in data[['col1','col2','col3']]:
vec[col]= TfidfVectorizer()
X = np.append(X,
vec[col].fit_transform(data[col]))
stacked_X = hstack(X).todense()
stacked_X.shape
# (2, 21)
for col, v in vec.items():
print(col)
print(v.get_feature_names())
# col1
# ['first', 'is', 'one', 'second', 'sentence', 'the', 'this']
# col2
# ['first', 'is', 'one', 'second', 'sentence', 'the', 'this']
# col3
# ['first', 'is', 'one', 'second', 'sentence', 'the', 'this']
推荐阅读
- c++ - Windows 中的 Qt 库链接错误
- android - 在相同的默认登录页面上制作带有电话号码和密码的登录页面
- r - 无法在本地服务器上安装 rgdal 包,发生不可恢复的异常。R 正在中止... [错误:加载失败]
- udp - 使用 Fluentd 转发数据包
- excel - 具有不同偏移量的索引/匹配
- php - 如何在 laravel withe ajax 中返回一些喜欢
- javascript - Firebase 响应具有 HTML 标签
- c# - 如何在 Visual Studio 解决方案的部署中使用 nuget 包
- sql - SQL 查看多个条件,如果任何一个无效,则提供单个“NotOk”值
- owl-carousel - 猫头鹰旋转木马 - 自动滚动并将其设置为 2 张卡片