zoukankan      html  css  js  c++  java
  • 【笔记】scikitlearn中的Scaler(归一化)

    scikit-learn中的数据归一化

    在机器学习使用数据归一化的时候有一个重要的注意事项

    我们对训练数据进行均值和方差的处理,得到mean_train以及std_train,但是在对测试数据进行归一化的时候,是不能直接用测试数据的均值和方差来进行归一化的,应该使用训练数据的均值和方差对测试数据进行均值方差归一化

    为什么要这样做呢,我们训练这个模型是为了在真实的环境中去使用的,测试数据是模拟真实的环境,但是真实环境很有可能是没法得到所有的测试数据的均值和方差的,是很难得到这种统计数据的,另外,对数据的归一化也是算法的一部分,我们针对后面来的数据,应该也对其进行这样的处理

    那么我们就必须要保存训练数据集得到的均值和方差
    整体流程

    实际操作(以鸢尾花为例)
    x前十行的内容(并未进行归一化处理)

    scikit-learn中的standardscaler
    想调用,只需要

      from sklearn.preprocessing import StandardScaler
    

    创建一个实例

      standardScaler = StandardScaler()
    

    进行fit操作,其包含了很多的信息

      standardScaler.fit(X_train)
    

    数组的均值(对应的四个特征的均值)
    对于mean_的_,对于是由用户传进去的变量计算得到的,用户可以随时在外围进行查询的,在后面要有_才行

    方差

      standardScaler.std_
    

    这个我的版本已经弃用了,使用的话会报错

    标准差

      standardScaler.scale_
    

    现在可以正式使用transform进行数据归一化处理

    注意:这样处理以后,X_train实际上没有进行变化

    使用

      X_train = standardScaler.transform(X_train)
    

    就可以使X_train保存下归一化以后的矩阵了
    在对训练矩阵进行归一化

      X_test_standard = standardScaler.transform(X_test)
    

    使用knn算法进行预测分析准确率

    值得注意的是,当我们用归一化以后的训练集来训练机器算法之后,我们在预测的时候,测试数据集必须同样进行归一化,不然的话准确率会相当的低

    在pc中手动写出可以实现的归一化

      import numpy as np
    
    
      class StandardScaler:
    
          def __init__(self):
              self.mean_ = None
              self.scale_ = None;
    
          def fit(self, X):
              assert X.ndim == 2, "The dimension of X must be 2"
    
              self.mean_ = np.array([np.mean(X[:, i]) for i in range(X.shape[1])])
              self.scale_ = np.array([np.std(X[:, i]) for i in range(X.shape[1])])
    
              return self
    
          def tranform(self, X):
              assert X.ndim == 2, "The dimension of X must be 2"
              assert self.mean_ is not None and self.scale_ is not None, \
                  "must fit before transform!"
              assert X.shape[1] == len(self.mean_), \
                  "the feature number of X must be equal to mean_ and std_"
    
              resX = np.empty(shape=X.shape, dtype=float)
              for col in range(X.shape[1]):
                  resX[:, col] = (X[:, col] - self.mean_[col]) / self.scale_[col]
    
              return resX
    

    您能读到这儿,我呢是发自真心的感谢您,若要转载,还望请您带上链接
  • 相关阅读:
    HDU 1058 Humble Numbers
    HDU 1421 搬寝室
    HDU 1176 免费馅饼
    七种排序算法的实现和总结
    算法纲要
    UVa401 回文词
    UVa 10361 Automatic Poetry
    UVa 537 Artificial Intelligence?
    UVa 409 Excuses, Excuses!
    UVa 10878 Decode the tape
  • 原文地址:https://www.cnblogs.com/jokingremarks/p/14277719.html
Copyright © 2011-2022 走看看