如何解决为什么MinMaxScaler仅应用于某些列不能使我的数据框标准化?
我需要规范化数据集中的列,避免规范化某些已经具有较小值和低于1的标准偏差的列。我要规范化的所有列都存储在 columns_to_normalize 列表中。执行以下代码仍然无法在规范化过程中提供帮助:
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from pandas import DataFrame
# create scaler
minmax_transformer = Pipeline(steps=[
('minmax',MinMaxScaler())])
# perform normalization on the dataset,avoiding ordinal columns
preprocessor = ColumnTransformer(
remainder='passthrough',transformers=[
('mm',minmax_transformer,columns_to_normalize)
])
# fit and transform model on data
df_norm_values = preprocessor.fit_transform(df)
# convert the array back to a dataframe
df_norm = DataFrame(df_norm_values)
# set columns' names
column_names = list(df.columns)
df_norm.columns = column_names
# normalized input variable's summarry
df_norm.describe()
为方便起见,最后两列未完全标准化,因为最小值为0.00和1.00,最大值为3.00和4.00),我不明白为什么我的代码不能成功实现这一点。
解决方法
缩放器可以正常工作,但是ColumnTransformer
正在更改列的顺序:
来自ColumnTransformer's documentation:
变换后的特征矩阵中列的顺序遵循 在转换器列表中指定列的顺序。 未指定原始要素矩阵的列为 从结果转换后的特征矩阵中删除,除非 在passthrough关键字中指定。那些用 直通会添加到变压器输出的右侧。
这是一个快速解决方法:
minmax_transformer = Pipeline(steps=[
('minmax',MinMaxScaler())])
# perform normalization on the dataset,avoiding ordinal columns
preprocessor = ColumnTransformer(
remainder='passthrough',transformers=[
('mm',minmax_transformer,columns_to_normalize)
])
# fit and transform model on data
df_norm_values = preprocessor.fit_transform(df)
# convert the array back to a dataframe
df_norm = DataFrame(df_norm_values)
# set columns' names
passthrough_cols = list(df.columns)
for col in columns_to_normalize: # remove cols that will be scaled
passthrough_cols.remove(col)
column_names = columns_to_normalize
column_names.extend(passthrough_cols) # stack columns names
df_norm.columns = column_names
# normalized input variable's summarry
df_norm.describe()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。