简体   繁体   English

如何规范numpy数组中的子数组

[英]how to normalize subarrays in a numpy array

I have a numpy array data of shape: [128, 64, 64, 64], and I wonder what's the best way to normalized each of the 128 slices into range [0.0, 1.0]. 我有一个形状为[128、64、64、64]的numpy数组data ,我想知道将128个切片中的每个切片归一化为[0.0,1.0]的最佳方法是什么。 I understand i could use np.max(data[0,...]), np.max(data[1,...])... np.max(data[127,...]) to compute max values in each slice, but wonder if i could do this more efficiently. 我了解我可以使用np.max(data [0,...]),np.max(data [1,...])... np.max(data [127,...])进行计算每个切片中的最大值,但想知道我是否可以更有效地做到这一点。

Essentially something like this: 本质上是这样的:

data_min = np.min(data[:,...])
data_max = np.max(data[:,...])
norm_data = (data[:,...] - data_min)/(data_max - data_min)

The result should still have shape [128, 64, 64, 64] But i haven't figured out which particular min/max functions and options to use to obtain the results. 结果仍应具有形状[128、64、64、64],但是我还没有弄清楚要使用哪个特定的最小/最大函数和选项来获得结果。

Please advise. 请指教。 Thanks! 谢谢!

Get the min and max values, while keeping dimensions to help us with broadcasting later on when we use those to normalize input data using the normalization formula, like so - 获取最小值和最大值,同时保留尺寸以帮助我们稍后在使用归一化公式对输入数据进行归一化时进行broadcasting ,例如,

mins = data.min(axis=(1,2,3), keepdims=True)
maxs = data.max(axis=(1,2,3), keepdims=True)
norm_data = (data-mins)/(maxs-mins)

You can use np.vectorize to apply a function over all elements of an array: 您可以使用np.vectorize将函数应用于数组的所有元素:

def norm(element):
    return (element - data_min) / (data_max - data_min)

ndnorm = np.vectorize(norm)

data_min = data.min()
data_max = data.max()

norm_data = ndnorm(data)

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

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