我尝试在学生的管道上做一个教程,但我阻止了。我不是专家,但我正在尝试改进。因此,感谢您的放纵。实际上,我尝试使用管道来执行几个步骤,以准备分类器的数据帧:
- 步骤1:数据框的描述
- 步骤2:填写NAN值
- 步骤3:将分类值转换为数字
这是我的代码:
class Descr_df(object):
def transform (self, X):
print ("Structure of the data: n {}".format(X.head(5)))
print ("Features names: n {}".format(X.columns))
print ("Target: n {}".format(X.columns[0]))
print ("Shape of the data: n {}".format(X.shape))
def fit(self, X, y=None):
return self
class Fillna(object):
def transform(self, X):
non_numerics_columns = X.columns.difference(X._get_numeric_data().columns)
for column in X.columns:
if column in non_numerics_columns:
X[column] = X[column].fillna(df[column].value_counts().idxmax())
else:
X[column] = X[column].fillna(X[column].mean())
return X
def fit(self, X,y=None):
return self
class Categorical_to_numerical(object):
def transform(self, X):
non_numerics_columns = X.columns.difference(X._get_numeric_data().columns)
le = LabelEncoder()
for column in non_numerics_columns:
X[column] = X[column].fillna(X[column].value_counts().idxmax())
le.fit(X[column])
X[column] = le.transform(X[column]).astype(int)
return X
def fit(self, X, y=None):
return self
如果我执行步骤1和2或步骤1和3,则可以执行,但是如果我同时执行步骤1、2和3。我有一个错误:
pipeline = Pipeline([('df_intropesction', Descr_df()), ('fillna',Fillna()), ('Categorical_to_numerical', Categorical_to_numerical())])
pipeline.fit(X, y)
AttributeError: 'NoneType' object has no attribute 'columns'
出现此错误,因为在管道中,第一个估计器的输出进入第二个,然后第二个估计器的输出进入第三,等等...
来自管道的文档:
适合所有一个接一个地转换并转换数据, 然后使用最终估算器拟合转换的数据。
因此,对于您的管道,执行步骤如下:
- descr_df.fit(x( ->不做任何事情并返回自我
- newx = descr_df.transform(x( ->应返回某些值以分配给NEWX,该值应传递给下一个估算器,但是您的定义不会返回任何内容(仅prints(。所以没有一个隐式返回
- fillna.fit(newx( ->不做任何事情,返回自我
- fillna.transform(newx( ->调用newx.columns。但是newx = none step2。因此错误。
解决方案:更改descr_df的转换方法以返回数据框架,因为它是:
def transform (self, X):
print ("Structure of the data: n {}".format(X.head(5)))
print ("Features names: n {}".format(X.columns))
print ("Target: n {}".format(X.columns[0]))
print ("Shape of the data: n {}".format(X.shape))
return X
建议:使您的类从Scikit中的基本估计器和变压器类继承以确认良好实践。
即,将class Descr_df(object)
更改为class Descr_df(BaseEstimator, TransformerMixin)
,Fillna(object)
更改为Fillna(BaseEstimator, TransformerMixin)
等。
有关管道自定义类的更多详细信息,请参见此示例:
- http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html#sphx-glr-auto-examples-hetero-feature-feature-union-py