• 数据正规化 (data normalization) 的原理及实现 (Python sklearn)


    原理

    数据正规化(data normalization)是将数据的每个样本(向量)变换为单位范数的向量,各样本之间是相互独立的.其实际上,是对向量中的每个分量值除以正规化因子.常用的正规化因子有 L1, L2 和 Max.假设,对长度为 n 的向量,其正规化因子 z 的计算公式,如下所示:

    注意:Max 与无穷范数  不同,无穷范数 是需要先对向量的所有分量取绝对值,然后取其中的最大值;而 Max 是向量中的最大分量值,不需要取绝对值的操作.

    补充:一阶范数也称为曼哈顿距离(Manhanttan distance)或街区距离;二阶范数也称为欧式距离(Euclidean distance).

    实现

    在 Python 库 sklearn 中,有两种实现方式进行数据的正规化,这两种实现都可通过参数 norm 选择正规化因子,可选项有 'l1', 'l2' 和 'max'.

    方法一:采用 sklearn.preprocessing.Normalizer 类,其示例代码如下:

    #!/usr/bin/env python
    # -*- coding: utf8 -*-
    # author: klchang
    # Use sklearn.preprocessing.Normalizer class to normalize data.
    from __future__ import print_function
    import numpy as np
    from sklearn.preprocessing import Normalizer
    
    
    x = np.array([1, 2, 3, 4], dtype='float32').reshape(1,-1)
    
    print("Before normalization: ", x)
    
    options = ['l1', 'l2', 'max']
    for opt in options:
        norm_x = Normalizer(norm=opt).fit_transform(x)
        print("After %s normalization: " % opt.capitalize(), norm_x)

    方法二:采用 sklearn.preprocessing.normalize 函数,其示例代码如下:

    #!/usr/bin/env python
    # -*- coding: utf8 -*-
    # author: klchang
    # Use sklearn.preprocessing.normalize function to normalize data.
    from __future__ import print_function import numpy as np from sklearn.preprocessing import normalize x = np.array([1, 2, 3, 4], dtype='float32').reshape(1,-1) print("Before normalization: ", x) options = ['l1', 'l2', 'max'] for opt in options: norm_x = normalize(x, norm=opt) print("After %s normalization: " % opt.capitalize(), norm_x)

    参考资料

    1. Scikit-learn Normalization mode (L1 vs L2 & Max). https://stats.stackexchange.com/questions/225564/scikit-learn-normalization-mode-l1-vs-l2-max

    2. sklearn.preprocessing.Normalizer - scikit-learn Documentation. http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Normalizer.html

    3. sklearn.preprocessing.normalize - scikit-learn Documentation. http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.normalize.html

    4. scikit-learn Documentation - 4.3. Preprocessing data. http://scikit-learn.org/stable/modules/preprocessing.html

    5. Norm (mathematics). https://en.wikipedia.org/w/index.php?title=Norm_(mathematics)&oldid=838245314

  • 相关阅读:
    【41】了解隐式接口和编译期多态
    【17】以独立语句将newed对象置入智能指针
    【16】成对使用new和delete时要采取相同形式
    【15】在资源管理类中提供对原始资源的访问
    【14】在资源管理类中小心copying行为
    【02】尽量以const,enum,inline替换#define
    【01】视C++为一个语言联邦
    一次数据库hang住的分析过程
    针对某个数据库error做systemstate dump
    数据库hang住如何收集信息
  • 原文地址:https://www.cnblogs.com/klchang/p/8973968.html
Copyright © 2020-2023  润新知