繁体   English   中英

如何创建一个函数,循环遍历 numpy 矩阵以 z 缩放每个数据点,返回标准化的数据

[英]How to create a function that loops through numpy matrix to z-scale each and every data points returning the data standardized

如何创建一个函数,循环遍历 numpy 矩阵以 z 缩放每个数据点,返回标准化的数据。 就像 sklearn.preprocessing.StandardScaler 是如何做到的。 我已经到了这里,但没有成功。 有人可以帮我吗?

def stand_scaler(data):
    mean = np.mean(data, axis=0)
    std = np.std(data, axis=0)
    for i in range(len(data)):
        data[i] = (data[i] - mean)/std
        return data

stand_scaler(data)

您不应该为此需要 for 循环; numpy 的数组操作正是针对这种情况。 对于一维数组,它很简单:

In [1]: import numpy as np

In [2]: x = np.random.normal(size=10)

In [3]: nx = (x - x.mean()) / x.std()

In [4]: x
Out[4]: 
array([ 0.52700345, -0.57358563, -0.16925383,  2.14401554,  1.05223331,
        0.72659482,  1.06816826,  0.31194848,  0.04004589,  1.09046925])

In [5]: nx
Out[5]: 
array([-0.12859083, -1.62209992, -1.0734181 ,  2.06570881,  0.58415071,
        0.14225641,  0.60577458, -0.42042233, -0.78939654,  0.63603721])

In [6]: nx.mean()
Out[6]: 5.551115123125783e-17

In [7]: nx.std()
Out[7]: 1.0000000000000002

对于更高的维度,您可以选择要处理的轴,并使用 numpy 的广播进行缩放; 例如,在这种情况下,想象每一列是一个不同的变量:

In [8]: y = np.array([10,1]) * np.random.normal(size=(5,2)) - np.array([5,-10])

In [9]: ny = (y - y.mean(axis=0)) / y.std(axis=0)

In [10]: ny
Out[10]: 
array([[ 0.78076062, -0.26971997],
       [-1.59591909, -1.2409338 ],
       [-0.55740483, -0.81901609],
       [ 1.22978416,  1.12697814],
       [ 0.14277914,  1.20269171]])

In [11]: ny.mean(axis=0), ny.std(axis=0)
Out[11]: (array([-3.33066907e-17,  8.43769499e-16]), array([1., 1.]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM