相关疑难解决方法(0)

使用scikit-learn对连续变量和分类变量(整数类型)进行预处理

主要目标如下:

1)适用StandardScaler于连续变量

2)应用LabelEncoderOnehotEncoder分类变量

连续变量需要缩放,但同时,一些分类变量也是整数类型.应用StandardScaler会导致不良影响.

另一方面,StandardScaler将扩展基于整数的分类变量,这也不是我们的.

由于连续变量和分类变量混合在一个PandasDataFrame中,所以推荐的工作流程是什么来解决这类问题?

说明我的观点的最好例子是Kaggle Bike Sharing Demand数据集,其中seasonweather是整数分类变量

python machine-learning pandas scikit-learn categorical-data

9
推荐指数
1
解决办法
5899
查看次数

在Pandas数据帧列的子集上使用Pipeline中的scikit StandardScaler

我想在pandas dataframe列的子集上使用sklearn.preprocessing.StandardScaler.在管道之外,这是微不足道的:

df[['A', 'B']] = scaler.fit_transform(df[['A', 'B']])
Run Code Online (Sandbox Code Playgroud)

但现在假设我在类型字符串的df中有列'C',以及下面的管道定义

from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

pipeline =  Pipeline([
                ('standard', StandardScaler())
            ])

df_scaled = pipeline.fit_transform(df)
Run Code Online (Sandbox Code Playgroud)

如何告诉StandardScaler只扩展A列和B列?

我已经习惯了SparkML管道,其中要缩放的特征可以传递给缩放器组件的构造函数:

normalizer = Normalizer(inputCol="features", outputCol="features_norm", p=1.0)
Run Code Online (Sandbox Code Playgroud)

注意:要素列包含稀疏向量,其中包含Spark的VectorAssembler创建的所有数字要素列

python pandas scikit-learn

9
推荐指数
2
解决办法
1207
查看次数

如何将 sklearn Pipeline 上的每个步骤应用于选定的列?

当我查找 sklearn.Pipeline 中的步骤如何准备仅在某些列上操作时,我从stackoverflow 上的这个答案中偶然发现了sklearn.Pipeline.FeatureUnion。但是,我不太清楚如何不对我不想要的列应用任何内容并将完整的数据传递到下一步。例如,在我的第一步中,我只想应用于某些列,可以使用下面所示的代码来完成,但问题是下一步将只有标准缩放的列。如何在下一步中获得完整的数据以及上一步中标准缩放的列?StandardScaler

这是一些示例代码:

from sklearn.pipeline import Pipeline, FeatureUnion, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.neighbors import KNeighborsClassifier

class Columns(BaseEstimator, TransformerMixin):
    def __init__(self, names=None):
        self.names = names

    def fit(self, X, y=None, **fit_params):
        return self

    def transform(self, X):
        return X[self.names]


pipe = Pipeline([
    # steps below applies on only some columns
    ("features", FeatureUnion([
        ('numeric', make_pipeline(Columns(names=[list of numeric column names]), StandardScaler())),
    ])),
    ('feature_engineer_step1', FeatEng_1()),
    ('feature_engineer_step2', FeatEng_2()),
    ('feature_engineer_step3', FeatEng_3()),
    ('remove_skew', Skew_Remover()),

    # …
Run Code Online (Sandbox Code Playgroud)

python pipeline python-3.x scikit-learn

1
推荐指数
1
解决办法
2891
查看次数