我正在使用带有Pipeline和FeatureUnion的scikit-learn从不同的输入中提取特征。我的数据集中的每个样本(实例)都指的是具有不同长度的文档。我的目标是独立计算每个文档的顶部 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
])
我写了两个类来处理每个管道功能。我的问题是book_contents管道,它主要处理每个样本并独立返回每本书的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
功能,但没有运气。知道如何解决这个问题。
感谢
答案 0 :(得分:1)
您可以将Neuraxle's Feature Union与需要自己编写的自定义连接器一起使用。连接器是传递给Neuraxle的FeatureUnion的类,用于按您期望的方式将结果合并在一起。
from neuraxle.base import NonFittableMixin, BaseStep
from neuraxle.pipeline import Pipeline
from neuraxle.steps.sklearn import SKLearnWrapper
from neuraxle.union import FeatureUnion
class BookContentCount(BaseStep):
def transform(self, data_dict, y=None):
transformed = do_things(...) # be sure to use SKLearnWrapper if you wrap sklearn items.
return Xtr
def fit(self, x, y=None):
return self
class CustomJoiner(NonFittableMixin, BaseStep):
def __init__(self):
BaseStep.__init__(self)
NonFittableMixin.__init__(self)
# def fit: is inherited from `NonFittableMixin` and simply returns self.
def transform(self, data_inputs):
# TODO: insert your own concatenation method here.
result = np.concatenate(data_inputs, axis=-1)
return result
book_summary= Pipeline([
ItemSelector(key='book'),
TfidfVectorizer(analyzer='word', ngram_range(1,3), min_df=1, lowercase=True, stop_words=my_stopword_list, sublinear_tf=True)
])
p = Pipeline([
FeatureUnion([
book_summary,
BookContentCount()
],
joiner=CustomJoiner()
),
SVC(kernel='linear', class_weight='balanced')
])
注意:如果您希望您的Neuraxle管道重新成为scikit-learn管道,则可以执行p = p.tosklearn()
。