当前位置:   article > 正文

sklearn:sklearn.preprocessing的MinMaxScaler简介、使用方法(包括自定scale_minmax函数义代码实现)之详细攻略_sklearn minmaxscaler

sklearn minmaxscaler

sklearn:sklearn.preprocessing的MinMaxScaler简介、使用方法(包括自定scale_minmax函数义代码实现)之详细攻略

目录

MinMaxScaler简介

MinMaxScaler函数解释

MinMaxScaler底层代码

MinMaxScaler的使用方法

1、基础案例

2、自定scale_minmax函数义代码实现


MinMaxScaler简介

MinMaxScaler函数解释

    """Transforms features by scaling each feature to a given range.
    
    This estimator scales and translates each feature individually such that it is in the given range on the training set, i.e. between zero and one.
    
    The transformation is given by::
    
    X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
    X_scaled = X_std * (max - min) + min
    
    where min, max = feature_range.
    
    This transformation is often used as an alternative to zero mean, unit variance scaling.
    
    Read more in the :ref:`User Guide <preprocessing_scaler>`.
“”通过将每个特性缩放到给定范围来转换特性。

这个估计量对每个特征进行了缩放和单独转换,使其位于训练集的给定范围内,即在0和1之间

变换由::

    X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
    X_scaled = X_std * (max - min) + min

其中,min, max = feature_range。

这种转换经常被用来替代零均值,单位方差缩放。

请参阅:ref: ' User Guide  '。</preprocessing_scaler>
    Parameters
    ----------
    feature_range : tuple (min, max), default=(0, 1)
    Desired range of transformed data.
    
    copy : boolean, optional, default True
    Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array).
参数

feature_range: tuple (min, max),默认值=(0,1)
所需的转换数据范围。

复制:布尔值,可选,默认为真
设置为False执行插入行规范化并避免复制(如果输入已经是numpy数组)。
    Attributes
    ----------
    min_ : ndarray, shape (n_features,)
    Per feature adjustment for minimum.
    
    scale_ : ndarray, shape (n_features,)
    Per feature relative scaling of the data.
    
    .. versionadded:: 0.17
    *scale_* attribute.
    
    data_min_ : ndarray, shape (n_features,)
    Per feature minimum seen in the data
    
    .. versionadded:: 0.17
    *data_min_*
    
    data_max_ : ndarray, shape (n_features,)
    Per feature maximum seen in the data
    
    .. versionadded:: 0.17
    *data_max_*
    
    data_range_ : ndarray, shape (n_features,)
    Per feature range ``(data_max_ - data_min_)`` seen in the data
    
    .. versionadded:: 0.17
    *data_range_*

属性
 ----------
min_: ndarray, shape (n_features,)
每个功能调整为最小。

scale_: ndarray, shape (n_features,)
每个特征数据的相对缩放。

. .versionadded:: 0.17
* scale_ *属性。

data_min_: ndarray, shape (n_features,)
每个特征在数据中出现的最小值

. .versionadded:: 0.17
* data_min_ *

data_max_: ndarray, shape (n_features,)
每个特征在数据中出现的最大值


. .versionadded:: 0.17
* data_max_ *
data_range_: ndarray, shape (n_features,)
在数据中看到的每个特性范围' ' (data_max_ - data_min_) ' '


. .versionadded:: 0.17
* data_range_ *

MinMaxScaler底层代码

  1. class MinMaxScaler Found at: sklearn.preprocessing.data
  2. class MinMaxScaler(BaseEstimator, TransformerMixin):
  3. def __init__(self, feature_range=(0, 1), copy=True):
  4. self.feature_range = feature_range
  5. self.copy = copy
  6. def _reset(self):
  7. """Reset internal data-dependent state of the scaler, if
  8. necessary.
  9. __init__ parameters are not touched.
  10. """
  11. # Checking one attribute is enough, becase they are all set
  12. together
  13. # in partial_fit
  14. if hasattr(self, 'scale_'):
  15. del self.scale_
  16. del self.min_
  17. del self.n_samples_seen_
  18. del self.data_min_
  19. del self.data_max_
  20. del self.data_range_
  21. def fit(self, X, y=None):
  22. """Compute the minimum and maximum to be used for later
  23. scaling.
  24. Parameters
  25. ----------
  26. X : array-like, shape [n_samples, n_features]
  27. The data used to compute the per-feature minimum and
  28. maximum
  29. used for later scaling along the features axis.
  30. """
  31. # Reset internal state before fitting
  32. self._reset()
  33. return self.partial_fit(X, y)
  34. def partial_fit(self, X, y=None):
  35. """Online computation of min and max on X for later scaling.
  36. All of X is processed as a single batch. This is intended for
  37. cases
  38. when `fit` is not feasible due to very large number of
  39. `n_samples`
  40. or because X is read from a continuous stream.
  41. Parameters
  42. ----------
  43. X : array-like, shape [n_samples, n_features]
  44. The data used to compute the mean and standard deviation
  45. used for later scaling along the features axis.
  46. y : Passthrough for ``Pipeline`` compatibility.
  47. """
  48. feature_range = self.feature_range
  49. if feature_range[0] >= feature_range[1]:
  50. raise ValueError(
  51. "Minimum of desired feature range must be smaller"
  52. " than maximum. Got %s." %
  53. str(feature_range))
  54. if sparse.issparse(X):
  55. raise TypeError("MinMaxScaler does no support sparse
  56. input. "
  57. "You may consider to use MaxAbsScaler instead.")
  58. X = check_array(X, copy=self.copy, warn_on_dtype=True,
  59. estimator=self, dtype=FLOAT_DTYPES)
  60. data_min = np.min(X, axis=0)
  61. data_max = np.max(X, axis=0)
  62. # First pass
  63. if not hasattr(self, 'n_samples_seen_'):
  64. self.n_samples_seen_ = X.shape[0]
  65. else:
  66. data_min = np.minimum(self.data_min_, data_min)
  67. data_max = np.maximum(self.data_max_, data_max)
  68. self.n_samples_seen_ += X.shape[0] # Next steps
  69. data_range = data_max - data_min
  70. self.scale_ = (feature_range[1] - feature_range[0]) /
  71. _handle_zeros_in_scale(data_range)
  72. self.min_ = feature_range[0] - data_min * self.scale_
  73. self.data_min_ = data_min
  74. self.data_max_ = data_max
  75. self.data_range_ = data_range
  76. return self
  77. def transform(self, X):
  78. """Scaling features of X according to feature_range.
  79. Parameters
  80. ----------
  81. X : array-like, shape [n_samples, n_features]
  82. Input data that will be transformed.
  83. """
  84. check_is_fitted(self, 'scale_')
  85. X = check_array(X, copy=self.copy, dtype=FLOAT_DTYPES)
  86. X *= self.scale_
  87. X += self.min_
  88. return X
  89. def inverse_transform(self, X):
  90. """Undo the scaling of X according to feature_range.
  91. Parameters
  92. ----------
  93. X : array-like, shape [n_samples, n_features]
  94. Input data that will be transformed. It cannot be sparse.
  95. """
  96. check_is_fitted(self, 'scale_')
  97. X = check_array(X, copy=self.copy, dtype=FLOAT_DTYPES)
  98. X -= self.min_
  99. X /= self.scale_
  100. return X

MinMaxScaler的使用方法

1、基础案例

  1. >>> from sklearn.preprocessing import MinMaxScaler
  2. >>>
  3. >>> data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
  4. >>> scaler = MinMaxScaler()
  5. >>> print(scaler.fit(data))
  6. MinMaxScaler(copy=True, feature_range=(0, 1))
  7. >>> print(scaler.data_max_)
  8. [ 1. 18.]
  9. >>> print(scaler.transform(data))
  10. [[ 0. 0. ]
  11. [ 0.25 0.25]
  12. [ 0.5 0.5 ]
  13. [ 1. 1. ]]
  14. >>> print(scaler.transform([[2, 2]]))
  15. [[ 1.5 0. ]]

2、自定scale_minmax函数义代码实现

  1. def scale_minmax(col):
  2. return (col-col.min())/(col.max()-col.min())
  3. df_cols_num_sca = df[cols_num].apply(scale_minmax,axis=0)
  4. print(df_cols_num_sca.head())

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/174551
推荐阅读
相关标签
  

闽ICP备14008679号