第一章 預(yù)備知識(shí)
一 Python基礎(chǔ)
匿名函數(shù)與map方法
1.匿名函數(shù):
my_func = lambda x: 2*x
#調(diào)用:
my_func(3)
2.map函數(shù)
#映射關(guān)系:
[(lambda x: 2*x)(i) for i in range(5)]
#map函數(shù):返回map對(duì)象,
#輸入:function(n個(gè)參數(shù)),n個(gè)iteration對(duì)象
map(lambda x: 2*x, range(5))
#通過list轉(zhuǎn)為列表:
list(map(lambda x: 2*x, range(5)))
#對(duì)于多個(gè)輸入值的函數(shù)映射,可以通過追加迭代對(duì)象實(shí)現(xiàn):
list(map(lambda x, y: str(x)+'_'+y, range(5), list('abcde')))
Python的iterator是一個(gè)惰性序列,意思是表達(dá)式和變量綁定后不會(huì)立即進(jìn)行求值,而是當(dāng)你用到其中某些元素的時(shí)候才去求某元素對(duì)的值。 惰性是指,你不主動(dòng)去遍歷它,就不會(huì)計(jì)算其中元素的值。
zip對(duì)象與enumerate方法
zip函數(shù)能夠把多個(gè)可迭代對(duì)象打包成一個(gè)元組構(gòu)成的可迭代對(duì)象,它返回了一個(gè) zip 對(duì)象,通過 tuple, list 可以得到相應(yīng)的打包結(jié)果:
L1, L2, L3 = list('abc'), list('def'), list('hij')
list(zip(L1, L2, L3)) #output: [('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
tuple(zip(L1, L2, L3)) #output:(('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j'))
#zip應(yīng)用場(chǎng)景1:循環(huán)迭代多個(gè)list
for i, j, k in zip(L1, L2, L3):
print(i, j, k)
'''
output:
a d h
b e i
c f j
'''
#zip應(yīng)用場(chǎng)景2:對(duì)兩個(gè)列表建立字典映射
dict(zip(L1,L2)) #{'a': 'd', 'b': 'e', 'c': 'f'}
解壓縮 *:
zipped = list(zip(L1, L2, L3)) #[('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
list(zip(*zipped)) # 三個(gè)元組分別對(duì)應(yīng)原來的列表 [('a', 'b', 'c'), ('d', 'e', 'f'), ('h', 'i', 'j')]
enumerate 是一種特殊的打包,它可以在迭代時(shí)綁定迭代元素的遍歷序號(hào):
for index, value in enumerate(L):
print(index, value)
二 Numpy基礎(chǔ)
np數(shù)組的構(gòu)造
array方法:
np.array([1,2,3])
一些特殊數(shù)組的生成方式
等差序列:np.linspace, np.arange
np.linspace(1,5,11) # 起始、終止(包含)、樣本個(gè)數(shù) array([1. , 1.4, 1.8, 2.2, 2.6, 3. , 3.4, 3.8, 4.2, 4.6, 5. ])np.arange(1,5,2) #起始、終止(不包含)、步長array([1, 3])
特殊矩陣 zeros, ones, eye, full
np.zeros((2,3)) # 傳入元組表示各維度大小(ones用法相同)
'''
array([[0., 0., 0.],
[0., 0., 0.]])
'''
np.eye(3) # 3*3的單位矩陣
'''
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
'''
np.eye(3, k=1) # 偏移主對(duì)角線1個(gè)單位的偽單位矩陣
'''
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]])
'''
np.full((2,3),10) #元組傳入行列數(shù),10為填充值
'''
[[10 10 10]
[10 10 10]]
'''
np.full((2,3), [1,2,3]) # 通過傳入列表填充每列的值
'''
[[1, 2, 3],
[1, 2, 3]]
'''
隨機(jī)矩陣np.random
最常用的隨機(jī)生成函數(shù)為 rand, randn, randint, choice ,它們分別表示0-1均勻分布的隨機(jī)數(shù)組、標(biāo)準(zhǔn)正態(tài)的隨機(jī)數(shù)組、隨機(jī)整數(shù)組和隨機(jī)列表抽樣:
#1. rand(a): 生成服從0-1均勻分布的a個(gè)隨機(jī)數(shù)
np.random.rand(3)
'''
[0.33475955, 0.95078732, 0.05285509]
'''
#rand(a,b) a行b列
np.random.rand(3, 3) # 注意這里傳入的不是元組,每個(gè)維度大小分開輸入
#服從區(qū)間 a 到 b 上的均勻分布可以如下生成
a, b = 5, 15
(b - a) * np.random.rand(3) + a
#2. randn(a)或randn(a,b): 生成N(0,1)的標(biāo)準(zhǔn)正態(tài)分布
np.random.randn(3)
np.random.randn(2, 2)
#對(duì)于服從方差為 σ2 均值為 μ 的一元正態(tài)分布可以如下生成:
sigma, mu = 2.5, 3
mu + np.random.randn(3) * sigma
#3. randint 可以指定生成隨機(jī)整數(shù)的最小值最大值(不包含)和維度大?。?low, high, size = 5, 15, (2,2) # 生成5到14的隨機(jī)整數(shù)
np.random.randint(low, high, size)
'''
[[ 7, 9],
[13, 7]]
'''
#4. choice 可以從給定的列表中,以一定概率和方式抽取結(jié)果,當(dāng)不指定概率時(shí)為均勻采樣,默認(rèn)抽取方式為有放回抽樣:
my_list = ['a', 'b', 'c', 'd']
np.random.choice(my_list, 2, replace=False, p=[0.1, 0.7, 0.1 ,0.1])
['b', 'd']
np.random.choice(my_list, (3,3))
'''
[['a', 'c', 'd'],
['d', 'b', 'c'],
['d', 'c', 'a']]
'''
#當(dāng)返回的元素個(gè)數(shù)與原列表相同時(shí),等價(jià)于使用 permutation 函數(shù),即打散原列表:
np.random.permutation(my_list)
#['d', 'c', 'a', 'b']
#5. 隨機(jī)種子,它能夠固定隨機(jī)數(shù)的輸出結(jié)果:(random.seed(0)作用:使得隨機(jī)數(shù)據(jù)可預(yù)測(cè),即只要seed的值一樣,后續(xù)生成的隨機(jī)數(shù)都一樣。)
np.random.seed(0)
np.random.rand() #0.5488135039273248
np.random.rand() #0.7151893663724195
np.random.seed(0)
np.random.rand() #0.5488135039273248 和之前的結(jié)果一樣
np數(shù)組的變形與合并
轉(zhuǎn)置: T
np.zeros((2,3)).T
'''
[[0., 0.],
[0., 0.],
[0., 0.]]
'''
合并操作: r_, c_
對(duì)于二維數(shù)組而言, r_ 和 c_ 分別表示上下合并和左右合并:
np.r_[np.zeros((2,3)),np.zeros((2,3))]
'''
[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]
'''
np.c_[np.zeros((2,3)),np.zeros((2,3))]
'''
[[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]]
'''
一維數(shù)組和二維數(shù)組進(jìn)行合并時(shí),應(yīng)當(dāng)把其視作列向量,在長度匹配的情況下只能夠使用左右合并的 c_ 操作:
np.c_[np.array([0,0]),np.zeros((2,3))]
'''
[[0., 0., 0., 0.],
[0., 0., 0., 0.]]
'''
維度變換: reshape
reshape 能夠幫助用戶把原數(shù)組按照新的維度重新排列。在使用時(shí)有兩種模式,分別為 C 模式和 F 模式,分別以逐行和逐列的順序進(jìn)行填充讀取。
target = np.arange(8).reshape(2,4)
'''
[[0 1 2 3]
[4 5 6 7]]
'''
#按行讀取和填充:注意target其實(shí)是沒變的
target2 = target.reshape((4,2), order='C')
'''
[[0 1]
[2 3]
[4 5]
[6 7]]
'''
# 按照列讀取和填充
target2 = target.reshape((4,2), order='F')
'''
[[0 2]
[4 6]
[1 3]
[5 7]]
'''
#特別地,由于被調(diào)用數(shù)組的大小是確定的, reshape 允許有一個(gè)維度存在空缺,此時(shí)只需填充-1即可:
target2 = target.reshape((4,-1))
'''
[[0 1]
[2 3]
[4 5]
[6 7]]
'''
#將 n*1 大小的數(shù)組轉(zhuǎn)為1維數(shù)組:
target = np.ones((3,1))
target.reshape(-1)
'''
[1., 1., 1.]
'''
np數(shù)組的切片與索引
slice
數(shù)組的切片模式支持使用 slice 類型的 start:end:step 切片,還可以直接傳入列表指定某個(gè)維度的索引進(jìn)行切片:
target = np.arange(9).reshape(3,3)
'''
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]
'''
#切片:0,2是列索引值
target[:-1, [0,2]]
'''
[[0 2]
[3 5]]
'''
np.ix_
可以利用 np.ix_ 在對(duì)應(yīng)的維度上使用布爾索引,但此時(shí)不能使用 slice 切片:
target = np.arange(33).reshape(3,-1)
target2 = target[np.ix_([1,2], [True, False, True, False, True])]
'''
[[11 13 15]
[22 24 26]]
'''
#np.ix_([a,b], [c,d]) a,b,c,d做笛卡爾集:
target2 = target[np.ix_([1,2], [0,2,4])] #效果同上
當(dāng)數(shù)組維度為1維時(shí),可以直接進(jìn)行布爾索引,而無需 np.ix_ :
new = target.reshape(-1)
target2 = new[new%2==0]
'''
[0, 2, 4, 6, 8]
'''
常用函數(shù)
假設(shè)下述函數(shù)輸入的數(shù)組都是一維的
where
where 是一種條件函數(shù),可以指定滿足條件與不滿足條件位置對(duì)應(yīng)的填充值:
a = np.array([-1,1,-1,0])
np.where(a>0, a, 5) # 對(duì)應(yīng)位置為True時(shí)填充a對(duì)應(yīng)元素,否則填充5
'''
[5 1 5 5]
'''
nonzero, argmax, argmin
這三個(gè)函數(shù)返回的都是索引, nonzero 返回非零數(shù)的索引, argmax, argmin 分別返回最大和最小數(shù)的索引:
a = np.array([-2,-5,0,1,3,-1])
np.nonzero(a) #[0, 1, 3, 4, 5]
a.argmax() #4
a.argmin() #1
any, all
any: 指當(dāng)序列至少 存在一個(gè) True 或非零元素時(shí)返回 True ,否則返回 False
all: 指當(dāng)序列元素 全為 True 或非零元素時(shí)返回 True ,否則返回 False
a = np.array([0,1])
a.any() #True
a.all() #False
cumprod, cumsum, diff
cumprod, cumsum 分別表示累乘和累加函數(shù),返回同長度的數(shù)組,diff 表示和前一個(gè)元素做差,由于第一個(gè)
元素為缺失值,因此在默認(rèn)參數(shù)情況下,返回長度是原數(shù)組減 1
a = np.array([1,2,3])
a.cumprod() #[1,2,6]
a.cumsum() #[1,3,6]
np.diff(a) #[1,1]
統(tǒng)計(jì)函數(shù)
常用的統(tǒng)計(jì)函數(shù)包括 max, min, mean, median, std, var, sum, quantile ,其中分位數(shù)計(jì)算是全局方法,因此不能通過 array.quantile 的方法調(diào)用:
target = np.arange(5)
'''
[0, 1, 2, 3, 4]
'''
target.max() #4
np.quantile(target, 0.5) # 0.5分位數(shù) 2
對(duì)于含有缺失值的數(shù)組,它們返回的結(jié)果也是缺失值;如果需要略過缺失值,必須使用 nan* 類型的函數(shù)
target = np.array([1, 2, np.nan])
target.max() #nan
np.nanmax(target) #2.0
np.nanquantile(target, 0.5) #1.5
對(duì)于協(xié)方差和相關(guān)系數(shù)分別可以利用 cov, corrcoef 如下計(jì)算:
target1 = np.array([1,3,5,9])
target2 = np.array([1,5,3,-9])
np.cov(target1, target2)
'''
[[ 11.66666667, -16.66666667],
[-16.66666667, 38.66666667]]
'''
np.corrcoef(target1, target2)
'''
[[ 1. , -0.78470603],
[-0.78470603, 1. ]]
'''
二維 Numpy 數(shù)組中統(tǒng)計(jì)函數(shù)的 axis 參數(shù),它能夠進(jìn)行某一個(gè)維度下的統(tǒng)計(jì)特征計(jì)算,當(dāng) axis=0 時(shí)結(jié)果為列的統(tǒng)計(jì)指標(biāo),當(dāng) axis=1 時(shí)結(jié)果為行的統(tǒng)計(jì)指標(biāo):
target = np.arange(1,10).reshape(3,-1)
'''
[[1 2 3]
[4 5 6]
[7 8 9]]
'''
target.sum(0) #[12 15 18]按列
target.sum(1) #[ 6 15 24]按行
廣播機(jī)制
廣播機(jī)制用于處理兩個(gè)不同維度數(shù)組之間的操作,這里只討論不超過兩維的數(shù)組廣播機(jī)制。
標(biāo)量和數(shù)組的操作
當(dāng)一個(gè)標(biāo)量和數(shù)組進(jìn)行運(yùn)算時(shí),標(biāo)量會(huì)自動(dòng)把大小擴(kuò)充為數(shù)組大小,之后進(jìn)行逐元素操作:
res = 3 * np.ones((2,2)) + 1
'''
[[4. 4.]
[4. 4.]]
'''
res = 1 / res
'''
[[0.25 0.25]
[0.25 0.25]]
'''
二維數(shù)組之間的操作
當(dāng)兩個(gè)數(shù)組維度完全一致時(shí),使用對(duì)應(yīng)元素的操作,否則會(huì)報(bào)錯(cuò),除非其中的某個(gè)數(shù)組的維度是 m × 1 或者1 × n ,那么會(huì)擴(kuò)充其具有 1 的維度為另一個(gè)數(shù)組對(duì)應(yīng)維度的大小。例如,1 × 2 數(shù)組和 3 × 2 數(shù)組做逐元素運(yùn)算時(shí)會(huì)把第一個(gè)數(shù)組擴(kuò)充為 3 × 2 ,擴(kuò)充時(shí)的對(duì)應(yīng)數(shù)值進(jìn)行賦值。但是,需要注意的是,如果第一個(gè)數(shù)組的維度是 1 × 3 ,那么由于在第二維上的大小不匹配且不為 1 ,此時(shí)報(bào)錯(cuò)。
res = np.ones((3,2))
'''
[[1., 1.],
[1., 1.],
[1., 1.]]
'''
res * np.array([[2,3]]) # 擴(kuò)充第一維度為3
'''
np的矩陣乘法是對(duì)應(yīng)位置的元素相乘,不是數(shù)學(xué)上的矩陣乘法
[[2., 3.],
[2., 3.],
[2., 3.]]
'''
res * np.array([[2],[3],[4]]) # 擴(kuò)充第二維度為2
'''
[[2., 2.],
[3., 3.],
[4., 4.]]
'''
res * np.array([[2]]) # 等價(jià)于兩次擴(kuò)充
'''
[[2., 2.],
[2., 2.],
[2., 2.]]
'''
一維數(shù)組與二維數(shù)組的操作
當(dāng)一維數(shù)組 AkAk 與二維數(shù)組 Bm,nBm,n 操作時(shí),等價(jià)于把一維數(shù)組視作 A1,kA1,k 的二維數(shù)組,使用的廣播法則與【b】中一致,當(dāng) k!=nk!=n 且 k,nk,n 都不是 11 時(shí)報(bào)錯(cuò)。
np.ones(3) + np.ones((2,3))
'''
[[2., 2., 2.],
[2., 2., 2.]]
'''
np.ones(3) + np.ones((2,1))
'''
[1, 1, 1], + [1]
[1, 1, 1] + [1]
=
2,2,2
2,2,2
'''
np.ones(1) + np.ones((2,3))
'''
[[2., 2., 2.],
[2., 2., 2.]]
'''
向量與矩陣的計(jì)算
向量?jī)?nèi)積: dot
a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b) #22
向量范數(shù)和矩陣范數(shù): np.linalg.norm
linalg=linear(線性)+algebra(代數(shù)),norm則表示范數(shù)。參數(shù):
x_norm=np.linalg.norm(x, ord=None, axis=None, keepdims=False)
x: 表示矩陣(也可以是一維)
ord:范數(shù)類型
-
axis:處理類型
? axis=1表示按行向量處理,求多個(gè)行向量的范數(shù)
? axis=0表示按列向量處理,求多個(gè)列向量的范數(shù)
? axis=None表示矩陣范數(shù)。
-
keepding:是否保持矩陣的二維特性
? True表示保持矩陣的二維特性,F(xiàn)alse相反
在矩陣范數(shù)的計(jì)算中,最重要的是 ord 參數(shù),可選值如下:
| ord | norm for matrices | norm for vectors |
|---|---|---|
| None | Frobenius norm | 2-norm |
| ‘fro’ | Frobenius norm | –矩陣A各項(xiàng)元素的絕對(duì)值平方的總和, |
| ‘nuc’ | nuclear norm | – |
| inf | max(sum(abs(x), axis=1)) | max(abs(x)) |
| -inf | min(sum(abs(x), axis=1)) | min(abs(x)) |
| 0 | – | sum(x != 0) |
| 1 | max(sum(abs(x), axis=0)) | as below |
| -1 | min(sum(abs(x), axis=0)) | as below |
| 2 | 2-norm (largest sing. value) | as below |
| -2 | smallest singular value | as below |
| other | – | sum(abs(x)ord)(1./ord) |
martix_target = np.arange(4).reshape(-1,2)
'''
[[0, 1],
[2, 3]]
'''
np.linalg.norm(martix_target, 'fro') #3.7416573867739413
np.linalg.norm(martix_target, np.inf) #5.0
np.linalg.norm(martix_target, 2) #3.702459173643833
矩陣乘法 @
a = np.arange(4).reshape(-1,2)
'''
[[0, 1],
[2, 3]]
'''
b = np.arange(-4,0).reshape(-1,2)
'''
[[-4,-3],
[-2,-1]]
'''
a@b
'''
[[ -2, -1],
[-14, -9]]
'''
三 練習(xí)
Ex1:利用列表推導(dǎo)式寫矩陣乘法
def my_func(i,j):
item = 0
for k in range(M1.shape[1]):
item += M1[i][k] * M2[k][j]
return item
res = [[my_func(i,j) for j in range(M2.shape[1])] for i in range(M1.shape[0])]
答案:
res = [[sum([M1[i][k] * M2[k][j] for k in range(M1.shape[1])]) for j in range(M2.shape[1])] for i in range(M1.shape[0])]
Ex2:更新矩陣
設(shè)矩陣 ,現(xiàn)在對(duì)
中的每一個(gè)元素進(jìn)行更新生成矩陣
,更新方法是
,例如下面的矩陣為
,則
,請(qǐng)利用
Numpy 高效實(shí)現(xiàn)。
C = [[sum(1/A[i][j] for j in range(A.shape[1]))] for i in range(A.shape[0])]
B = A * C
答案:
B = A*(1/A).sum(1).reshape(-1,1)
Ex3:卡方統(tǒng)計(jì)量
設(shè)矩陣 ,記
,定義卡方值如下:
請(qǐng)利用 Numpy 對(duì)給定的矩陣 A 計(jì)算 。
import numpy as np
np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))
B = (A.sum(1).reshape(-1,1) @ A.sum(0).reshape(1,-1))/A.sum()
kafa = ((A-B) ** 2 / B).sum()
答案:
import numpy as np
np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))
B = A.sum(0)*A.sum(1).reshape(-1, 1)/A.sum() #兩個(gè)一維向量相乘會(huì)報(bào)錯(cuò),但是加上reshape(-1,1)之后就會(huì)變成正常的矩陣乘法
kafa = ((A-B) ** 2 / B).sum()
Ex4:改進(jìn)矩陣計(jì)算的性能
設(shè)為
的矩陣,
和
分別是
和
的矩陣,
為
的第
行,
為
的第
列,下面定義
,其中
表示向量
的分量平方和
。
現(xiàn)有某人根據(jù)如下給定的樣例數(shù)據(jù)計(jì)算 的值,請(qǐng)充分利用
Numpy 中的函數(shù),基于此問題改進(jìn)這段代碼的性能。
np.random.seed(0)
m, n, p = 100, 80, 50
B = np.random.randint(0, 2, (m, p))
U = np.random.randint(0, 2, (p, n))
Z = np.random.randint(0, 2, (m, n))
def solution(B=B, U=U, Z=Z):
L_res = []
for i in range(m):
for j in range(n):
norm_value = ((B[i]-U[:,j])**2).sum()
L_res.append(norm_value*Z[i][j])
return sum(L_res)
print(solution(B, U, Z))
答案:
構(gòu)造Y矩陣:
(((B**2).sum(1).reshape(-1,1) + (U**2).sum(0) - 2*B@U)*Z).sum()
Ex5:連續(xù)整數(shù)的最大長度
輸入一個(gè)整數(shù)的 Numpy 數(shù)組,返回其中遞增連續(xù)整數(shù)子數(shù)組的最大長度。例如,輸入 [1,2,5,6,7],[5,6,7]為具有最大長度的遞增連續(xù)整數(shù)子數(shù)組,因此輸出3;輸入[3,2,1,2,3,4,6],[1,2,3,4]為具有最大長度的遞增連續(xù)整數(shù)子數(shù)組,因此輸出4。請(qǐng)充分利用 Numpy 的內(nèi)置函數(shù)完成。(提示:考慮使用 nonzero, diff 函數(shù))
f=lambdax:np.diff(np.nonzero(np.r_[1,np.diff(x)!=1,1])).max()
參考:https://datawhalechina.github.io/joyful-pandas/build/html/%E7%9B%AE%E5%BD%95/ch1.html