logo

Python マトリックス

このチュートリアルでは、Python 行列について学習します。 Python では、行列オブジェクトは多次元であるため、入れ子になったリストに似ています。 Numpy 配列を使用して行列を作成する方法を見ていきます。これに続いて、理解を深めるためにさまざまな行列演算の方法と例を見ていきます。

Python の行列とは何ですか?

Python の行列は、長方形の Numpy 配列です。この配列は 2 次元である必要があります。これには、配列の行と列に格納されたデータが含まれます。 Python 行列では、水平方向の一連の項目は「行」と呼ばれ、垂直方向の一連の項目は「列」と呼ばれます。行と列は、入れ子になったリストのように積み重ねられます。行列に r 個の行と c 個の列が含まれている場合 (r と c は正の整数)、r x c によってこの行列オブジェクトの順序が決まります。

文字列、整数、および他のデータ型のオブジェクトを行列に格納できます。データは、マトリックスの行と列のスタックに格納されます。行列は、数学や科学の計算に重要なデータ構造です。 Python では、行列オブジェクトの組み込み型が含まれていないため、リストのリストまたは入れ子になったリストを行列と見なします。

このチュートリアルでは、次の行列演算メソッドのリストを見ていきます。

  • 行列加算
  • 行列乗算
  • 行列乗算演算子
  • Numpy を使用しない行列乗算
  • 逆行列
  • 行列転置
  • 行列から配列へ

Python の行列はどのように機能するのでしょうか?

データを 2 次元配列に書き込んで行列を作成します。それは次のように行われます。

 [ 2 3 5 7 6 3 2 6 7 2 5 7 2 6 1 ] 

3 行 5 列の行列が表示されるため、その次元は 3×5 になります。整数データ型オブジェクトは、この行列のデータを構成します。最初の行である Row1 の値は (2、3、5、7、6)、Row2 の値は (3、2、6、7、2)、Row3 の値は 5、7、2、6、1 です。列、Column1 には値 (2、3、5)、Column2 には値 (3、2、7) が含まれます。

 [ 0, 0, 1 0, 1, 0 1, 0, 0 ] 

3 行 3 列の行列が表示されるため、その次元は 3×3 になります。このような等しい行と列を持つ行列は正方行列と呼ばれます。

同様に、Python を使用すると、ユーザーは m x n 次元の行列内にデータを保存できます。行列のような構造に対して、行列の加算、乗算、転置、その他の演算を実行できます。

Python での行列オブジェクトの実装は簡単ではありません。配列を使用して Python 行列を作成し、同様に使用することができます。

NumPy 配列

科学計算ソフトウェア NumPy は、堅牢な N 次元配列オブジェクトをサポートしています。 NumPy をプログラムで使用するには、NumPy をインストールすることが前提条件です。

NumPy はインストール後に使用およびインポートできます。 Numpy 配列の基本を理解すると、行列を理解するのに役立ちます。

項目の複数の次元を持つ配列は、NumPy によって提供されます。以下に図を示します。

C# リスト

コード

 # Python program to show how to create a Numpy array # Importing numpy import numpy as np # Creating a numpy array array = np.array([4, 6, 'Harry']) print(array) print('Data type of array object: ', type(array)) 

出力:

 ['4' '6' 'Harry'] Data type of array object: 

ご覧のとおり、Numpy 配列は ndarray クラスに属しています。

Numpy 配列を使用して行列を作成する例

生徒の成績の記録を作成するシナリオを考えてみましょう。 PythonプログラミングとMatrixの2科目で生徒の名前と成績を記録します。 numpy 配列を使用して 2 次元行列を作成し、それを再形成します。

コード

 # Python program to create a matrix using numpy array # Importing numpy import numpy as np # Creating the matrix record = np.array( [['Itika', 89, 91], ['Aditi', 96, 82], ['Harry', 91, 81], ['Andrew', 87, 91], ['Peter', 72, 79]]) matrix = np.reshape(record, (5,3)) print('The matrix is: 
', matrix) 

出力:

 The matrix is: [['Itika' '89' '91'] ['Aditi' '96' '82'] ['Harry' '91' '81'] ['Andrew' '87' '91'] ['Peter' '72' '79']] 

Numpy 行列メソッドを使用して行列を作成する例

numpy.matrix を使用して 2D マトリックスを作成できます。

コード

 # Python program to show how to create a matrix using the matrix method # importing numpy import numpy as np # Creating a matrix matrix = np.matrix('3,4;5,6') print(matrix) 

出力:

 [[3 4] [5 6]] 

行列の値へのアクセス

行列のインデックスを使用して、行列に格納されている要素にアクセスできます。行列に格納されたデータには、2 次元配列に使用するのと同じアプローチを使用してアクセスできます。

コード

 # Python program to access elements of a matrix # Importing numpy import numpy as np # Creating the matrix record = np.array( [['Itika', 89, 91], ['Aditi', 96, 82], ['Harry', 91, 81], ['Andrew', 87, 91], ['Peter', 72, 79]]) matrix = np.reshape(record, (5,3)) # Accessing record of Itika print( matrix[0] ) # Accessing marks in the matrix subject of Andrew print( 'Andrew's marks in Matrix subject: ', matrix[3][2] ) 

出力:

 ['Itika' '89' '91'] Andrew's marks in Matrix subject: 91 

2 次元の Numpy 配列または行列を作成するメソッド

2 次元の NumPy 配列、つまり行列を作成するには、いくつかの方法があります。行と列のエントリを提供する

整数、浮動小数点、さらには複素数を提供できます。配列メソッドの dtype 属性を使用すると、必要なデータ型を指定できます。

コード

 # Python program to show how to create a Numpy array # Importing numpy import numpy as np # Creating numpy arrays array1 = np.array([[4, 2, 7, 3], [2, 8, 5, 2]]) print('Array of data type integers: 
', array1) array2 = np.array([[1.5, 2.2, 3.1], [3, 4.4, 2]], dtype = 'float') print('Array of data type float: 
', array2) array3 = np.array([[5, 3, 6], [2, 5, 7]], dtype = 'complex') print('Array of data type complex numbers: 
', array3) 

出力:

 Array of data type integers: [[4 2 7 3] [2 8 5 2]] Array of data type float: [[1.5 2.2 3.1] [3. 4.4 2. ]] Array of data type complex numbers: [[5.+0.j 3.+0.j 6.+0.j] [2.+0.j 5.+0.j 7.+0.j]] 

0 と 1 を含む配列

コード

 # Python program to show how to create a Numpy array having zeroes and ones # Importing numpy import numpy as np # Creating numpy arrays zeores_array = np.zeros( (3, 2) ) print(zeores_array) ones_array = np.ones( (2, 4), dtype=np.int64 ) print(ones_array) 

出力:

 [[0. 0.] [0. 0.] [0. 0.]] [[1 1 1 1] [1 1 1 1]] 

ここでは、dtype を 64 ビットに指定しています。

arange() メソッドとshape() メソッドの使用

コード

 # Python program to show how to create Numpy array using arrange() and shape() methods # Importing numpy import numpy as np # Creating numpy arrays array1 = np.arange( 5 ) print(array1) array2 = np.arange( 6 ).reshape( 2, 3 ) print(array2) 

出力:

 [0 1 2 3 4] [[0 1 2] [3 4 5]] 

Python 行列演算

Python行列の加算

2 つの行列を追加し、指定された行列に対してネストされた for ループを使用します。

コード

 # Python program to add two matrices without using numpy # Creating matrices in the form of nested lists matrix1 = [[23, 43, 12], [43, 13, 55], [23, 12, 13]] matrix2 = [[4, 2, -1], [5, 4, -34], [0, -4, 3]] matrix3 = [[0,1,0], [1,0,0], [0,0,1]] matrix4 = [[0,0,0], [0,0,0], [0,0,0]] matrices_length = len(matrix1) #Adding the three matrices using nested loops for row in range(len(matrix1)): for column in range(len(matrix2[0])): matrix4[row][column] = matrix1[row][column] + matrix2[row][column] + matrix3[row][column] #Printing the final matrix print('The sum of the matrices is = ', matrix4) 

出力:

 The sum of the matrices is = [[27, 46, 11], [49, 17, 21], [23, 8, 17]] 

Python 行列の乗算

Python 行列乗算演算子

