numpyの演算

numpyの演算は、二次元の配列と一次元の配列を明確に区別している。 一次元の配列はvectorとして、二次元の配列はmatrixとして、数学的に許された演算のみ可能。 例えば、[0 1 2 3 4 5][[0 1 2 3 4 5]]の演算はできない。

def printVar(var, symboltable):
    for k, v in symboltable.items():
        if id(v) == id(var):
            print("{0}:".format(k))
            print(v)
            print("")

a = np.arange(6)
row_mat = np.arange(6).reshape(1, -1)
row_mat_trans = row_mat.T
col_mat = np.arange(6).reshape(-1, 1)
col_mat_trans = col_mat.T
add_mat = row_mat + col_mat_trans
mult_mat = row_mat.dot(col_mat)

printVar(a, locals())
printVar(row_mat, locals())
printVar(row_mat_trans, locals())
printVar(col_mat, locals())
printVar(col_mat_trans, locals())
printVar(add_mat, locals())
printVar(mult_mat, locals())

# operations causing errors
# mult_mat = a.dot(row_mat)

出力は

a:
[0 1 2 3 4 5]

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

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

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

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

add_mat:
[[ 0  2  4  6  8 10]]

mult_mat:
[[55]]