我正在使用scikit-learn和Pipeline以及FeatureUnion从不同的输入中提取特征。我的数据集中每个样本(实例)都是具有不同长度的文档。我的目标是独立地计算每个文档的前tfidf,但我一直收到此错误消息:
ValueError: blocks[0,:] 行维度不兼容. 得到 blocks[0,1].shape[0] == 1,期望2000。
2000是训练数据的大小。 这是主要代码:
book_summary= Pipeline([
('selector', ItemSelector(key='book')),
('tfidf', TfidfVectorizer(analyzer='word', ngram_range(1,3), min_df=1, lowercase=True, stop_words=my_stopword_list, sublinear_tf=True))
])
book_contents= Pipeline([('selector3', book_content_count())])
ppl = Pipeline([
('feats', FeatureUnion([
('book_summary', book_summary),
('book_contents', book_contents)])),
('clf', SVC(kernel='linear', class_weight='balanced') ) # classifier with cross fold 5
])
我编写了两个类来处理每个pipeline函数。 我的问题在于book_contents pipeline,它主要处理每个样本,并独立地为每本书返回TFidf矩阵。
class book_content_count():
def count_contents2(self, bookid):
book = open('C:/TheCorpus/'+str(int(bookid))+'_book.csv', 'r')
book_data = pd.read_csv(book, header=0, delimiter=',', encoding='latin1',error_bad_lines=False,dtype=str)
corpus=(str([user_data['text']]).strip('[]'))
return corpus
def transform(self, data_dict, y=None):
data_dict['bookid'] #from here take the name
text=data_dict['bookid'].apply(self.count_contents2)
vec_pipe= Pipeline([('vec', TfidfVectorizer(min_df = 1,lowercase = False, ngram_range = (1,1), use_idf = True, stop_words='english'))])
Xtr = vec_pipe.fit_transform(text)
return Xtr
def fit(self, x, y=None):
return self
数据样本(示例):
title Summary bookid
The beauty and the beast is a traditional fairy tale... 10
ocean at the end of the lane is a 2013 novel by British 11
然后每个id将指向一个文本文件,其中包含这些书的实际内容
我尝试过toarray
和reshape
函数,但都没有成功。有任何想法如何解决这个问题。