【问题标题】:Inverse scaler transform within sklearn pipelinesklearn管道中的逆缩放器变换
【发布时间】:2021-12-13 01:10:18
【问题描述】:

我正在尝试应用标准化,然后使用 KNN 进行插补。然后我想反向转换这些值,因为我将应用一些需要原始数据的其他转换。是否可以在 scikit-learn 管道中执行此操作?无论我尝试什么,都会出错。

注意:逆变换应该在管道内完成,而不是在管道完成后。


import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, OneHotEncoder, FunctionTransformer
from sklearn.impute import KNNImputer
from sklearn.pipeline import Pipeline 
from sklearn.compose import ColumnTransformer

ss = StandardScaler()
imputer = KNNImputer(n_neighbors=3, add_indicator=False)
ohe = OneHotEncoder()

df_example = pd.DataFrame(data={"num1":[1, 2, 3, np.nan, 6, 6, 9, 4, 5], 
                                "num2":[4, np.nan, 6, 5, 3, 8, 2, 8, 3], 
                                "cat1":['A', 'B', 'C', 'A', 'B', 'C', 'A', 'A', 'B']})

list_numeric_vars = ["num1", "num2"]
list_cat_vars = ["cat1"]

pipeline_num = Pipeline([    

    ("standardizer", ss),
    ("imputer", imputer),
    ("standardizer_inverse", FunctionTransformer(ss.inverse_transform))
])

pipeline_cat = Pipeline([    
    ("ohe", ohe),
])


ct = ColumnTransformer(
    transformers = 
        [
            ("pipeline_num", pipeline_num, list_numeric_vars),
            ("pipeline_cat", pipeline_cat, list_cat_vars)
            
        ], 
    remainder ="drop"
    )

ct.fit(df_example) # Error


【问题讨论】:

  • 您的问题解决了吗?

标签: python scikit-learn pipeline


【解决方案1】:

由于标准缩放器和 KNN imputer(来自 n 个最近邻的平均值)是线性运算,因此运行 standardizer >> imputer >> inverse_standardizer 会产生与单独运行 imputer 相同的结果。

您可以按如下方式简化数字管道:

pipeline_num = Pipeline([
    ("imputer", imputer),
    # Add other processing steps here
])

这里是“证明”,单独的 imputer 操作会产生相同的结果:

df1 = ss.fit_transform(df_example[list_numeric_vars])
df1 = imputer.fit_transform(df1)
df1 = ss.inverse_transform(df1)
print(f'Scale/Impute/Inverse-Scale:\n{df1}\n')

df2 = imputer.fit_transform(df_example[list_numeric_vars])
print(f'Impute Only:\n{df2}\n')

这是输出:

Scale/Impute/Inverse-Scale:
[[1.         4.        ]
 [2.         6.        ]
 [3.         6.        ]
 [3.33333333 5.        ]
 [6.         3.        ]
 [6.         8.        ]
 [9.         2.        ]
 [4.         8.        ]
 [5.         3.        ]]

Impute Only:
[[1.         4.        ]
 [2.         6.        ]
 [3.         6.        ]
 [3.33333333 5.        ]
 [6.         3.        ]
 [6.         8.        ]
 [9.         2.        ]
 [4.         8.        ]
 [5.         3.        ]]

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 2018-01-09
    • 2020-09-16
    • 1970-01-01
    • 2018-11-22
    • 2017-01-17
    • 1970-01-01
    • 2021-02-09
    • 2021-09-21
    相关资源
    最近更新 更多