沿给定轴将 ndarray 除以最大值
Divide ndarray by maximums along given axis
假设我有一个这样的数组
import numpy as np
a = np.array([[2]*9 + [3]*9 + [4]*9])
a = a.reshape((-1,3, 3))
print(a)
这是
[[[2 2 2]
[2 2 2]
[2 2 2]]
[[3 3 3]
[3 3 3]
[3 3 3]]
[[4 4 4]
[4 4 4]
[4 4 4]]]
因此,例如,如果我想将轴 0 中的每个对象除以其最大值(只得到 1),我将如何在不循环的情况下做到这一点?
您可以在第一个轴的每个 ndarray
中找到最大值,方法是沿行和列取 np.max
,设置 keepdims=True
,因此 a
被划分通过沿第一个轴产生的最大值:
a / np.max(a, axis=(1,2), keepdims=True)
输出
array([[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]])
基于上述答案,我认为将其扩展到需要多个 numpy 函数的转换会很有用,例如使用 min/max:
在 [0,1] 中进行归一化
import numpy as np
np.random.seed(1)
def zero_one_normalize_3d(arr):
fs = np.min, np.max
arr_min, arr_max = [f(arr, axis = (1, 2), keepdims = True) for f in fs]
return (arr - arr_min) / (arr_max - arr_min)
def zero_one_normalize_2d(arr):
return (arr - arr.min()) / (arr.max() - arr.min())
points = 10000
x1 = np.random.normal(3, 10, points)
x2 = np.random.normal(6, 10, points)
x3 = np.random.normal(9, 10, points)
a = np.column_stack((x1, x2, x3))
a = a.reshape(-1, 10, 3)
print(np.alltrue(zero_one_normalize_3d(a)[0] == zero_one_normalize_2d(a[0])))
> True
假设我有一个这样的数组
import numpy as np
a = np.array([[2]*9 + [3]*9 + [4]*9])
a = a.reshape((-1,3, 3))
print(a)
这是
[[[2 2 2]
[2 2 2]
[2 2 2]]
[[3 3 3]
[3 3 3]
[3 3 3]]
[[4 4 4]
[4 4 4]
[4 4 4]]]
因此,例如,如果我想将轴 0 中的每个对象除以其最大值(只得到 1),我将如何在不循环的情况下做到这一点?
您可以在第一个轴的每个 ndarray
中找到最大值,方法是沿行和列取 np.max
,设置 keepdims=True
,因此 a
被划分通过沿第一个轴产生的最大值:
a / np.max(a, axis=(1,2), keepdims=True)
输出
array([[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]])
基于上述答案,我认为将其扩展到需要多个 numpy 函数的转换会很有用,例如使用 min/max:
在 [0,1] 中进行归一化import numpy as np
np.random.seed(1)
def zero_one_normalize_3d(arr):
fs = np.min, np.max
arr_min, arr_max = [f(arr, axis = (1, 2), keepdims = True) for f in fs]
return (arr - arr_min) / (arr_max - arr_min)
def zero_one_normalize_2d(arr):
return (arr - arr.min()) / (arr.max() - arr.min())
points = 10000
x1 = np.random.normal(3, 10, points)
x2 = np.random.normal(6, 10, points)
x3 = np.random.normal(9, 10, points)
a = np.column_stack((x1, x2, x3))
a = a.reshape(-1, 10, 3)
print(np.alltrue(zero_one_normalize_3d(a)[0] == zero_one_normalize_2d(a[0])))
> True