如何使用scikit-learn将具有不同维度输出的特征进行组合

12

我正在使用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将指向一个文本文件,其中包含这些书的实际内容

我尝试过toarrayreshape函数,但都没有成功。有任何想法如何解决这个问题。


你能否提供一些示例数据? - Vivek Kumar
我已经添加了一个数据示例。 - Abrial
1
这不能在FeatureUnion内完成。它在内部使用numpy.hstack,要求所有部分的行数相等。这里的第一部分“book_summary”将处理整个训练数据并返回一个2000行的矩阵。但是你的第二部分“book_contents”只会返回一行。你如何组合这样的数据? - Vivek Kumar
Book_content_count() 是用于转换和适配书籍内容的类。 - Abrial
2
你好,只是好奇,你是否找到了解决方案?请注意,“每个文档独立的tfidf”等同于countvectorizer。 - mikalai
显示剩余6条评论
1个回答

1
你可以使用Neuraxle的Feature Union和自定义连接器一起使用,需要自己编写连接器。连接器是传递给Neuraxle的FeatureUnion的类,用于按照预期的方式合并结果。

1. 导入Neuraxle的类。

from neuraxle.base import NonFittableMixin, BaseStep
from neuraxle.pipeline import Pipeline
from neuraxle.steps.sklearn import SKLearnWrapper
from neuraxle.union import FeatureUnion

2. 继承 BaseStep 定义您的自定义类:

class BookContentCount(BaseStep): 

    def transform(self, data_dict, y=None):
        transformed = do_things(...)  # be sure to use SKLearnWrapper if you wrap sklearn items.
        return transformed

    def fit(self, x, y=None):
        return self

3. 创建一个合并器,以您希望的方式合并特征联合的结果:

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

4. 最后,通过将连接器传递给FeatureUnion来创建您的管道:

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()
要了解更多关于Neuraxle的内容: https://github.com/Neuraxio/Neuraxle 文档中的更多示例: https://www.neuraxle.org/stable/examples/index.html

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