[PYTHON] Let's do it by dividing numpy without using the for statement

When you want to normalize on a certain axis

If the scale is different for each axis and it collapses when compared collectively, I would like to divide each axis by the maximum value or total value to normalize and compare. You can do it with a for statement, but you can easily do it with ** keepdims = True **. I added an axis after sum, but ** keepdims ** can do the same thing. I feel that there is something for this.

AAA  = np.arange(24).reshape((2,3,4)) 
print("AAA.shape=", AAA.shape)
print("AAA=", AAA)

sAAA = AAA.sum(-1, keepdims=True)
# sAAA = AAA.sum(-1)[..., np.newaxis]Same as. 
nAAA = AAA / sAAA
print("\nsAAA.shape=", sAAA.shape)
print("\nnAAA=", nAAA)

mAAA = AAA.max(1, keepdims=True)
# mAAA = AAA.max(1)[:, np.newaxis]Same as
nAAA = AAA / mAAA
print("\nmAAA.shape=", mAAA.shape)
print("\nnAAA=", nAAA)

mAAA = AAA.max((0,2), keepdims=True)
nAAA = AAA / mAAA
print("\nsAAA.shape=", sAAA.shape)
print("\nnAAA=", nAAA)
AAA.shape= (2, 3, 4)
AAA= [[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

sAAA.shape= (2, 3, 1)

nAAA= [[[0.         0.16666667 0.33333333 0.5       ]
  [0.18181818 0.22727273 0.27272727 0.31818182]
  [0.21052632 0.23684211 0.26315789 0.28947368]]

 [[0.22222222 0.24074074 0.25925926 0.27777778]
  [0.22857143 0.24285714 0.25714286 0.27142857]
  [0.23255814 0.24418605 0.25581395 0.26744186]]]

mAAA.shape= (2, 1, 4)

nAAA= [[[0.         0.11111111 0.2        0.27272727]
  [0.5        0.55555556 0.6        0.63636364]
  [1.         1.         1.         1.        ]]

 [[0.6        0.61904762 0.63636364 0.65217391]
  [0.8        0.80952381 0.81818182 0.82608696]
  [1.         1.         1.         1.        ]]]

sAAA.shape= (2, 3, 1)

nAAA= [[[0.         0.06666667 0.13333333 0.2       ]
  [0.21052632 0.26315789 0.31578947 0.36842105]
  [0.34782609 0.39130435 0.43478261 0.47826087]]

 [[0.8        0.86666667 0.93333333 1.        ]
  [0.84210526 0.89473684 0.94736842 1.        ]
  [0.86956522 0.91304348 0.95652174 1.        ]]]

Recommended Posts

Let's do it by dividing numpy without using the for statement
Let's do it by multiplying numpy without using the for statement
Do a search by image from the camera roll using Pythonista3
Understanding the python class Struggle (1) Let's move it for the time being
Let's display the map using Basemap
[Python] Multiplication table using for statement
For the first time in Numpy, I will update it from time to time
I thought it would be slow to use a for statement in NumPy, but that wasn't the case.