东方耀AI技术分享

标题: 数据归一化的方式 [打印本页]

作者: 东方耀    时间: 2019-9-11 10:38
标题: 数据归一化的方式



数据归一化的方式


from sklearn.preprocessing import MinMaxScaler
最值归一化 normalization :把所有数据映射到0-1之间 适用于分布有明显边界的情况


from sklearn.preprocessing import StandardScaler
均值方差归一化 standardization :把所有数据归一化到均值为0 方差为1的分布中 没有明显的边界的情况也适用


  1. import numpy as np


  2. class StandardScaler:

  3.     def __init__(self):
  4.         self.mean_ = None
  5.         self.scale_ = None

  6.     def fit(self, X):
  7.         """根据训练数据集X获得数据的均值和方差"""
  8.         assert X.ndim == 2, "The dimension of X must be 2"

  9.         self.mean_ = np.array([np.mean(X[:,i]) for i in range(X.shape[1])])
  10.         self.scale_ = np.array([np.std(X[:,i]) for i in range(X.shape[1])])

  11.         return self

  12.     def transform(self, X):
  13.         """将X根据这个StandardScaler进行均值方差归一化处理"""
  14.         assert X.ndim == 2, "The dimension of X must be 2"
  15.         assert self.mean_ is not None and self.scale_ is not None, \
  16.                "must fit before transform!"
  17.         assert X.shape[1] == len(self.mean_), \
  18.                "the feature number of X must be equal to mean_ and std_"

  19.         resX = np.empty(shape=X.shape, dtype=float)
  20.         for col in range(X.shape[1]):
  21.             resX[:,col] = (X[:,col] - self.mean_[col]) / self.scale_[col]
  22.         return resX
复制代码








欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/) Powered by Discuz! X3.4