在 sklearn 预处理中跟踪输出列
Keeping track of the output columns in sklearn preprocessing
如何跟踪 sklearn.compose.ColumnTransformer
生成的转换数组的列? "keeping track of" 我的意思是执行逆变换所需的每一位信息都必须 显式显示 。这至少包括以下内容:
- 输出数组中每一列的源变量是什么?
- 如果输出数组的一列来自分类变量的单热编码,那么该类别是什么?
- 每个变量的确切估算值是多少?
- 用于标准化每个数值变量的(平均值,标准偏差)是多少? (由于估算的缺失值,这些可能与直接计算不同。)
我正在使用基于 this answer 的相同方法。我的输入数据集也是一个具有多个数字和分类列的通用 pandas.DataFrame
。是的,这个答案可以转换原始数据集。但是我忘记了输出数组中的列。我需要这些信息用于同行评审、报告撰写、演示和进一步的模型构建步骤。我一直在寻找一种系统的方法,但没有运气。
上面提到的答案是基于Sklearn中的this。
您可以使用以下代码片段获得前两个问题的答案。
def get_feature_names(columnTransformer):
output_features = []
for name, pipe, features in columnTransformer.transformers_:
if name!='remainder':
for i in pipe:
trans_features = []
if hasattr(i,'categories_'):
trans_features.extend(i.get_feature_names(features))
else:
trans_features = features
output_features.extend(trans_features)
return output_features
import pandas as pd
pd.DataFrame(preprocessor.fit_transform(X_train),
columns=get_feature_names(preprocessor))
transformed_cols = get_feature_names(preprocessor)
def get_original_column(col_index):
return transformed_cols[col_index].split('_')[0]
get_original_column(3)
# 'embarked'
get_original_column(0)
# 'age'
def get_category(col_index):
new_col = transformed_cols[col_index].split('_')
return 'no category' if len(new_col)<2 else new_col[-1]
print(get_category(3))
# 'Q'
print(get_category(0))
# 'no category'
对于当前版本的 Sklearn,跟踪是否对特征进行了一些插补或缩放并非易事。
如何跟踪 sklearn.compose.ColumnTransformer
生成的转换数组的列? "keeping track of" 我的意思是执行逆变换所需的每一位信息都必须 显式显示 。这至少包括以下内容:
- 输出数组中每一列的源变量是什么?
- 如果输出数组的一列来自分类变量的单热编码,那么该类别是什么?
- 每个变量的确切估算值是多少?
- 用于标准化每个数值变量的(平均值,标准偏差)是多少? (由于估算的缺失值,这些可能与直接计算不同。)
我正在使用基于 this answer 的相同方法。我的输入数据集也是一个具有多个数字和分类列的通用 pandas.DataFrame
。是的,这个答案可以转换原始数据集。但是我忘记了输出数组中的列。我需要这些信息用于同行评审、报告撰写、演示和进一步的模型构建步骤。我一直在寻找一种系统的方法,但没有运气。
上面提到的答案是基于Sklearn中的this。
您可以使用以下代码片段获得前两个问题的答案。
def get_feature_names(columnTransformer):
output_features = []
for name, pipe, features in columnTransformer.transformers_:
if name!='remainder':
for i in pipe:
trans_features = []
if hasattr(i,'categories_'):
trans_features.extend(i.get_feature_names(features))
else:
trans_features = features
output_features.extend(trans_features)
return output_features
import pandas as pd
pd.DataFrame(preprocessor.fit_transform(X_train),
columns=get_feature_names(preprocessor))
transformed_cols = get_feature_names(preprocessor)
def get_original_column(col_index):
return transformed_cols[col_index].split('_')[0]
get_original_column(3)
# 'embarked'
get_original_column(0)
# 'age'
def get_category(col_index):
new_col = transformed_cols[col_index].split('_')
return 'no category' if len(new_col)<2 else new_col[-1]
print(get_category(3))
# 'Q'
print(get_category(0))
# 'no category'
对于当前版本的 Sklearn,跟踪是否对特征进行了一些插补或缩放并非易事。