Pythonのマトリックス


これは、線形代数の章の一部ですData Science from Scratch by Joel Grus .

マトリックス


最初に注意すべきことはmatriceslists of lists これは型注釈で明示的です.
from typing import List

Matrix = List[List[float]]
あなたは疑問に賭けるかもしれないlist of lists とはどういうわけか違うlist of vectors 我々は、以前はvector_sum 関数.参照するには、引数を定義するために型注釈を使用しました.
ここではvector_sum 以前定義した関数
def vector_sum(vectors: List[Vector]) -> Vector:
    """Sum all corresponding elements (componentwise sum)"""
    # Check that vectors is not empty
    assert vectors, "no vectors provided!"
    # Check the vectorss are all the same size
    num_elements = len(vectors[0])
    assert all(len(v) == num_elements for v in vectors), "different sizes!"
    # the i-th element of the result is the sum of every vector[i]
    return [sum(vector[i] for vector in vectors)
            for i in range(num_elements)]

assert vector_sum([[1,2], [3,4], [5,6], [7,8]]) == [16,20]
新しい機能があります.vector_sum2 型注釈付きで定義されます
def vector_sum2(lists: List[List[float]]) -> List:
   """Sum all corresponding list (componentwise sum?)"""
   assert lists, "this list is empty!"
   # check that lists are the same size
   num_lists = len(lists[0])
   assert all(len(l) == num_lists for l in lists), "different sizes!"
   # the i-th list is the sum of every list[i]
   return [sum(l[i] for l in lists)
           for i in range(num_lists)]

assert vector_sum2([[1,2], [3,4], [5,6], [7,8]]) == [16,20]
私は、見るべきいろいろなことをしましたvector_sum and vector_sum2 異なった振る舞いをするが、

# both are functions
assert callable(vector_sum) == True
assert callable(vector_sum2) == True

# when taking the same argument, they both return a list
type(vector_sum([[1,2], [3,4], [5,6], [7,8]])) #list
type(vector_sum2([[1,2], [3,4], [5,6], [7,8]])) #list

# the same input yields the same output
vector_sum([[1,2],[3,4]])    # [4,6]
vector_sum2([[1,2],[3,4]])   # [4,6]
単純に保つために、行列の文脈では、ベクトルを行列の行と考えることができます.
たとえば、小さなデータセットを行列として表す場合、列の高さ、重さ、年齢などの変数として考えることができますそして、人としての各行:
sample_data = [[70, 170, 40],
               [65, 120, 26],
               [77, 250, 19]]
行と列の拡張によって行列の形状の関数を書くことができます.下記shape 関数は行列をとり、tuple つの整数、行の数と列の数を指定します.
from typing import Tuple

def shape(A: Matrix) -> Tuple[int, int]:
    """Returns (# of rows of A, # of columns of A)"""
    num_rows = len(A)
    num_cols = len(A[0]) if A else 0  # number of elements in first row
    return num_rows, num_cols

assert shape([[1,2,3], [4,5,6]]) == (2,3) # 2 rows, 3 columns
assert shape(sample_data) == (3,3)
実際には、特定の行または特定の列をつかむための関数を書くことができます.
Vector = List[float]

# rows
def get_row(A: Matrix, i: int) -> Vector:
    """Returns the i-th row of A (as a Vector)"""
    return A[i]  # A[i] is already the ith row

# column
def get_column(A: Matrix, i: int) -> Vector:
    """Returns the j-th column of A (as a Vector)"""
    return [A_i[j]
            for A_i in A]
さて、既存の行列の形、行、列を見つけることを超えて、行列を作成したいと思います.
from typing import Callable

def make_matrix(num_rows: int,
                num_cols: int,
                entry_fn: Callable[[int, int], float]) -> Matrix:
    """
    Returns a num_rows x num_cols matrix
    whose (i,j)-th entry is entry_fn(i, j)
    """
    return [[entry_fn(i,j)            # given i, create a list
            for j in range(num_cols)] # [entry_fn(i, 0), ...]
            for i in range(num_rows)] # create one list for each i
それから、我々は実際にmake_matrix 特殊な行列を生成する関数identity matrix :
def identity_matrix(n: int) -> Matrix:
    """Returns the n x n identity matrix"""
    return make_matrix(n, n, lambda i, j: 1 if i == j else 0)

assert identity_matrix(5) == [[1, 0, 0, 0, 0],
                              [0, 1, 0, 0, 0],
                              [0, 0, 1, 0, 0],
                              [0, 0, 0, 1, 0],
                              [0, 0, 0, 0, 1]]

概要


確かにあるother types of matrices , しかし、この章では、私たちは簡単に私たちを素直に建設を探索しています.
データを表すために行列を使用することができることを知っています.行列の列を知ることもできるので,k次元ベクトルをn次元ベクトルに写像する線形関数を表現する.
最後に、行列をバイナリ関係をマップするために使用することもできます.

フラッシュバック


Datasciensterの我々の最初の日に™ 与えられたfriendship_pairs データ
friendship_pairs = [(0,1), (0,2), (1,2), (1,3), (2,3), (3,4),
                    (4,5), (5,6), (5,7), (6,8), (7,8), (8,9)]
これらfriendship_pairs マトリックス形式で表すこともできます.
#            user 0  1  2  3  4  5  6  7  8  9
friend_matrix = [[0, 1, 1, 0, 0, 0, 0, 0, 0, 0], # user 0
                 [1, 0, 1, 1, 0, 0, 0, 0, 0, 0], # user 1
                 [1, 1, 0, 1, 0, 0, 0, 0, 0, 0], # user 2
                 [0, 1, 1, 0, 1, 0, 0, 0, 0, 0], # user 3
                 [0, 0, 0, 1, 0, 1, 0, 0, 0, 0], # user 4
                 [0, 0, 0, 0, 1, 0, 1, 1, 0, 0], # user 5
                 [0, 0, 0, 0, 0, 1, 0, 0, 1, 0], # user 6
                 [0, 0, 0, 0, 0, 1, 0, 0, 1, 0], # user 7
                 [0, 0, 0, 0, 0, 0, 1, 1, 0, 1], # user 8
                 [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]] # user 9
これにより、2人のユーザが友人であるかどうかを確認できます.
assert friend_matrix[0][2] == 1, "0 and 2 are friends"
assert friend_matrix[0][8] == 0, "0 and 8 are not friends"
そして、それぞれのユーザの友人をチェックしたいなら、
# checking the friends of user at index five (Clive)
friends_of_five = [i
                  for i, is_friend in enumerate(friend_matrix[5])
                  if is_friend]

# checking the friends of user at index zero (Hero)
friends_of_zero = [i
                   for i, is_friend in enumerate(friend_matrix[0])
                   if is_friend]

assert friends_of_five == [4,6,7]
assert friends_of_zero == [1,2]

データサイエンス、機械学習、R、パイソン、SQLとより多くのより多くの内容のために.