理解 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM