LoginSignup
0
0

More than 3 years have passed since last update.

for文を使わずに、numpy の割り算でやってみよう

Posted at

ある軸で正規化したいとき

軸毎にスケールが違って、まとめて比較するとつぶれてしまう場合に、軸毎に最大値や合計値で割って正規化して比較したい。
for文でもできるけど、keepdims=True 使うと簡単にできる。
sumした後わざわざ軸追加したけど、keepdimsで同じことができるとは。このためにあるぐらいって気がする。

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] と同じ. 
nAAA = AAA / sAAA
print("\nsAAA.shape=", sAAA.shape)
print("\nnAAA=", nAAA)

mAAA = AAA.max(1, keepdims=True)
# mAAA = AAA.max(1)[:, np.newaxis] と同じ
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.        ]]]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0