沿给定轴将ndarray除以最大值

时间:2019-03-02 18:50:18

标签: python numpy multidimensional-array tensor

说我有一个像这样的数组

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),该如何在不循环的情况下做到这一点?

2 个答案:

答案 0 :(得分:1)

通过沿其行和列取np.max,将ndarray设置为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.]]])

输出

class Handler {
  handleReq = () => {
    this.ctx = ctx;
  };

  testFunc = async () => {

  };
}

export default (HandleReq = Handler.prototype.handleReq);

答案 1 :(得分:0)

基于以上答案,我认为将其扩展到不仅需要单个numpy函数的转换是有用的,例如使用最小值/最大值在[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
相关问题