AttributeError: ‘numpy.ndarray‘ object has no attribute ‘fit‘

AttributeError: ‘numpy.ndarray’ object has no attribute ‘fit’

源代码运行如下:

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

num_pipeline = Pipeline([
    ('imputer',SimpleImputer(strategy="median")),
    ('attribs_adder',CombinedAttributesAdder()),
    ('std_scaler',StandardScaler)
])

housing_num_tr = num_pipeline.fit_transform(housing_num)

以上代码实现的目的和过程为:
1.许多数据转换的步骤需要以正确的顺序来执行,pipeline支持这样的操作;
2.pipeline构造函数会通过一系列名称/估算器的配对来定义步骤的序列,必须是转换器,必须有fit_transform()方法;
3.调用流水线fit方法时,会在所有转换器上按照顺序依次调用fit_transform(),将一个调用输出作为参数传递给下一个调用方法,直到传递到最终;
4.估算器只会调用fit()方法。

运行结果:

AttributeError                            Traceback (most recent call last)
<ipython-input-277-2330a4b94434> in <module>
     13 ])
     14 
---> 15 housing_num_tr = num_pipeline.fit_transform(housing_num)

d:\python3.8.5\lib\site-packages\sklearn\pipeline.py in fit_transform(self, X, y, **fit_params)
    374             fit_params_last_step = fit_params_steps[self.steps[-1][0]]
    375             if hasattr(last_step, 'fit_transform'):
--> 376                 return last_step.fit_transform(Xt, y, **fit_params_last_step)
    377             else:
    378                 return last_step.fit(Xt, y,

d:\python3.8.5\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
    688         if y is None:
    689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
    691         else:
    692             # fit method of arity 2 (supervised transformation)

AttributeError: 'numpy.ndarray' object has no attribute 'fit'

明显的错误提示:AttributeError: ‘numpy.ndarray’ object has no attribute ‘fit’
仔细检查后发现原来是,StandarScaler,没有调用,加上小括号后StandarScaler() 才会被调用,

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

num_pipeline = Pipeline([
    ('imputer',SimpleImputer(strategy="median")),
    ('attribs_adder',CombinedAttributesAdder()),
    ('std_scaler',StandardScaler())
])

housing_num_tr = num_pipeline.fit_transform(housing_num)

重新运行,OK。

心得体会:学习,练习代码的过程,是一个不断磨练心性的过程,足够的耐心去敲,足够细心去发现些微的差异。

你可能感兴趣的:(机器学习,python)