Python では、@ は乗算演算子として知られています。この演算子を使用して 2 つの行列を乗算する例を見てみましょう。

コード

 # Python program to show how to create a matrix using the matrix method. # importing numpy import numpy as np # Creating the matrices matrix1 = np.matrix('3,4;5,6') matrix2 = np.matrix('4,6;8,2') # Usng multiplication operator to multiply two matrices print(matrix1 @ matrix2) 

出力:

メインメソッドJava
 [[44 26] [68 42]] 

Numpyを使用しないPython行列乗算

2 つの行列を乗算する別の方法は、ネストされたループを使用することです。以下に例を示します。

コード

 # Python program to show how to create a matrix using the matrix method # importing numpy import numpy as np # Creating two matrices matrix1 = [[4, 6, 2], [7, 4, 8], [6, 2, 7]] matrix2 = [[4, 6, 8, 2], [6, 5, 3, 7], [7, 3, 7, 6]] # Result will be a 3x4 matrix output = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # Iterating through the rows of matrix1 for i in range(len(matrix1)): # iterating through the columns of matrix2 for j in range(len(matrix2[0])): # iterating through the rows of matrix2 for k in range(len(matrix2)): output[i][j] += matrix1[i][k] * matrix2[k][j] for row in output: print(row) 

出力:

 [66, 60, 64, 62] [108, 86, 124, 90] [85, 67, 103, 68] 

Python 逆行列

方程式を満たす未知の変数の値を取得するために方程式を解く必要がある場合、通常の数学で行うのと同様に、行列の逆数が計算されます。行列の逆行列は、元の行列と乗算すると単位行列が得られる行列です。非特異行列のみが逆行列を持つことができます。非特異行列には非ゼロの行列式があります。

コード

 # Python program to show how to calculate the inverse of a matrix # Importing the required library import numpy as np # Creating a matrix A = np.matrix('3, 4, 6; 6, 2, 7; 6, 4, 6') # Calculating the inverse of A print(np.linalg.inv(A)) 

出力:

 [[-3.33333333e-01 -7.40148683e-17 3.33333333e-01] [ 1.25000000e-01 -3.75000000e-01 3.12500000e-01] [ 2.50000000e-01 2.50000000e-01 -3.75000000e-01]] 

Python 行列転置

Numpy を使用しない Python 行列転置

行列の転置には、行と列の入れ替えが含まれます。 X'という記号が付いています。行列 X の i 行 j 列のオブジェクトを行列 X' の j 行 i 列に配置します。したがって、元の行列 X が 3x4 行列の場合、X' は 4x3 行列になります。

コード

 # Python program to find the transpose of a matrix using nested loops # Creating a matrix matrix = [[4, 6, 7, 8], [3, 7, 2, 7], [7, 3, 7, 5]] result = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] # iterating through the rows for i in range(len(matrix)): # iterating through the columns for j in range(len(matrix[0])): result[j][i] = matrix[i][j] for row in result: print(row) 

出力:

 [4, 3, 7] [6, 7, 3] [7, 2, 7] [8, 7, 5] 

Numpyを使用したPython行列転置

Numpy の matrix.transpose() メソッドを使用して、行列の転置を取得できます。

コード

 # Python program to find the transpose of a matrix # importing the required module import numpy as np # Creating a matrix using matrix method matrix = np.matrix('[5, 7, 6; 4, 2, 4]') #finding transpose using matrix.transpose method transpose = matrix.transpose() print(transpose) 

出力:

 [[5 4] [7 2] [6 4]] 

Python 行列から配列への変換

ravel 関数と flatten 関数を使用して、Python 行列を Python 配列に変換できます。

コード

 # Python program to convert a matrix to an array # importing the required module import numpy as np # Creating a matrix using numpy matrix = np.matrix('[4, 6, 7; 5, 2, 6; 6, 3, 6]') # Using ravel() function to covert matrix to array array = matrix.ravel() print(array) # Using flatten() function to covert matrix to array array = np.asarray(matrix).flatten() print(array) # Using reshape() function to covert matrix to array array = (np.asarray(matrix)).reshape(-1) print(array) 

出力:

 [[4 6 7 5 2 6 6 3 6]] [4 6 7 5 2 6 6 3 6] [4 6 7 5 2 6 6 3 6]