【问题标题】:FeatureUnion : Sklearn FeatureUnion does not allows fit paramsFeatureUnion :Sklearn FeatureUnion 不允许拟合参数
【发布时间】:2019-09-27 02:17:05
【问题描述】:

FeatureUnion 无法适应。以下代码 fit() 的最后一行抛出错误为:

from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest

iris = load_iris()    
X, y = iris.data, iris.target
pca = PCA(n_components=2)
selection = SelectKBest(k=1)
combined_features = FeatureUnion([("pca", pca), ("univ_select", selection)])
svm = SVC(kernel="linear")

pipeline = Pipeline([("features", combined_features), ("svm", svm)])
pipeline.fit (X, y, features__univ_select__k=2)

抛出错误:

TypeError: fit_transform() got an unexpected keyword argument 'univ_select__k'

【问题讨论】:

  • 虽然这段代码实际上并没有什么用,但它公开了一个在涉及 FeatureUnion 时传递 pipeline__ 参数的真实用例。实际上,我在相关代码中遇到了这个错误,而这并不完全是这个错误。因此,当涉及到 FeatureUnion 时,我需要符合 fit() 的行为。
  • 不要使用 cmets 空间添加此类信息 - 改为编辑和更新您的帖子

标签: python python-3.x scikit-learn


【解决方案1】:

参数features__univ_select__k=2fit中使用;另一方面,这里根本没有必要。

如果您遵循 scikit-learn 文档中的功能联合 example(您似乎是这样),您应该注意到它在 param_grid 中用作参数,而不是在 fit 中。

但是这里你不执行任何参数网格搜索;因为你已经定义了

pca = PCA(n_components=2)
selection = SelectKBest(k=1)
combined_features = FeatureUnion([("pca", pca), ("univ_select", selection)])

对于要使用的功能数量没有任何其他“选择”,因此您不应使用任何features__univ_select__k=2 参数。简单地给予

pipeline.fit (X, y)

完成任务:

Pipeline(memory=None,
     steps=[('features', FeatureUnion(n_jobs=None,
       transformer_list=[('pca', PCA(copy=True, iterated_power='auto', n_components=2, random_state=None,
  svd_solver='auto', tol=0.0, whiten=False)), ('univ_select', SelectKBest(k=1, score_func=<function f_classif at 0x000000000808AD08>))],
       tran...r', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False))])

【讨论】:

  • 我明白,你是对的。但这仍然不能回答我的问题。实际上,我在相关代码中遇到了这个错误,而这并不完全是这个错误。因此,当涉及到 FeatureUnion 时,我需要确认 fit() 的行为。
  • @sapthrishi007 但这里确实涉及到 FeatureUnion 。而且,无论如何,features__univ_select__k 不应该在fit 中使用,因此您的问题的实际答案是您使用了错误的语法(更新答案以突出显示这一点)。
猜你喜欢
  • 2017-12-20
  • 2017-11-25
  • 2019-08-31
  • 2017-05-07
  • 2021-08-19
  • 2020-08-19
  • 1970-01-01
  • 2016-08-07
  • 2019-01-12
相关资源
最近更新 更多