理解 sklearn.preprocessing.MinMaxScaler

公式

非常有用的工具,可以把数据集的不同特征缩放到固定范围。

先从简单的说起,[0,1]缩放,公式

\(X_{scaled} = \frac{x-x_{min}}{x_{max}-x_{min}}\)

MinMaxScaler可以缩放到任意范围[MIN,MAX],因此更一般化的公式是

\(X_{std} = \frac{x-x_{min}}{x_{max}-x_{min}}\)\(X_{scaled} = \frac{X_{std}}{MAX-MIN} + MIN\)

\(MIN\)\(MAX\)为0和1时,公式等价于[0,1]缩放。

代码

再来看源代码。

def transform(self, X):
        """Scale features of X according to feature_range.
        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input data that will be transformed.
        Returns
        -------
        Xt : array-like of shape (n_samples, n_features)
            Transformed data.
        """
        check_is_fitted(self)

        X = check_array(X, copy=self.copy, dtype=FLOAT_DTYPES,
                        force_all_finite="allow-nan")

        X *= self.scale_
        X += self.min_
        return X
"""
    min_ : ndarray of shape (n_features,)
        Per feature adjustment for minimum. Equivalent to
        ``min - X.min(axis=0) * self.scale_``
    scale_ : ndarray of shape (n_features,)
        Per feature relative scaling of the data. Equivalent to
        ``(max - min) / (X.max(axis=0) - X.min(axis=0))``
        .. versionadded:: 0.17
           *scale_* attribute.
    data_min_ : ndarray of shape (n_features,)
        Per feature minimum seen in the data
        .. versionadded:: 0.17
           *data_min_*
    data_max_ : ndarray of shape (n_features,)
        Per feature maximum seen in the data
        .. versionadded:: 0.17
           *data_max_*
"""

这里的scale_相当于\(\frac{MAX-MIN}{x_{max}-x_{min}}\),所以min_相当于\(MIN-x_{min}*\frac{MAX-MIN}{x_{max}-x_{min}}\),这两个参数主要是方便以下逆变换

def inverse_transform(self, X):
        """Undo the scaling of X according to feature_range.
        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input data that will be transformed. It cannot be sparse.
        Returns
        -------
        Xt : array-like of shape (n_samples, n_features)
            Transformed data.
        """
        check_is_fitted(self)

        X = check_array(X, copy=self.copy, dtype=FLOAT_DTYPES,
                        force_all_finite="allow-nan")

        X -= self.min_
        X /= self.scale_
        return X
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值