scikit-klearn中的特征联合与不相容行维数

2024-09-30 01:19:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经开始使用scikit learn进行文本提取。 当我在一个管道中使用标准函数CountVectorizer和tfiddTransformer时,当我试图结合新的特性(矩阵的一个集合)时,我遇到了一个行维数问题。在

这是我的管道:

pipeline = Pipeline([('feats', FeatureUnion([
('ngram_tfidf', Pipeline([('vect', CountVectorizer()),'tfidf', TfidfTransformer())])),
('addned', AddNed()),])), ('clf', SGDClassifier()),])

这是我的类添加,在每个文档上添加30个新闻特性(示例)。在

^{pr2}$

以及我的主程序的第一部分

data = load_files('HO_without_tag')
grid_search = GridSearchCV(pipeline, parameters, n_jobs = 1, verbose = 20)
print(len(data.data), len(data.target))
grid_search.fit(X, Y).transform(X)

但我得到的结果是:

486 486
Fitting 3 folds for each of 3456 candidates, totalling 10368 fits
[CV]feats__ngram_tfidf__vect__max_features=3000....
323
<class 'list'>
(323,) (486, 30)

当然还有索引器异常

return np.concatenate((X_np, x_new_feat), axis = 1)
IndexError: axis 1 out of bounds [0, 1

当我在transform函数中有参数X(class added),为什么我没有一个numpy数组(4863000)的形状。我只有(323,)个形状。我不明白,因为如果我删除Feature Union和AddNed()管道,CountVectorizer和tf_idf可以正常使用正确的特性和正确的形状。 如果有人有主意? 谢谢。在


Tags: 函数searchdata管道pipeline特性gridtfidf
2条回答

好吧,我会再解释一下。当我说做某事的时候,我说不要对X做任何事。 如果我重写的话

def transform (self, X, **transform_params):
    print(X.shape)   #Print X shape on first line before do anything
    print(type(X))   #For information
    do_nothing_withX #Construct a new matrix with a shape (number of samples, 30 new features) 
    x_new_feat = np.array(list_feat) #Get my new matrix in numpy array 
    print(x_new_feat.shape) 
    return x_new_feat

在上面的这个转换例子中,我不连接X矩阵和新矩阵。我想功能联盟会这么做。。。 我的结果是:

^{pr2}$

进一步说,如果我对gridsearchCV进行交叉验证,只需修改样本大小:

grid_search = GridSearchCV(pipeline, parameters, cv=2, n_jobs = 1, verbose = 20)

我有这样的结果:

486 486
Fitting 2 folds for each of 3456 candidates, totalling 6912 fits
[CV] ......
(242, 3000) #This a new sample size due to cross validation
<class 'scipy.sparse.csr.csr_matrix'>
(486, 30)
..........
ValueError: blocks[0,:] has incompatible row dimensions

当然,如果有必要的话,我可以给你所有的代码。 但我不明白的是,这就是为什么使用管道countvectorizer+tdf_idf的样本大小不等于加载的文件数sklearn.datasets.load_文件()功能。在

你现在可能已经解决了,但其他人可能也有同样的问题:

(323, 3000) # X shape Matrix
<class 'scipy.sparse.csr.csr_matrix'>

AddNed试图将一个矩阵与一个稀疏矩阵相连接,稀疏矩阵应首先转换为密集矩阵。 我在尝试使用CountVectorizer的结果时发现了相同的错误

相关问题 更多 >

    热门问题