掌握numpy(四)

目錄

掌握numpy(一)
掌握numpy(二)
掌握numpy(三)
掌握numpy(四)html

數組的累加(拼接)

在前面講了使用切片方法可以對數組進行切分,使用copy對切片的數組進行復制,那麼數組該如何拼接呢?數組

a1 = np.full((2,3),1)#填充數組
a2 = np.full((3,3),2)
a3 = np.full((2,3),3)
>>a3
array([[ 3.,  3.,  3.],
       [ 3.,  3.,  3.]])

vstack

豎直方向拼接數組dom

a4 = np.vstack((a1,a2,a3)) #a1,a2,a3必須有相同的列數
>> a4
[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 2.  2.  2.]
 ..., 
 [ 2.  2.  2.]
 [ 3.  3.  3.]
 [ 3.  3.  3.]]

hstack

使用hstack從水平方向拼接數組機器學習

try:
    a5 = np.hstack((a1,a2))#行數不匹配
except ValueError as e:
    >>print e
all the input array dimensions except for the concatenation axis must match exactly

a5 = np.hstack((a1,a3))#正確
>>a5
array([[ 1.,  1.,  1.,  3.,  3.,  3.],
       [ 1.,  1.,  1.,  3.,  3.,  3.]])

concatenate

vstackhstack的融合版本,經過指定axis進行選擇拼接方向ide

a6 = np.concatenate((a1,a2),axis=0)#豎直方向
>>a6
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.],
       [ 2.,  2.,  2.],
       [ 2.,  2.,  2.]])
a7 = np.concatenate((a1,a3),axis=1)
>>a7
array([[ 1.,  1.,  1.,  3.,  3.,  3.],
       [ 1.,  1.,  1.,  3.,  3.,  3.]])

stack

上面介紹的三種方法都是按照某一維度進行拼接,stack方法拼接是引入了一個新的維度學習

a8=np.stack((a1,a3))
>>a8
array([[[ 1.,  1.,  1.],#a8[0]
        [ 1.,  1.,  1.]],

       [[ 3.,  3.,  3.],#a8[1]
        [ 3.,  3.,  3.]]])
>>a8.shape
(2L, 2L, 3L)

數組的拆分(split)

前面講到了數組的拼接,相應的就是拆分。vstack->vsplithstack->hsplitui

vsplit

c = np.arange(24).reshape(4, 6)
c1,c2 = np.vsplit(c,2)
>>c1
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])

hsplit

c3,c4 = np.hsplit(c,2)
>>c3
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14],
       [18, 19, 20]])

線性代數

Numpy的二維數組經常使用來表示線性代數中的矩陣,提供了一些便捷的矩陣操做方法,代數運算的方法主要是在numpy.linalg模塊中。code

矩陣的轉置

矩陣的轉置使用transpose或者Thtm

m = np.arange(24).reshape(4, 6)
>>m
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])
>>m.T
array([[ 0,  6, 12, 18],
       [ 1,  7, 13, 19],
       [ 2,  8, 14, 20],
       [ 3,  9, 15, 21],
       [ 4, 10, 16, 22],
       [ 5, 11, 17, 23]])

上面的例子是矩陣的rank>=2的時候,若是rank=1的時候呢?blog

m1=np.arange(5)
 >>m1
array([0, 1, 2, 3, 4])
>>m1.T
array([0, 1, 2, 3, 4]) #併爲發生變化

能夠看出T對於rank=1的數組是無效的。咱們能夠經過reshape將1D數組轉化爲2D.

m1r = m1.reshape(1,5)#array([[0, 1, 2, 3, 4]])
>>m1r.T
array([[0],
       [1],
       [2],
       [3],
       [4]])

矩陣的內積運算

在作內積運算的時候,兩個矩陣是有形狀限制的,例如n1的形狀爲MxN,那麼n2的形狀必須爲NxS

n1 = np.arange(10).reshape(2, 5)
n2 = np.arange(15).reshape(5,3)
>>n1.dot(n2)
array([[ 90, 100, 110],
       [240, 275, 310]])

矩陣的逆(inverse)

inv方法是用來計算方陣的逆矩陣

import numpy.linalg as linalg
m2 =  np.array([[1,2,3],[5,7,11],[21,29,31]])
>>m2
array([[ 1,  2,  3],
       [ 5,  7, 11],
       [21, 29, 31]])
>>linalg.inv(m2)
array([[-2.31818182,  0.56818182,  0.02272727],
       [ 1.72727273, -0.72727273,  0.09090909],
       [-0.04545455,  0.29545455, -0.06818182]])

