NumPy

NumPy 行列の計算まとめ

スカラー演算

import numpy as np
matrix = np.array([[1, 2, 3], 
                   [4, 5, 6],
                   [7, 8, 9]], dtype = np.float) # 3x3行列

print(matrix + 1)
'''
[[ 2.  3.  4.]
 [ 5.  6.  7.]
 [ 8.  9. 10.]]
'''

print(matrix - 1)
'''
[[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]]
'''

print(matrix * 2)
'''
[[ 2.  4.  6.]
 [ 8. 10. 12.]
 [14. 16. 18.]]
'''

print(matrix / 2)
'''
[[0.5 1.  1.5]
 [2.  2.5 3. ]
 [3.5 4.  4.5]]
'''

ゼロ行列, 単位行列

import numpy as np

# ゼロ行列
print(np.zeros((3, 3)))
'''
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
'''

# 単位行列
print(np.identity(3))
'''
[[ 1. 0. 0. ]
 [ 0. 1. 0. ]
 [ 0. 0. 1. ]]
'''

# 要素が全て1の配列
print(np.ones((3, 3)))
'''
[[ 1. 1. 1. ]
 [ 1. 1. 1. ]
 [ 1. 1. 1. ]]
'''

転置行列

import numpy as np
matrix = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]],
               dtype = np.float)  # 3x3行列

print(np.transpose(matrix))
'''
[[1. 4. 7.]
 [2. 5. 8.]
 [3. 6. 9.]]
'''

逆行列

import numpy as np
matrix = np.array([[1, 2], 
                   [3, 4]], dtype = np.float) # 2x2行列

print(np.linalg.inv(matrix))
'''
[[ -2.   1.  ]
 [  1.5 -0.5 ]]
'''

要素同士の加算・減算・積・内積

import numpy as np
matrix_a = np.array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]],
                 dtype = np.float)  # 3×3行列

matrix_b = np.array([[2, 2, 2],
                  [2, 2, 2],
                  [2, 2, 2]],
                 dtype = np.float)  # 3×3行列

print(matrix_a + matrix_b)
'''
[[ 3.  4.  5.]
 [ 6.  7.  8.]
 [ 9. 10. 11.]]
'''

print(matrix_a - matrix_b)
'''
[[-1.  0.  1.]
 [ 2.  3.  4.]
 [ 5.  6.  7.]]
'''

print(matrix_a * matrix_b)
'''
[[ 2.  4.  6.]
 [ 8. 10. 12.]
 [14. 16. 18.]]
'''

print(np.dot(matrix_a, matrix_b))
'''
[[12. 12. 12.]
 [30. 30. 30.]
 [48. 48. 48.]]
'''

行・列の合計・平均, 全要素の最大・最小、合計・平均

import numpy as np
matrix = np.array([[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]],
                 dtype = np.float)  # 3×3行列

# 列ごとの合計
print(np.sum(matrix, axis=0)) # [12. 15. 18.]
# 行ごとの合計
print(np.sum(matrix, axis=1)) # [ 6. 15. 24.]

# 列ごとの平均
print(np.mean(matrix, axis=0)) # [4. 5. 6.]
# 行ごとの平均
print(np.mean(matrix, axis=1)) # [2. 5. 8.]

# 全成分の最大
print(np.max(matrix)) # 9.0
# 全成分の最小
print(np.min(matrix)) # 1.0

# 全成分の合計
print(np.sum(matrix)) # 45.0
# 全成分の平均
print(np.mean(matrix)) # 5.0