gpt4 book ai didi

python - CountVectorizer 变换后出现意外的稀疏矩阵

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:17 26 4
gpt4 key购买 nike

我是 NLTK 的新人,在创建评论分类器时遇到问题。 enter image description here

当作为输入传递的数据的形状为 (10000,1) 时,我无法理解转换后的数据的形状如何是 1*1 稀疏矩阵我对原始评论数据进行了一些处理。比如删除停用词、词干和删除标点符号。

我需要有关哪里出错的帮助,如果需要更多详细信息来查找问题,请告诉我。

最佳答案

根据屏幕截图的格式,看起来 X_train1 实际上是一个 Pandas 数据框。问题在于 Description 是一列单词列表(可能长度不等)。像这样的事情:

X = np.array([['alpha','beta'],['theta','theta','gamma'],['delta','delta']])
X_train1 = pd.DataFrame(X, columns=["Description"])

X_train1
Description
0 [alpha, beta]
1 [theta, theta, gamma]
2 [delta, delta]

X_train1.shape # (3,1)

因此,您有 10,000 行单词列表(形状为 (nrow, 1))。
但是 CountVectorizer(假设您使用的是 sklearn 类)需要一个文档数组。来自 documentation :

CountVectorizer: Convert a collection of text documents to a matrix of token counts

更具体地说,考虑 fit() 的参数定义:

raw_documents: An iterable which yields either str, unicode or file objects.

如果您只是尝试传入 X_train1,则您没有提供预期的输入 - 您传入的数据帧包含包含字符串列表对象的列。您应该期望这样做会得到奇怪的输出。

假设X_train1中的每一行代表一个文档,尝试连接每行上的单词列表,然后传递给CountVectorizer:

X = X_train1.Description.apply(lambda row: ' '.join(row))
ctvec = CountVectorizer()
ctvec.fit_transform(X) # combine fit(X) and transform(X)

输出:

<3x5 sparse matrix of type '<class 'numpy.int64'>'
with 5 stored elements in Compressed Sparse Row format>

此输出更符合预期输入。

关于python - CountVectorizer 变换后出现意外的稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47736659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com