單位矩陣

單位矩陣(identity matrix)是對角線上元素都爲1的矩陣;原始矩陣與逆矩陣的內積爲單位矩陣。

>>m2.dot(linalg.inv(m))
array([[  1.00000000e+00,  -1.11022302e-16,  -6.93889390e-18],
       [ -1.33226763e-15,   1.00000000e+00,  -5.55111512e-17],
       [  2.88657986e-15,   0.00000000e+00,   1.00000000e+00]])

在前面咱們講到了使用ones來建立全爲1的矩陣,numpy也提供了單位矩陣的方法eys

>>np.eye(3)
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

矩陣的行列式

>>linalg.det(m2)
43.999999999999993#浮點數偏差

特徵值和特徵向量

特徵值(eigenvalues)和特徵向量(eigenvectors)的求解在矩陣分解時常被用到。

value,vector = linalg.eig(m2)
>>value
array([ 42.26600592,  -0.35798416,  -2.90802176])
>>vector
array([[-0.08381182, -0.76283526, -0.18913107],
       [-0.3075286 ,  0.64133975, -0.6853186 ],
       [-0.94784057, -0.08225377,  0.70325518]])

奇異矩陣分解

奇異矩陣分解(Singular Value Decomposition)被普遍的應用在推薦系統和數據降維中。

m3=np.array([[1,0,0,0,2], [0,0,3,0,0], [0,0,0,0,0], [0,2,0,0,0]])
U, S_diag, V = linalg.svd(m3)
>>S_diag
array([ 3.        ,  2.23606798,  2.        ,  0.        ])

svd將矩陣才分爲三部分,svd方法得到的S_diag是特徵向量,如今咱們須要的是Σ矩陣,因此須要構建Σ矩陣。

S = np.zeros((4, 5))
S[np.diag_indices(4)] = S_diag
>>S  # Σ
array([[ 3.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  2.23606798,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  2.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ]])

U、S和V三者的內積可以還原出原始矩陣

>>U.dot(S).dot(V)
array([[ 1.,  0.,  0.,  0.,  2.],
       [ 0.,  0.,  3.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.,  0.]])

存儲和加載

Numpy被普遍應用到機器學習領域,將一些處理後的數據持久可以有助於之後的使用。Numpy可以方便的存儲和加載二進制文件和文本格式文件。

二進制.npy格式

建立一個隨機數組並將其存儲。

a = np.random.rand(2,3)
>>a
array([[ 0.37740913,  0.45913655,  0.87659924],
       [ 0.24951215,  0.04142309,  0.57092372]])
np.save("my_array", a)

在本地就生成了my_array.npy文件,note:雖然文件名並無加後綴,NUmpy生成的文件名會自動的添加.npy後綴。咱們看一看文件內容

with open('my_array.npy','rb') as f: #須要添加.npy後綴
    content =  f.read()
>>content
'\x93NUMPY\x01\x00F\x00{\'descr\': \'<f8\', \'fortran_order\': False, \'shape\': (2L, 3L), }        \n\xbb\xa99\xfe1\xab\xea?\xa4k\x04\x14\xdc"\xda?\xe8\x95\x92\xc5:\xc4\xd6?\x98]\xed\x97\x07\x9e\xed?\xff\x9e\x97\xee\xa2\x16\xed?\xec\xd5\xc7\x8e\x8b\xaa\xcd?'

正確的加載方式是使用load

a = np.load('my_array.npy')

文本格式

上面是以二進制格式存儲,還能夠文本格式存儲。

np.savetxt("my_array.csv", a)

上面的格式可使用普通的文件讀取方式讀取,這裏就再也不贅述,下面說一下numpy的讀取方式

a = np.loadtxt("my_array.csv", delimiter=",")

zipped 格式

numpy還支持將多個ndarray持久化到同一個文件中

b = np.arange(24, dtype=np.uint8).reshape(2, 3, 4)
>>b
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]], dtype=uint8)
np.savez("my_arrays", my_a=a, my_b=b) #自動添加.npz後綴

save,二進制格式讀取讀出來的爲亂碼,使用load方法

my_arrays = np.load("my_arrays.npz")
>>my_arrays
<numpy.lib.npyio.NpzFile at 0xb2e39e8>
>>my_arrays.keys()
['my_b', 'my_a']
>>my_arrays['my_a']#字典方式讀取
array([[ 0.75760441,  0.91559205,  0.42412305],
       [ 0.49412246,  0.60609836,  0.69437913]])

至此,掌握NumPy系列文章到此結束,想要了解更多請參考官方文檔

相關文章
相關標籤/搜索