Python常用庫(kù)Numpy進(jìn)行矩陣運(yùn)算詳解
Numpy支持大量的維度數(shù)組和矩陣運(yùn)算,對(duì)數(shù)組運(yùn)算提供了大量的數(shù)學(xué)函數(shù)庫(kù)!
Numpy比Python列表更具優(yōu)勢(shì),其中一個(gè)優(yōu)勢(shì)便是速度。在對(duì)大型數(shù)組執(zhí)行操作時(shí),Numpy的速度比Python列表的速度快了好幾百。因?yàn)镹umpy數(shù)組本身能節(jié)省內(nèi)存,并且Numpy在執(zhí)行算術(shù)、統(tǒng)計(jì)和線(xiàn)性代數(shù)運(yùn)算時(shí)采用了優(yōu)化算法。
Numpy的另一個(gè)強(qiáng)大功能是具有可以表示向量和矩陣的多維數(shù)組數(shù)據(jù)結(jié)構(gòu)。Numpy對(duì)矩陣運(yùn)算進(jìn)行了優(yōu)化,使我們能夠高效地執(zhí)行線(xiàn)性代數(shù)運(yùn)算,使其非常適合解決機(jī)器學(xué)習(xí)問(wèn)題。
與Python列表相比,Numpy具有的另一個(gè)強(qiáng)大優(yōu)勢(shì)是具有大量?jī)?yōu)化的內(nèi)置數(shù)學(xué)函數(shù)。這些函數(shù)使你能夠非??焖俚剡M(jìn)行各種復(fù)雜的數(shù)學(xué)計(jì)算,并且用到很少代碼(無(wú)需使用復(fù)雜的循環(huán)),使程序更容易讀懂和理解。
注:在ndarray結(jié)構(gòu)中,里面元素必須是同一類(lèi)型的,如果不是,會(huì)自動(dòng)的向下進(jìn)行。
Numpy簡(jiǎn)單創(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ù)值類(lèi)型)
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ù)值類(lèi)型)
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ù)值類(lèi)型)
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)建對(duì)角矩陣
Numpy.diag(參數(shù)1:v,主對(duì)角線(xiàn)數(shù)值,參數(shù) 2:k,對(duì)角線(xiàn)元素):K = 0表示主對(duì)角線(xiàn),k>0的值選擇在主對(duì)角線(xiàn)之上的對(duì)角線(xiàn)中的元素,k<0的值選擇在主對(duì)角線(xiàn)之下的對(duì)角線(xiàn)中的元素
array_diag = np.diag([10, 20, 30, 40]) print(array_diag)
Numpy查看數(shù)組屬性
數(shù)組元素個(gè)數(shù):b.size 或 np.size()
數(shù)組形狀:b.shape 或 np.shape()
數(shù)組維度:b.ndim
數(shù)組元素類(lèi)型:b.dtype
# 數(shù)組元素個(gè)數(shù):3 print(b.size) # 數(shù)組形狀:(3,) print(b.shape) # 數(shù)組維度:1 print(b.ndim) # 數(shù)組元素類(lèi)型:int32 print(b.dtype)
矩陣第一維的長(zhǎng)度:shape[0] # 行
矩陣第二維的長(zhǎng)度: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)建隨機(jī)數(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)的一個(gè)數(shù):Numpy.random.uniform(low, high, size=None)
array_uniform = np.random.uniform(0, 100, size=5) print(array_uniform)
創(chuàng)建指定范圍的一個(gè)整數(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)建一個(gè)秩為1的array,其中包含位于半開(kāi)區(qū)間[start, stop)內(nèi)并均勻分布的值,step表示兩個(gè)相鄰值之間的差。
Numpy.linspace(start, stop, N):創(chuàng)建N個(gè)在閉區(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)建給定均值、標(biāo)準(zhǔn)差、維度的正態(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ù)組的復(fù)制
Numpy.copy(參數(shù) 1:數(shù)組):創(chuàng)建給定array的一個(gè)副本,還可當(dāng)做方法用。
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ù)使用時(shí),不更改被排序的原始array;array.sort()作為方法使用時(shí),會(huì)對(duì)原始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ù)組改變形狀,但是元素個(gè)數(shù)不變;有返回值,即不對(duì)原始多維數(shù)組進(jìn)行修改
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時(shí),自動(dòng)計(jì)算維度 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ù)組改變形狀,但是元素個(gè)數(shù)可變,不足補(bǔ)0;無(wú)返回值,即對(duì)原始多維數(shù)組進(jìn)行修改
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計(jì)算
條件運(yùn)算
Numpy.where(condition, x, y):三目運(yùn)算滿(mǎn)足condition,為x;不滿(mǎn)足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)計(jì)運(yùn)算
指定軸最大值:amax(參數(shù)1:數(shù)組;參數(shù)2:axis=0/1,0表示行1表示列)
# 求整個(gè)矩陣的最大值 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表示列)
# 求整個(gè)矩陣的最小值 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ù)類(lèi)型)
# 求整個(gè)矩陣的平均值 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ù)類(lèi)型)
# 求整個(gè)矩陣的方差 result = np.std(score) print(result) # 求每一列的方差(0表示列) result = np.std(score, axis=0) print(result) # 求每一行的方差(1表示行) result = np.std(score, axis=1) print(result)
類(lèi)似的,求和:Numpy.sum(),求中值:Numpy.median
數(shù)組運(yùn)算
數(shù)組與數(shù)的運(yùn)算(加、減、乘、除、取整、取模)
# 循環(huán)數(shù)組行和列,每一個(gè)數(shù)值都加5 score[:, :] = score[:, :]+5 print(score) # 循環(huán)數(shù)組行和列,每一個(gè)數(shù)值都減5 score[:, :] = score[:, :]-5 print(score) # 循環(huán)數(shù)組行和列,每一個(gè)數(shù)值都乘以5 score[:, :] = score[:, :]*5 print(score) # 循環(huán)數(shù)組行和列,每一個(gè)數(shù)值都除以5 score[:, :] = score[:, :]/5 print(score) # 循環(huán)數(shù)組行和列,每一個(gè)數(shù)值除以5取整 score[:, :] = score[:, :] // 5 print(score) # 循環(huán)數(shù)組行和列,每一個(gè)數(shù)值除以5取模 score[:, :] = score[:, :] % 5 print(score)
數(shù)組間運(yùn)算(加、減、乘、除),前提是兩個(gè)數(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ù)組保證每個(gè)數(shù)值不能為0 b = score / score
Numpy.intersect1d(參數(shù) 1:數(shù)組a;參數(shù) 2:數(shù)組b):查找兩個(gè)數(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):查找兩個(gè)數(shù)組的并集元素
矩陣運(yùn)算(一種特殊的二維數(shù)組)
計(jì)算規(guī)則
(M行,N列)*(N行,Z列)=(M行,Z列)
st_score = np.array([[80, 88], [82, 81], [84, 75], [86, 83], [75, 81]]) # 平時(shí)成績(jī)占40% 期末成績(jī)占60%, 計(jì)算結(jié)果 q = np.array([[0.4], [0.6]]) result = np.dot(st_score, q) print(result)
矩陣拼接
矩陣垂直拼接(前提兩個(gè)兩個(gè)矩陣列數(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)
矩陣水平拼接(前提兩個(gè)兩個(gè)矩陣行數(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,刪除的對(duì)象;參數(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ù)類(lèi)型
comments:注釋
delimiter:分隔符,默認(rèn)是空格
skiprows:跳過(guò)前幾行讀取,默認(rèn)是0
usecols:讀取哪些列,usecols=(1, 2, 5)讀取第1,2,5列,默認(rèn)所有列
到此這篇關(guān)于Python常用庫(kù)Numpy進(jìn)行矩陣運(yùn)算詳解的文章就介紹到這了,更多相關(guān)Python Numpy 矩陣運(yùn)算內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python中矩陣創(chuàng)建和矩陣運(yùn)算方法
- python的常見(jiàn)矩陣運(yùn)算(小結(jié))
- Python矩陣常見(jiàn)運(yùn)算操作實(shí)例總結(jié)
- python如何進(jìn)行矩陣運(yùn)算
- Python操作多維數(shù)組輸出和矩陣運(yùn)算示例
- Python實(shí)現(xiàn)的矩陣轉(zhuǎn)置與矩陣相乘運(yùn)算示例
- 純python進(jìn)行矩陣的相乘運(yùn)算的方法示例
- Python中的Numpy 矩陣運(yùn)算
- python矩陣的基本運(yùn)算及各種操作
- 關(guān)于python的矩陣乘法運(yùn)算
- python矩陣基本運(yùn)算的實(shí)現(xiàn)
相關(guān)文章
python 等差數(shù)列末項(xiàng)計(jì)算方式
這篇文章主要介紹了python 等差數(shù)列末項(xiàng)計(jì)算方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05構(gòu)建高效的python requests長(zhǎng)連接池詳解
這篇文章主要介紹了構(gòu)建高效的python requests長(zhǎng)連接池詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05python中對(duì)二維列表中一維列表的調(diào)用方法
在本文里小編給大家整理的是關(guān)于python中對(duì)二維列表中一維列表的調(diào)用方法,正在學(xué)習(xí)的朋友們可以參考下。2020-06-06Python的for和break循環(huán)結(jié)構(gòu)中使用else語(yǔ)句的技巧
平時(shí)我們把在if結(jié)構(gòu)中使用else語(yǔ)句當(dāng)作理所當(dāng)然,然而,Python強(qiáng)大的語(yǔ)法糖可以讓else語(yǔ)句在for和while循環(huán)中使用!下面我們就通過(guò)例子來(lái)看一下Python的for和break循環(huán)結(jié)構(gòu)中使用else語(yǔ)句的技巧2016-05-05