FunctionTransformer 很有用,因为它允许您在管道中应用自定义函数。因为 sklearn.pipeline 中的 Pipeline() 仅适用于实现 .transform() 和 .fit() 方法的对象,所以您使用 FunctionTransformer 更改自定义函数以允许使用 .transform() 和/或 .fit()在上面。
您可以使用 .apply() (或类似列表推导式)转换 DataFrame 或 Series,但如果不先使用 Function Transformer,您将无法在 Pipeline() 中使用该函数。
(答案改编自“专家机器学习:学校预算”课程中的 DataCamp 模块“多种类型的处理:FunctionTransformer”)
例子:
# Import FunctionTransformer
from sklearn.preprocessing import FunctionTransformer
# Obtain the text data: get_text_data
get_text_data = FunctionTransformer(lambda x: x['text'], validate=False)
# Obtain the numeric data: get_numeric_data
get_numeric_data = FunctionTransformer(lambda x: x[['numeric', 'with_missing']], validate=False)
# Fit and transform the text data: just_text_data
just_text_data = get_text_data.fit_transform(sample_df)
# Fit and transform the numeric data: just_numeric_data
just_numeric_data = get_numeric_data.fit_transform(sample_df)
# Print head to check results
print('Text Data')
print(just_text_data.head())
print('\nNumeric Data')
print(just_numeric_data.head())
<script.py> output:
Text Data
0
1 foo
2 foo bar
3
4 foo bar
Name: text, dtype: object
Numeric Data
numeric with_missing
0 -10.856306 4.433240
1 9.973454 4.310229
2 2.829785 2.469828
3 -15.062947 2.852981
4 -5.786003 1.826475