2016-12-27 39 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