2016-12-27 41 views
0

你好,我有一个list_cluster叫列表,看起来如下:如何将以下功能添加到tfidf矩阵?

list_cluster=["hello,this","this is a test","the car is red",...] 

我使用TfidfVectorizer产生模型如下:

from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer 
with open('vectorizerTFIDF.pickle', 'rb') as infile: 
    tdf = pickle.load(infile) 
tfidf2 = tdf.transform(list_cluster) 

话,我想新的功能添加到这个矩阵称为tfidf2,我有一个列表如下:

dates=['010000000000', '001000000000', '001000000000', '000000000001', '001000000000', '000000000010',...] 

该列表具有list_cluster相同lenght,和表示日期有12个位置S和在哪里是1年相应月份的地方,

例如“0100亿”代表二月,

为了使用它作为功能开始我尝试:

import numpy as np 
dates=np.array(listMonth) 
dates=np.transpose(dates) 

获得numpy的数组,然后进行转置它,以便与所述第一矩阵来连接它tfidf2

print("shape tfidf2: "+str(tfidf2.shape),"shape dates: "+str(dates.shape)) 

以串联我的矢量和矩阵我尝试:

tfidf2=np.hstack((tfidf2,dates[:,None])) 

然而,这是输出:

shape tfidf2: (11159, 1927) shape dates: (11159,) 
Traceback (most recent call last): 
    File "Main.py", line 230, in <module> 
    tfidf2=np.hstack((tfidf2,dates[:,None])) 
    File "/usr/local/lib/python3.5/dist-packages/numpy/core/shape_base.py", line 278, in hstack 
    return _nx.concatenate(arrs, 0) 
ValueError: all the input arrays must have same number of dimensions 

形状似乎不错,但我不知道什么是失败,我想欣赏支持来连接这个功能我tfidf2矩阵,谢谢提前注意,

+0

什么是'dtypes'?如果'日期'是1d,那么'转置'什么都不做。但'[:,无]'应该给它适当的二维形状。 – hpaulj

+0

@hpaulj,感谢您的支持,是的日期是1d,如何将它转换为1,11159矩阵然后与我的矩阵连接? – neo33

+0

'(11159,1)'是'hstack'的正确形状(与axis = 1连接)。这就是为什么我问'dtypes'来看看是否有其他问题(尽管错误说的是什么)。 – hpaulj

回答

1

您需要将所有字符串转换为sklearn的数字。一种方法是在sklearn的预处理模块中使用LabelBinarizer类。这会为原始列中的每个唯一值创建一个新的二进制列。

如果日期与tfidf2相同的行数,那么我认为这将工作。

# create tfidf2 
tfidf2 = tdf.transform(list_cluster) 

#create dates 
dates=['010000000000', '001000000000', '001000000000', '000000000001', '001000000000', '000000000010',...] 

# binarize dates 
lb = LabelBinarizer() 
b_dates = lb.fit_transform(dates) 

new_tfidf = np.concatenate((tfidf2, b_dates), axis=1) 
+0

谢谢我真的很感谢支持, – neo33