7
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

numpy & scipy 備忘録

Last updated at Posted at 2016-02-10

numpy & scipy 備忘録

概要

  • メモ程度ですが,簡単にまとめていきます
  • 随時更新していきます(たぶん)

numpy 備忘録

自己共分散行列

>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> y = np.cov(x)
>>> y
array([[ 1., -1.],
       [-1.,  1.]])
>>> y = np.cov(x,rowvar = 0)
>>> y
array([[ 2.,  0., -2.],
       [ 0.,  0.,  0.],
       [-2.,  0.,  2.]])

平均

>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
2.5
>>> np.mean(a, axis=0)
array([ 2.,  3.])
>>> np.mean(a, axis=1)
array([ 1.5,  3.5])

行列の固有値固有ベクトル

eigVals,eigVecs = np.linalg.eig(np.mat(Mat))

行列の連結

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
       [3, 4, 6]])

行列の次元変換

>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
       [2, 3]])
>>> np.transpose(x)
array([[0, 2],
       [1, 3]])
>>> x = np.ones((1, 2, 3))
>>> np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)

サイズ1の次元の削除

>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=(2,)).shape
(1, 3)

クロネッカー積

>>> np.kron([1,10,100], [5,6,7])
array([  5,   6,   7,  50,  60,  70, 500, 600, 700])
>>> np.kron([5,6,7], [1,10,100])
array([  5,  50, 500,   6,  60, 600,   7,  70, 700])

単位行列作成(identityは正方行列,eyeはオプションで色々指定できる)

>>> np.identity(3)
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> np.eye(2, dtype=int)
array([[1, 0],
       [0, 1]])
>>> np.eye(3, k=1)
array([[ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  0.]])
>>> np.eye(3, 2)
array([[ 1.,  0.],
       [ 0.,  1.],
       [ 0.,  0.]])

重複するものを除く

インデックスを返す
>>> a = np.array(['a', 'b', 'b', 'c', 'a'])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array(['a', 'b', 'c'],
       dtype='|S1')
>>> indices
array([0, 1, 3])
>>> a[indices]
array(['a', 'b', 'c'],
       dtype='|S1')
再構成用にインデックスを返す
>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> indices
array([0, 1, 4, 3, 1, 2, 1])
>>> u[indices]
array([1, 2, 6, 4, 2, 3, 2])
arrayをある範囲に指定する
>>> a = np.arrange(1,2,3,4,5)
>>> np.clip(a,a_min=2,a_max=4)
array([2,2,3,4,4])

scipy 備忘録

特異値分解

full_matrices=True:U,V正方行列,False:s正方行列

>>> U,s,V = scipy.linalg.svd(A, full_matrices=False, check_finite=False)
7
11
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
7
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?