pythonのnumpy行列のtips
ここ最近はCourseraのdeer learning specializationと平行して 詳解 ディープラーニングを進めているのですが、これまでrを使っていたこともあり、pythonのnumpy関連で引っかかったところをメモ代わりに。
python初心者向けの内容です。
reshapeの引数の動き
numpy配列の整形をするreshapeメソッドの引数の渡し方について。
下記のように3*4の行列を1*12の行列に変換する際に()が二重になっていてなんじゃこれと。
a = np.random.randn(3, 4)
a = a.reshape*1
例えば、上記のようなコードではreshapeの第一引数に行列の形を指定することによって、整形を行っています。
1つの引数として(1, 12)を渡しているので、()が2重になるとのこと。
ちなみに、似た機能を持つresizeを利用すると、要素数に指定した形が一致していない場合、要素数に応じて削除や繰り返しを行ってくれます。いっぽう、reshapeでは要素数に形が一致しない場合にはエラーになります。
reshapeではエラー
hoge = np.random.randn(4, 7)
hogehoge = hoge.reshape*2
print(hogehoge)
ValueError Traceback (most recent call last)
<ipython-input-40-206422a1d141> in <module>()
1 hoge = np.random.randn(4, 7)
----> 2 hogehoge = hoge.reshape*3
3 print(hogehoge)ValueError: cannot reshape array of size 28 into shape (2,28)
resizeはいい感じにしてくれる
hoge = np.random.randn(4, 7)
hogehoge = np.resize(hoge, (2,28))
print(hogehoge)
[[ 0.17984156 -1.48711857 -1.87728238 0.18789091 -0.86492046 -1.76621145
-0.29362186 0.99425392 -0.63614095 -0.27467144 -2.11563702 0.07660544
1.46468977 -1.45524859 -0.00916827 -0.61070898 -0.67908168 1.37773914
0.25296565 0.0475988 0.47181726 0.14466797 -1.55518391 -0.0218339
-0.1627627 -1.21755984 0.12008514 1.81046075]
[ 0.17984156 -1.48711857 -1.87728238 0.18789091 -0.86492046 -1.76621145
-0.29362186 0.99425392 -0.63614095 -0.27467144 -2.11563702 0.07660544
1.46468977 -1.45524859 -0.00916827 -0.61070898 -0.67908168 1.37773914
0.25296565 0.0475988 0.47181726 0.14466797 -1.55518391 -0.0218339
-0.1627627 -1.21755984 0.12008514 1.81046075]]
入れ子構造になったarrayのshape
numpyのarrayでは行列を入れ子構造にできるのだが、行列作成時の引数の指定と構造の関係がすぐに分からなかったのでメモとして。
基本的には、例えばnp.random.randn(a, b, c, x, y)で生成した場合、(x, y)の行列をベースとして、まずは(x, y)がc個繋がり、次にそれがb個、最後にまたa個繋がってという感じになる。
hoge = np.random.randn(4, 3, 2, 2)
print(hoge)
[[[[-0.58394088 -0.69682622]
[-1.3257897 -0.25776192]][[ 1.26725302 -0.05233107]
[-0.24043602 -0.40466777]][[-2.43003962 1.0796623 ]
[-1.32372067 0.00298865]]]
[[[-0.75399924 -0.23905212]
[-0.50676904 1.61758912]][[-0.57973531 0.43609008]
[ 0.4742734 0.51253294]][[ 0.61526245 -0.49094768]
[ 0.70260153 1.46168456]]]
[[[-0.53245236 -0.09998614]
[ 0.20760135 0.27993352]][[ 0.56461812 2.28180134]
[ 0.33748457 1.07951289]][[-2.03471952 -0.17823477]
[-0.83554739 -1.74027867]]]
[[[ 0.89970965 -0.63134293]
[ 0.21429068 0.63303917]][[ 0.84023875 0.03602931]
[-0.15912151 -1.948296 ]][[ 0.67663275 -0.44216258]
[ 0.44355083 -0.56121392]]]]
ただ、(x, y)が繋がった移行の行と列の概念が分からんままです。。
行列の形確認に便利なshape
shape関数で行列の形を確認できる。
a.shape
Andrew NgもCourseraで適宜shapeで確認することを推奨していました。