在Tfidf矩阵中添加列

3
我希望构建一个文本分类模型,使用单词以及一些额外的特征(例如,是否具有链接)。
tweets = ['this tweet has a link htt://link','this one does not','this one does http://link.net']

我使用sklearn得到了文本数据的稀疏矩阵。

tfidf_vectorizer = TfidfVectorizer(max_df=0.90, max_features=200000, min_df=0.1, stop_words='english', use_idf=True, tokenizer=nltk.tokenize, ngram_range=(1,2))

tfidf_matrix = tfidf_vectorizer.fit_transform(tweets)

我希望为其添加列以支持文本数据的其他特征。我尝试了以下方法:

import scipy as sc

all_data = sc.hstack((tfidf_matrix, [1,0,1]))

这将给我一个看起来像这样的数据:

array([ <3x8 sparse matrix of type '<type 'numpy.float64'>' with 10 stored elements in Compressed Sparse Row format>, 1, 1, 0], dtype=object)

当我将这个数据框馈送到模型中时:
`from sklearn.naive_bayes import MultinomialNB
 clf = MultinomialNB().fit(all_data, y)` 

我遇到了一个回溯错误:
`Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "C:\Anaconda\lib\site- packages\spyderlib\widgets\externalshell\sitecustomize.py", line 580, in   runfile
 execfile(filename, namespace)
 File "C:/Users/c/Desktop/features.py", line 157, in <module>
 clf = MultinomialNB().fit(all_data, y)
File "C:\Anaconda\lib\site-packages\sklearn\naive_bayes.py", line 302, in  fit
_, n_features = X.shape

数值错误:需要至少1个值来解包

编辑:数据的形状

`tfidf_matrix.shape
 (100, 2)
 all_data.shape
 (100L,)`

我可以直接将列添加到稀疏矩阵中吗?如果不行,我该如何将数据转换为支持此操作的格式?我担心使用稀疏矩阵以外的其他格式会增加内存占用。


请发布完整的回溯信息。 - Alex Plugaru
它能简单地使用 MultinomialNB().fit(tfidf_matrix, y) 吗? - Alex Plugaru
@AlexPlugaru 你好,Alex。它有效了,我只是使用了tfidf_matrix。而没有尝试附加其他列。 - mech
tfidf_matrixall_datashape可能不匹配?也许你应该这样做:根据这里的解释,all_data = sc.hstack((tfidf_matrix, [[1],[0],[1]])):http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.hstack.html - Alex Plugaru
似乎特征的形状丢失了。也许你应该进行重塑:all_data.reshape(tfidf_matrix.shape) - Alex Plugaru
3个回答

13

我可以将列 直接 追加到一个 稀疏矩阵 中吗? - 可以。而且你可能应该这样做,因为在大型语料库中,解包(使用 todensetoarray)很容易导致内存爆炸。

使用 scipy.sparse.hstack

import numpy as np
import scipy as sp
from sklearn.feature_extraction.text import TfidfVectorizer

tweets = ['this tweet has a link htt://link','this one does not','this one does http://link.net']
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(tweets)
print tfidf_matrix.shape

(3, 10)

new_column = np.array([[1],[0],[1]])
print new_column.shape

(3, 1)

final = sp.sparse.hstack((tfidf_matrix, new_column))
print final.shape

(3, 11)


1
将稀疏矩阵转换为密集矩阵。
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
tweets = ['this tweet has a link htt://link','this one does not','this one does http://link.net']

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(tweets)
dense = tfidf_matrix.todense()
print dense.shape

newCol = [[1],[0],[1]]

allData = np.append(dense, newCol, 1)

print allData.shape

(3L, 10L)

(3L, 11L)


0

这是正确的表单:

all_data = sc.hstack([tfidf_matrix, sc.csr_matrix([1,0,1]).T], 'csr')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接