numpy基礎

numpy基礎

インポート

import numpy as np

shape, transpose, reshape, flatten

>>> W = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(W.shape)
(2, 3)
>>> print(W)
[[1 2 3]
 [4 5 6]]
>>> print(W.T)
[[1 4]
 [2 5]
 [3 6]]
>>> print(W.reshape(3,2))
[[1 2]
 [3 4]
 [5 6]]
>>> print(W.flatten())
[1 2 3 4 5 6]

numpy配列生成(zeros, ones, arange)

>>> print(np.zeros((2,3)))
[[0. 0. 0.]
 [0. 0. 0.]]
>>> print(np.ones((2,3)))
[[1. 1. 1.]
 [1. 1. 1.]]
>>> print(np.arange(1,5))
[1 2 3 4]

要素アクセス

>>> W = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(W[0])
[1 2 3]
>>> print(W[1])
[4 5 6]
>>> print(W[:, 0])
[1 4]
>>> print(W[:, 1])
[2 5]
>>> print(W[:, 2])
[3 6]

>>> a = np.arange(5)
>>> print(a)
[0 1 2 3 4]
>>> print(a < 3)
[ True  True  True False False]
>>> print(np.where(a < 3))
(array([0, 1, 2], dtype=int64),)

行列積

>>> W = np.array([[1, 2, 3], [4, 5, 6]])
>>> x = np.array([7, 8, 9])
>>> print(np.matmul(W, x))
[ 50 122]
>>> print(np.dot(W, x))
[ 50 122]

乱数

>>> #一様乱数(0.0~1.0の間のランダムな数値)
>>> np.random.rand()
0.39923416947813717
>>> #一様乱数(0~1の間のランダムな数値)
>>> np.random.randint(10)
5
>>> # 標準正規乱数 (平均:0.0, 標準偏差:1.0) に従う乱数を 1 件出力
>>> np.random.normal()
1.4228127988480683
>>> 配列シャッフル
>>> array=['A','B','C']
>>> print(array)
['A', 'B', 'C']
>>> np.random.shuffle(array)
>>> print(array)
['C', 'A', 'B']

Pythonカテゴリの最新記事