Python常用庫Numpy進行矩陣運算詳解
Numpy支持大量的維度數(shù)組和矩陣運算,對數(shù)組運算提供了大量的數(shù)學函數(shù)庫!
Numpy比Python列表更具優(yōu)勢,其中一個優(yōu)勢便是速度。在對大型數(shù)組執(zhí)行操作時,Numpy的速度比Python列表的速度快了好幾百。因為Numpy數(shù)組本身能節(jié)省內(nèi)存,并且Numpy在執(zhí)行算術(shù)、統(tǒng)計和線性代數(shù)運算時采用了優(yōu)化算法。
Numpy的另一個強大功能是具有可以表示向量和矩陣的多維數(shù)組數(shù)據(jù)結(jié)構(gòu)。Numpy對矩陣運算進行了優(yōu)化,使我們能夠高效地執(zhí)行線性代數(shù)運算,使其非常適合解決機器學習問題。
與Python列表相比,Numpy具有的另一個強大優(yōu)勢是具有大量優(yōu)化的內(nèi)置數(shù)學函數(shù)。這些函數(shù)使你能夠非??焖俚剡M行各種復雜的數(shù)學計算,并且用到很少代碼(無需使用復雜的循環(huán)),使程序更容易讀懂和理解。
注:在ndarray結(jié)構(gòu)中,里面元素必須是同一類型的,如果不是,會自動的向下進行。
Numpy簡單創(chuàng)建數(shù)組
a = [1, 2, 3] b = np.array(a) c = np.array([[0, 1, 2, 10], [12, 13, 100, 101], [102, 110, 112, 113]], int) print(c) print(b)
創(chuàng)建數(shù)值為1的數(shù)組
Numpy.ones(參數(shù) 1:shape,數(shù)組的形狀;參數(shù) 2:dtype, 數(shù)值類型)
array_one = np.ones([10, 10], dtype=np.int) print(array_one)
創(chuàng)建數(shù)值為0的數(shù)組
Numpy.zeros(參數(shù) 1:shape,數(shù)組的形狀;參數(shù) 2:dtype, 數(shù)值類型)
array_zero = np.zeros([10, 9], dtype=np.float) print(array_zero)
創(chuàng)建指定數(shù)值的數(shù)組
Numpy.full(參數(shù) 1:shape,數(shù)組的形狀; 參數(shù) 2:constant value,數(shù)組填充的常數(shù)值;參數(shù) 3:dtype, 數(shù)值類型)
array_full = np.full((2, 3), 5) print(array_full)
創(chuàng)建單位矩陣
Numpy.eye(參數(shù) 1:N,方陣的維度)
array_eye = np.eye(5) print(array_eye)
創(chuàng)建對角矩陣
Numpy.diag(參數(shù)1:v,主對角線數(shù)值,參數(shù) 2:k,對角線元素):K = 0表示主對角線,k>0的值選擇在主對角線之上的對角線中的元素,k<0的值選擇在主對角線之下的對角線中的元素
array_diag = np.diag([10, 20, 30, 40]) print(array_diag)
Numpy查看數(shù)組屬性
數(shù)組元素個數(shù):b.size 或 np.size()
數(shù)組形狀:b.shape 或 np.shape()
數(shù)組維度:b.ndim
數(shù)組元素類型:b.dtype
# 數(shù)組元素個數(shù):3 print(b.size) # 數(shù)組形狀:(3,) print(b.shape) # 數(shù)組維度:1 print(b.ndim) # 數(shù)組元素類型:int32 print(b.dtype)
矩陣第一維的長度:shape[0] # 行
矩陣第二維的長度:shape[1] # 列
.......
array_rand = np.random.rand(10, 10, 4) print(array_rand) print(array_rand.ndim) print(array_rand.shape[0]) print(array_rand.shape[1]) print(array_rand.shape[2])
Numpy創(chuàng)建隨機數(shù)組(np.random)
均勻分布
創(chuàng)建指定形狀的數(shù)組,數(shù)值范圍在0~1之間
array_rand = np.random.rand(10, 10, 4) print(array_rand) print(array_rand.ndim)
創(chuàng)建指定范圍內(nèi)的一個數(shù):Numpy.random.uniform(low, high, size=None)
array_uniform = np.random.uniform(0, 100, size=5) print(array_uniform)
創(chuàng)建指定范圍的一個整數(shù):Numpy.random.randint(low, high, size=None)
array_int = np.random.randint(0, 100, size=3) print(array_int) print(array_int.size)
Numpy.arange()和Numpy.linspace()函數(shù)也可以均勻分布
Numpy.arange(start, stop, step):創(chuàng)建一個秩為1的array,其中包含位于半開區(qū)間[start, stop)內(nèi)并均勻分布的值,step表示兩個相鄰值之間的差。
Numpy.linspace(start, stop, N):創(chuàng)建N個在閉區(qū)間[start, stop]內(nèi)均勻分布的值。
X = np.arange(1, 5, 2, dtype=np.int) print(X) y = np.linspace(1, 5, 3) print(y)
正態(tài)分布
創(chuàng)建給定均值、標準差、維度的正態(tài)分布:Numpy.random.normal(loc, scale, size)
# 正態(tài)生成4行5列的二位數(shù)組 array_normal = np.random.normal(loc=1.75, scale=0.1, size=[4, 5]) print(array_normal) print(array_normal.ndim)
Numpy數(shù)組操作
數(shù)組的索引
array[start : end]
array[start:]
array[:end]
布爾型索引:array[array>10 & array<20]
# 截取第0至第3行,第2至第4列(從第0行第0列算起) after_array = array_normal[:3, 2:4] print(after_array)
數(shù)組的復制
Numpy.copy(參數(shù) 1:數(shù)組):創(chuàng)建給定array的一個副本,還可當做方法用。
after_array = array_normal[:3, 2:4].copy() copy_array = np.copy(array_normal[:, 2:4])
Numpy.sort(參數(shù) 1:a,數(shù)組;參數(shù) 2:axis=0/1,0表示行1表示列):np.sort()作為函數(shù)使用時,不更改被排序的原始array;array.sort()作為方法使用時,會對原始array修改為排序后數(shù)組array
# 整體排序 np.sort(array_normal) # 僅行排序 np.sort(array_normal, axis=0) # 僅列排序 np.sort(array_normal, axis=1)
數(shù)組唯一元素
Numpy.unique(參數(shù) 1:a,數(shù)組;參數(shù) 2:return_index=True/False,新列表元素在舊列表中的位置;參數(shù) 3:return_inverse=True/False,舊列表元素在新列表中的位置;參數(shù) 4:return_counts,元素的數(shù)量;參數(shù) 5:axis=0/1,0表示行1表示列):查找array中的唯一元素。
print("提取唯一元素", np.unique(array_normal)) print("提取唯一元素", np.unique(array_normal, return_index=True)) print("提取唯一元素", np.unique(array_normal, return_counts=True)) print("提取唯一元素", np.unique(array_normal, return_index=True, return_inverse=True, axis=0))
數(shù)組的改變
數(shù)組轉(zhuǎn)置
array_normal.T
reshape():把指定的數(shù)組改變形狀,但是元素個數(shù)不變;有返回值,即不對原始多維數(shù)組進行修改
c = np.array([[[0, 1, 2], [10, 12, 13]], [[100, 101, 102], [110, 112, 113]]]) """ [[[ 0 1] [ 2 10]] [[ 12 13] [100 101]] [[102 110] [112 113]]] """ print(c.reshape(3, 2, 2)) """ [[ 0 1 2 10] [ 12 13 100 101] [102 110 112 113]] """ # 某一維指定為-1時,自動計算維度 print(c.reshape(3, -1)) """[[[ 0 1] [ 2 10] [ 12 13]] [[100 101] [102 110] [112 113]]]""" print(c.reshape(2, -1, 2))
resize():把指定的數(shù)組改變形狀,但是元素個數(shù)可變,不足補0;無返回值,即對原始多維數(shù)組進行修改
a = np.array([[[0, 1, 2], [10, 12, 13]], [[100, 101, 102], [110, 112, 113]]]) b = np.array([[[0, 1, 2], [10, 12, 13]], [[100, 101, 102], [110, 112, 113]]]) '''[[0] [1] [2]]''' a.resize((3, 1)) '''[[ 0 1 2 10 12] [ 13 100 101 102 110] [112 113 0 0 0]]''' b.resize((3, 5)) print(a) print(b)
*Numpy計算
條件運算
Numpy.where(condition, x, y):三目運算滿足condition,為x;不滿足condition,則為y
score = np.array([[80, 88], [82, 81], [84, 75], [86, 83], [75, 81]]) # 如果數(shù)值小于80,替換為0,如果大于等于80,替換為90 re_score = np.where(score < 80, 0, 90) print(re_score)
]統(tǒng)計運算
指定軸最大值:amax(參數(shù)1:數(shù)組;參數(shù)2:axis=0/1,0表示行1表示列)
# 求整個矩陣的最大值 result = np.amax(score) print(result) # 求每一列的最大值(0表示行) result = np.amax(score, axis=0) print(result) # 求每一行的最大值(1表示列) result = np.amax(score, axis=1) print(result)
指定軸最小值:amin(參數(shù)1:數(shù)組;參數(shù)2:axis=0/1,0表示行1表示列)
# 求整個矩陣的最小值 result = np.amin(score) print(result) # 求每一列的最小值(0表示行) result = np.amin(score, axis=0) print(result) # 求每一行的最小值(1表示列) result = np.amin(score, axis=1) print(result)
指定軸平均值:mean(參數(shù)1:數(shù)組;參數(shù)2:axis=0/1,0表示行1表示列;參數(shù)3:dtype,輸出數(shù)據(jù)類型)
# 求整個矩陣的平均值 result = np.mean(score, dtype=np.int) print(result) # 求每一列的平均值(0表示行) result = np.mean(score, axis=0) print(result) # 求每一行的平均值(1表示列) result = np.mean(score, axis=1) print(result)
指定軸方差:std(參數(shù)1:數(shù)組;參數(shù)2:axis=0/1,0表示行1表示列;參數(shù)3:dtype,輸出數(shù)據(jù)類型)
# 求整個矩陣的方差 result = np.std(score) print(result) # 求每一列的方差(0表示列) result = np.std(score, axis=0) print(result) # 求每一行的方差(1表示行) result = np.std(score, axis=1) print(result)
類似的,求和:Numpy.sum(),求中值:Numpy.median
數(shù)組運算
數(shù)組與數(shù)的運算(加、減、乘、除、取整、取模)
# 循環(huán)數(shù)組行和列,每一個數(shù)值都加5 score[:, :] = score[:, :]+5 print(score) # 循環(huán)數(shù)組行和列,每一個數(shù)值都減5 score[:, :] = score[:, :]-5 print(score) # 循環(huán)數(shù)組行和列,每一個數(shù)值都乘以5 score[:, :] = score[:, :]*5 print(score) # 循環(huán)數(shù)組行和列,每一個數(shù)值都除以5 score[:, :] = score[:, :]/5 print(score) # 循環(huán)數(shù)組行和列,每一個數(shù)值除以5取整 score[:, :] = score[:, :] // 5 print(score) # 循環(huán)數(shù)組行和列,每一個數(shù)值除以5取模 score[:, :] = score[:, :] % 5 print(score)
數(shù)組間運算(加、減、乘、除),前提是兩個數(shù)組的shape一樣
加:“+”或者np.add(a, b) 減:“-”或者np.subtract(a, b)
乘:“*”或者np.multiply(a, b) 除:“/”或者np.divide(a, b)
c = score + score d = score - score e = score * score # 分母數(shù)組保證每個數(shù)值不能為0 b = score / score
Numpy.intersect1d(參數(shù) 1:數(shù)組a;參數(shù) 2:數(shù)組b):查找兩個數(shù)組中的相同元素
Numpy.setdiff1d(參數(shù) 1:數(shù)組a;參數(shù) 2:數(shù)組b):查找在數(shù)組a中不在數(shù)組b中的元素
Numpy.union1d(參數(shù) 1:數(shù)組a;參數(shù) 2:數(shù)組b):查找兩個數(shù)組的并集元素
矩陣運算(一種特殊的二維數(shù)組)
計算規(guī)則
(M行,N列)*(N行,Z列)=(M行,Z列)
st_score = np.array([[80, 88], [82, 81], [84, 75], [86, 83], [75, 81]]) # 平時成績占40% 期末成績占60%, 計算結(jié)果 q = np.array([[0.4], [0.6]]) result = np.dot(st_score, q) print(result)
矩陣拼接
矩陣垂直拼接(前提兩個兩個矩陣列數(shù)相同,行數(shù)隨意):vstack(參數(shù):tuple)
v1 = [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]] v2 = [[12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [18, 19, 20, 21, 22, 23]] result = np.vstack((v1, v2)) print(result)
矩陣水平拼接(前提兩個兩個矩陣行數(shù)相同,列數(shù)隨意):hstack(參數(shù):tuple)
v1 = [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]] v2 = [[12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]] result = np.hstack((v1, v2)) print(result)
矩陣刪除:Numpy.delete(參數(shù) 1:a,數(shù)組;參數(shù) 2:elements,刪除的對象;參數(shù) 3:axis=0/1)
OriginalY = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(np.delete(OriginalY, [0, 2])) print(np.delete(OriginalY, [0, 2], axis=0)) print(np.delete(OriginalY, [0, 2], axis=1))
矩陣添加:Numpy.append(參數(shù) 1:array,數(shù)組;參數(shù) 2: elements,添加元素;參數(shù) 3: axis=0/1)
OriginalY = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # 末尾添加元素 print(np.append(OriginalY, [0, 2])) # 最后一行添加一行 print(np.append(OriginalY, [[0, 2, 11]], axis=0)) # 最后一列添加一列(注意添加元素格式) print(np.append(OriginalY, [[0], [2], [11]], axis=1))
矩陣插入:Numpy.insert(參數(shù) 1:array,數(shù)組;參數(shù) 2:index,插入位置索引;參數(shù) 3: elements,添加元素;參數(shù) 4: axis=0/1)
OriginalY = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(np.insert(OriginalY, 1, [11, 12, 10])) print(np.insert(OriginalY, 1, [[11, 12, 10]], axis=0)) # 在列索引1的位置插入(注意元素格式,跟添加格式不同) print(np.insert(OriginalY, 1, [[11, 12, 10]], axis=1))
文件加載
np.loadtxt(fname,dtype,comments='#',delimiter=None,skiprows=0,usecols=None)
fname:讀取的文件、文件名
dtype:數(shù)據(jù)類型
comments:注釋
delimiter:分隔符,默認是空格
skiprows:跳過前幾行讀取,默認是0
usecols:讀取哪些列,usecols=(1, 2, 5)讀取第1,2,5列,默認所有列
到此這篇關(guān)于Python常用庫Numpy進行矩陣運算詳解的文章就介紹到這了,更多相關(guān)Python Numpy 矩陣運算內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
構(gòu)建高效的python requests長連接池詳解
這篇文章主要介紹了構(gòu)建高效的python requests長連接池詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python的for和break循環(huán)結(jié)構(gòu)中使用else語句的技巧
平時我們把在if結(jié)構(gòu)中使用else語句當作理所當然,然而,Python強大的語法糖可以讓else語句在for和while循環(huán)中使用!下面我們就通過例子來看一下Python的for和break循環(huán)結(jié)構(gòu)中使用else語句的技巧2016-05-05