预备知识
pip安装第三方库:
pip install + 包名 #安装包
pip uninstall + 包名 #卸载包
pip freeze #查看已安装的包及其版本
pip list --outdated #查看可升级的包
pip install -U <包名> #升级指定包(包括pip本身)
python -m pip install --upgrade pip #升级pip版本
pip install pandas==1.1.5 #升级为固定的版本
一、Python基础
1. 列表推导式与条件赋值
在生成一个数字序列的时候,在Python
中可以如下写出:
# 导入需要的模块
import pandas as pd
import numpy as np
L = []
def my_func(x):
return 2*x
for i in range(5):
L.append(my_func(i))
L
[0, 2, 4, 6, 8]
# 方法2:
L1 = []
for i in range(10):
if i % 2 == 0:
L1.append(i)
L1
[0, 2, 4, 6, 8]
# 方法2-简化:
[i for i in range(10) if i % 2 == 0]
[0, 2, 4, 6, 8]
简化:[* for i in *]
。其中,第一个*
为映射函数,其输入为后面i
指代的内容,第二个*
表示迭代的对象。
# 方法3:
[my_func(i) for i in range(5)]
[0, 2, 4, 6, 8]
列表表达式还支持多层嵌套,如下面的例子中第一个for
为外层循环,第二个为内层循环:
# 初始写法:for循环嵌套
L2 = []
for m in ['a', 'b']:
for n in ['c', 'd']:
L2.append(m + '_' + n)
print(L2)
['a_c', 'a_d', 'b_c', 'b_d']
# 列表表达式写法
#第一个 for 为外层循环,第二个为内层循环
[m+'_'+n for m in ['a', 'b'] for n in ['c', 'd']]
['a_c', 'a_d', 'b_c', 'b_d']
除了列表推导式,另一个实用的语法糖是带有if
选择的条件赋值,其形式为value = a if condition else b
:
#条件赋值写法
value = 'cat' if 2>1 else 'dog'
value
'cat'
等价于如下的写法:
a, b = 'cat', 'dog'
condition = 2 > 1 # 此时为True
if condition:
value = a
else:
value = b
或者
a = 'cat'
b = 'dog'
if 2 > 1:
value = a
else:
value = b
print(value)
下面举一个例子,截断列表中超过5的元素,即超过5的用5代替,小于5的保留原来的值:
L = [1, 2, 3, 4, 5, 6, 7]
[i if i <= 5 else 5 for i in L]
[1, 2, 3, 4, 5, 5, 5]
2. 匿名函数与map方法
形式为函数名 = lambda 参数 : 返回值
func1 = lambda x: 2*x
func1(3)
6
func2 = lambda a, b: a + b
func2(1, 2)
3
匿名的目的就是要没有名字,给匿名函数赋给一个名字是没有意义的
匿名函数的参数规则、作用域关系与有名函数是一样的
匿名函数的函数体通常应该是 一个表达式,该表达式必须要有一个返回值
# 匿名函数改第一小节代码
[(lambda x: 2*x)(i) for i in range(5)]
[0, 2, 4, 6, 8]
map()
会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
语法:map(function, iterable, ...)
#上面的例子用map函数来写
list(map(lambda x: 2*x, range(5)))
[0, 2, 4, 6, 8]
#思考:如果不加list返回的是什么?
a = map(lambda x: x * 2, range(5))
a
<map at 0x24e0baa65c0>
对于多个输入值的函数映射,可以通过追加迭代对象实现:
list(map(lambda x, y: str(x)+'_'+y, range(5), list('abcde')))
['0_a', '1_b', '2_c', '3_d', '4_e']
3. zip对象与enumerate方法
zip
函数能够把多个可迭代对象打包成一个元组构成的可迭代对象,它返回了一个zip
对象,通过tuple
, list
可以得到相应的打包结果:
L1, L2, L3 = list('abc'), list('def'), list('hij')
list(zip(L1, L2, L3))
[('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
tuple(zip(L1, L2, L3))
(('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j'))
往往会在循环迭代的时候使用到zip
函数:
for i, j, k in zip(L1, L2, L3):
print(i, j, k)
a d h
b e i
c f j
enumerate()
函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
语法:enumerate(sequence, [start=0])
- sequence – 一个序列、迭代器或其他支持迭代对象。
- start – 下标起始位置。
L = list('abcd')
for index, value in enumerate(L):
print(index, value)
0 a
1 b
2 c
3 d
用zip
对象实现:
for index, value in zip(range(len(L)), L):
print(index, value)
0 a
1 b
2 c
3 d
当需要对两个列表建立字典映射时,可以利用zip
对象:
dict(zip(L1, L2))
{'a': 'd', 'b': 'e', 'c': 'f'}
既然有了压缩函数,那么Python
也提供了*
操作符和zip
联合使用来进行解压操作:
zipped = list(zip(L1, L2, L3))
zipped
[('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
list(zip(*zipped)) # 三个元组分别对应原来的列表
[('a', 'b', 'c'), ('d', 'e', 'f'), ('h', 'i', 'j')]
二、Numpy基础
1. np数组的构造
最一般的方法是通过array
来构造:
思考:array和ndarray的区别
想法:在numpy中,np.array()是一个函数,返回的对象就是ndarray。所以ndarray是一个类对象,而array是一个方法。
c = np.array([1, 2, 3])
type(c)
numpy.ndarray
下面讨论一些特殊数组的生成方式:
【a】等差序列:np.linspace
, np.arange
np.linspace语法:numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)[source]
np.arange语法:numpy.arange([start, ]stop, [step, ]dtype=None)
np.linspace(1,5,3) # 起始、终止(包含)、样本个数
array([1., 3., 5.])
np.arange(1,4,2) # 起始、终止(不包含)、步长
array([1, 3])
【b】特殊矩阵:
-
零矩阵
语法:numpy.zeros(shape, dtype=float, order='C')
-
单位矩阵
语法:numpy.eye(N,M=None,k=0,dtype=<class 'float'>,order='C)
-
np.full()
语法:numpy.full(shape, fill_value, dtype=None, order=‘C’)
# 传入元组表示各维度大小
np.zeros((2,3))
array([[0., 0., 0.],
[0., 0., 0.]])
# 3*3的单位矩阵
np.eye(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
# 偏移主对角线1个单位的伪单位矩阵
np.eye(3, k=1)
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]])
# 元组传入大小,10表示填充数值
np.full((2,3), 10)
array([[10, 10, 10],
[10, 10, 10]])
# 每行填入相同的列表
np.full((2,3), [1,2,3])
array([[1, 2, 3],
[1, 2, 3]])
【c】随机矩阵:np.random
- 生成服从区间 a 到 b 上的均匀分布
如果u是从标准均匀分布中采样的值,则如上所述,a+(b-a)u的值遵循由a和b参数化的均匀分布。
a, b = 5, 15
(b - a) * np.random.rand(3) + a
array([13.04194642, 12.4636136 , 10.58947049])
# 一般的,可以选择已有的库函数:
np.random.uniform(5, 15, 3)
array([11.26499636, 13.12311185, 6.00774156])
# 生成服从0-1均匀分布的三个随机数
np.random.rand(3)
array([0.92340835, 0.20019461, 0.40755472])
np.random.rand(3, 3) # 注意这里传入的不是元组,每个维度大小分开输入
array([[0.8012362 , 0.53154881, 0.05858554],
[0.13103034, 0.18108091, 0.30253153],
[0.00528884, 0.99402007, 0.36348797]])
- N(0,1)标准正态分布:
假设X~N(μ,σ^2),则Y=(X-μ)/σ~N(0,1)
sigma, mu = 2.5, 3
mu + np.random.randn(3) * sigma
array([ 3.63058544, 1.72694227, -0.23475296])
# 同样的,也可选择从已有函数生成
np.random.normal(3, 2.5, 3)
array([3.53517851, 5.3441269 , 3.51192744])
- 随机整数组:randint
语法:numpy.random.randint(low, high=None, size=None, dtype=int)
low, high, size = 5, 15, (2,2) # 生成5到14的随机整数
np.random.randint(low, high, size)
array([[ 7, 5],
[ 9, 12]])
- 随机列表抽样:choice
语法:numpy.random.choice(a, size=None, replace=True, p=None)
注意:p是各个结果抽取的概率,之和为1;replace为抽样方法,默认为有放回抽样
my_list = ['a', 'b', 'c', 'd']
np.random.choice(my_list, 2, replace=False, p=[0.1, 0.7, 0.1 ,0.1])
array(['b', 'd'], dtype='<U1')
np.random.choice(my_list, (3,3))
array([['c', 'b', 'd'],
['d', 'a', 'd'],
['a', 'c', 'd']], dtype='<U1')
当返回的元素个数与原列表相同时,等价于使用 permutation 函数,即打散原列表
#两种写法等价
np.random.choice(my_list, 4, replace=False)
np.random.permutation(my_list)
array(['c', 'a', 'b', 'd'], dtype='<U1')
同样的,也可选择从已有函数生成:
当返回的元素个数与原列表相同时,不放回抽样等价于使用permutation
函数,即打散原列表:
np.random.permutation(my_list)
array(['a', 'd', 'c', 'b'], dtype='<U1')
最后,需要提到的是随机种子,它能够固定随机数的输出结果:
np.random.seed(0)
np.random.rand()
0.5488135039273248
np.random.seed(0)
np.random.rand()
0.5488135039273248
2. np数组的变形与合并
【a】转置:T
np.zeros((2,3)).T
array([[0., 0.],
[0., 0.],
[0., 0.]])
【b】合并操作:r_
, c_
对于二维数组而言,r_
和c_
分别表示上下合并和左右合并:
# 上下合并
np.r_[np.zeros((2,3)),np.zeros((2,3))]
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
# 左右合并
np.c_[np.zeros((2,3)),np.zeros((2,3))]
array([[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]])
一维数组和二维数组进行合并时,应当把其视作列向量,在长度匹配的情况下只能够使用左右合并的c_
操作:
try:
np.r_[np.array([0,0]),np.zeros((2,1))]
except Exception as e:
Err_Msg = e
Err_Msg
ValueError('all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)')
np.r_[np.array([0,0]),np.zeros(2)]
array([0., 0., 0., 0.])
np.c_[np.array([0,0]),np.zeros((2,3))]
array([[0., 0., 0., 0.],
[0., 0., 0., 0.]])
问题:
np.r_[np.array([0,0]),np.zeros(2)],这不是一个1 * 2矩阵与1 * 2矩阵上下合并么,结果为什么不是2 * 2矩阵而是1 * 4矩阵?
x = np.random.randint(0,10,(2,2))
y = np.random.randint(0,10,(2,2))
#在第一维度进行拼接
print(np.concatenate([x,y]).shape)
print(np.vstack([x,y]).shape)
print(np.r_[x,y].shape)
#在第二维度进行拼接
print(np.concatenate([x,y],axis=1).shape)
print(np.c_[x,y].shape)
print(np.hstack([x,y]).shape)
一维数组和二维数组进行合并时,应当把其视作列向量,在长度匹配的情况下只能够使用左右合并的 c_ 操作
1 * 2
矩阵和1 * 2
矩阵上下合并为1 * 4
矩阵
2 * 1
矩阵和2 * 3
矩阵左右合并为2 * 4
矩阵
1 * 2
矩阵和2 * 1
矩阵无法进行上下合并
【c】维度变换:reshape
reshape
能够帮助用户把原数组按照新的维度重新排列。在使用时有两种模式,分别为C
模式和F
模式,分别以逐行和逐列的顺序进行填充读取。
target = np.arange(8).reshape(2,4)
target
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
# C 模式,按照列读取和填充
target.reshape((4,2), order='C')
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
# F 模式,按照列读取和填充
target.reshape((4,2), order='F')
array([[0, 2],
[4, 6],
[1, 3],
[5, 7]])
特别地,由于被调用数组的大小是确定的,reshape
允许有一个维度存在空缺,此时只需填充-1即可:
target.reshape((4,-1))
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
下面将n*1
大小的数组转为1维数组的操作是经常使用的:
target = np.ones((3,1))
target
array([[1.],
[1.],
[1.]])
target.reshape(-1)
array([1., 1., 1.])
3. np数组的切片与索引
数组的切片模式支持使用slice
类型的start:end:step
切片(不包含末尾)还可以直接传入列表指定某个维度的索引进行切片:
target = np.arange(9).reshape(3,3)
target
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
# 除去最后一行,即前两行,取第一个和第三个元素
target[:-1, [0,2]]
array([[0, 2],
[3, 5]])
此外,还可以利用np.ix_
在对应的维度上使用布尔索引,但此时不能使用slice
切片:
# 取第一行和第三行中,第一个和第三个元素
target[np.ix_([True, False, True], [True, False, True])]
array([[0, 2],
[6, 8]])
target[np.ix_([1,2], [True, False, True])]
array([[3, 5],
[6, 8]])
当数组维度为1维时,可以直接进行布尔索引,而无需np.ix_
:
new = target.reshape(-1)
new[new%2==0]
array([0, 2, 4, 6, 8])
4. 常用函数
为了简单起见,这里假设下述函数输入的数组都是一维的。
【a】where
语法:numpy.where(condition[, x, y])
where
是一种条件函数,类似于excel的if函数,可以指定满足条件与不满足条件位置对应的填充值:
a = np.array([-1,1,-1,0])
np.where(a>0, a, 5) # 对应位置为True时填充a对应元素,否则填充5
array([5, 1, 5, 5])
【b】
返回索引的三个函数:
nonzero
:返回非零数的索引
argmax
:返回最大的索引
argmin
:最小数的索引
a = np.array([-2,-5,0,1,3,-1])
np.nonzero(a)
# 因为第3个元素为0,所以索引数字不返回2
(array([0, 1, 3, 4, 5], dtype=int64),)
a.argmax()
# 最大数字是第5个,所以返回索引为4
4
a.argmin()
# 最小数字为第2个,所以返回索引为1
1
【c】any
, all
any
指当序列至少 存在一个 True
或非零元素时返回True
,否则返回False
all
指当序列元素 全为 True
或非零元素时返回True
,否则返回False
a = np.array([0,1])
a.any()
True
a.all()
False
【d】
cumprod
:累乘函数
cumsum
:累加函数,返回同长度的数组
diff
:表示和前一个元素做差,由于第一个元素为缺失值,因此在默认参数情况下,返回长度是原数组减1。
a = np.array([1,2,3])
a.cumprod()
array([1, 2, 6], dtype=int32)
a.cumsum()
array([1, 3, 6], dtype=int32)
np.diff(a)
array([1, 1])
【e】 统计函数
常用的统计函数包括max, min, mean, median, std, var, sum, quantile
,其中分位数计算是全局方法,因此不能通过array.quantile
的方法调用:
target = np.arange(5)
target
array([0, 1, 2, 3, 4])
target.max()
4
np.quantile(target, 0.5) # 0.5分位数
2.0
但是对于含有缺失值的数组,它们返回的结果也是缺失值,如果需要略过缺失值,必须使用nan*
类型的函数,上述的几个统计函数都有对应的nan*
函数。
target = np.array([1, 2, np.nan])
target
array([ 1., 2., nan])
target.max()
nan
np.nanmax(target)
2.0
np.nanquantile(target, 0.5)
1.5
对于协方差和相关系数分别可以利用cov, corrcoef
如下计算:
target1 = np.array([1,3,5,9])
target2 = np.array([1,5,3,-9])
np.cov(target1, target2)
array([[ 11.66666667, -16.66666667],
[-16.66666667, 38.66666667]])
np.corrcoef(target1, target2)
array([[ 1. , -0.78470603],
[-0.78470603, 1. ]])
最后,需要说明二维Numpy
数组中统计函数的axis
参数,它能够进行某一个维度下的统计特征计算,当axis=0
时结果为列的统计指标,当axis=1
时结果为行的统计指标:
target = np.arange(1,10).reshape(3,-1)
target
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
target.sum(0)# 0 =(axis=0)
array([12, 15, 18])
target.sum(1)
array([ 6, 15, 24])
5. 广播机制
广播机制用于处理两个不同维度数组之间的操作,这里只讨论不超过两维的数组广播机制。
【a】标量和数组的操作
当一个标量和数组进行运算时,标量会自动把大小扩充为数组大小,之后进行逐元素操作:
res = 3 * np.ones((2,2)) + 1
res
array([[4., 4.],
[4., 4.]])
res = 1 / res
res
array([[0.25, 0.25],
[0.25, 0.25]])
【b】二维数组之间的操作
当两个数组维度完全一致时,使用对应元素的操作,否则会报错,除非其中的某个数组的维度是 m × 1 m×1 m×1或者 1 × n 1×n 1×n,那么会扩充其具有 1 1 1的维度为另一个数组对应维度的大小。例如, 1 × 2 1×2 1×2数组和 3 × 2 3×2 3×2数组做逐元素运算时会把第一个数组扩充为 3 × 2 3×2 3×2,扩充时的对应数值进行赋值。但是,需要注意的是,如果第一个数组的维度是 1 × 3 1×3 1×3,那么由于在第二维上的大小不匹配且不为 1 1 1,此时报错。
res = np.ones((3,2))
res
array([[1., 1.],
[1., 1.],
[1., 1.]])
res * np.array([[2,3]]) # 第二个数组扩充第一维度为3
array([[2., 3.],
[2., 3.],
[2., 3.]])
res * np.array([[2],[3],[4]]) # 第二个数组扩充第二维度为2
array([[2., 2.],
[3., 3.],
[4., 4.]])
res * np.array([[2]]) # 等价于两次扩充,第二个数组两个维度分别扩充为3和2
array([[2., 2.],
[2., 2.],
[2., 2.]])
【c】一维数组与二维数组的操作
当一维数组 A k A_k Ak与二维数组 B m , n B_{m,n} Bm,n操作时,等价于把一维数组视作 A 1 , k A_{1,k} A1,k的二维数组,使用的广播法则与【b】中一致,当 k ! = n k!=n k!=n且 k , n k,n k,n都不是 1 1 1时报错。
np.ones(3) + np.ones((2,3))
array([[2., 2., 2.],
[2., 2., 2.]])
np.ones(3) + np.ones((2,1))
array([[2., 2., 2.],
[2., 2., 2.]])
np.ones(1) + np.ones((2,3))
array([[2., 2., 2.],
[2., 2., 2.]])
6. 向量与矩阵的计算
【a】向量内积:dot
a ⋅ b = ∑ i a i b i \rm \mathbf{a}\cdot\mathbf{b} = \sum_ia_ib_i a⋅b=i∑aibi
a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b)
22
【b】向量范数和矩阵范数:np.linalg.norm
在矩阵范数的计算中,最重要的是ord
参数,可选值如下:
ord | norm for matrices | norm for vectors |
---|---|---|
None | Frobenius norm | 2-norm |
‘fro’ | Frobenius norm | / |
‘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) |
matrix_target = np.arange(4).reshape(-1,2)
matrix_target
array([[0, 1],
[2, 3]])
np.linalg.norm(matrix_target, 'fro')
3.7416573867739413
np.linalg.norm(matrix_target, np.inf)
5.0
np.linalg.norm(matrix_target, 2)
3.702459173643833
vector_target = np.arange(4)
vector_target
array([0, 1, 2, 3])
np.linalg.norm(vector_target, np.inf)
3.0
np.linalg.norm(vector_target, 2)
3.7416573867739413
np.linalg.norm(vector_target, 3)
3.3019272488946263
【c】矩阵乘法:@
[ A m × p B p × n ] i j = ∑ k = 1 p A i k B k j \rm [\mathbf{A}_{m\times p}\mathbf{B}_{p\times n}]_{ij} = \sum_{k=1}^p\mathbf{A}_{ik}\mathbf{B}_{kj} [Am×pBp×n]ij=k=1∑pAikBkj
a = np.arange(4).reshape(-1,2)
a
array([[0, 1],
[2, 3]])
b = np.arange(-4,0).reshape(-1,2)
b
array([[-4, -3],
[-2, -1]])
a@b
array([[ -2, -1],
[-14, -9]])
三、练习
Ex1:利用列表推导式写矩阵乘法
一般的矩阵乘法根据公式,可以由三重循环写出,请将其改写为列表推导式的形式。
M1 = np.random.rand(2,3)
M2 = np.random.rand(3,4)
res = np.empty((M1.shape[0],M2.shape[1]))
for i in range(M1.shape[0]):
for j in range(M2.shape[1]):
item = 0
for k in range(M1.shape[1]):
item += M1[i][k] * M2[k][j]
res[i][j] = item
((M1@M2 - res) < 1e-15).all() # 排除数值误差
True
# 或者
M1 = np.random.rand(2,3)
M2 = np.random.rand(3,4)
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])]
((M1@M2 - res) < 1e-15).all()
True
Ex2:更新矩阵
设矩阵
A
m
×
n
A_{m×n}
Am×n ,现在对
A
A
A 中的每一个元素进行更新生成矩阵
B
B
B ,更新方法是
B
i
j
=
A
i
j
∑
k
=
1
n
1
A
i
k
B_{ij}=A_{ij}\sum_{k=1}^n\frac{1}{A_{ik}}
Bij=Aij∑k=1nAik1 ,例如下面的矩阵为
A
A
A ,则
B
2
,
2
=
5
×
(
1
4
+
1
5
+
1
6
)
=
37
12
B_{2,2}=5\times(\frac{1}{4}+\frac{1}{5}+\frac{1}{6})=\frac{37}{12}
B2,2=5×(41+51+61)=1237 ,请利用 Numpy
高效实现。
KaTeX parse error: No such environment: split at position 7: \begin{̲s̲p̲l̲i̲t̲}̲A=\left[ \begin…
A = np.arange(1,10).reshape(3,-1)
B = A*(1/A).sum(1).reshape(-1,1)
B
array([[1.83333333, 3.66666667, 5.5 ],
[2.46666667, 3.08333333, 3.7 ],
[2.65277778, 3.03174603, 3.41071429]])
Ex3:卡方统计量
设矩阵
A
m
×
n
A_{m\times n}
Am×n,记
B
i
j
=
(
∑
i
=
1
m
A
i
j
)
×
(
∑
j
=
1
n
A
i
j
)
∑
i
=
1
m
∑
j
=
1
n
A
i
j
B_{ij} = \frac{(\sum_{i=1}^mA_{ij})\times (\sum_{j=1}^nA_{ij})}{\sum_{i=1}^m\sum_{j=1}^nA_{ij}}
Bij=∑i=1m∑j=1nAij(∑i=1mAij)×(∑j=1nAij),定义卡方值如下:
χ
2
=
∑
i
=
1
m
∑
j
=
1
n
(
A
i
j
−
B
i
j
)
2
B
i
j
\chi^2 = \sum_{i=1}^m\sum_{j=1}^n\frac{(A_{ij}-B_{ij})^2}{B_{ij}}
χ2=i=1∑mj=1∑nBij(Aij−Bij)2
请利用Numpy
对给定的矩阵
A
A
A计算
χ
2
\chi^2
χ2
np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))
B = A.sum(0)*A.sum(1).reshape(-1, 1)/A.sum()
res = ((A-B)**2/B).sum()
res
11.842696601945802
Ex4:改进矩阵计算的性能
设 Z Z Z为 m × n m×n m×n的矩阵, B B B和 U U U分别是 m × p m×p m×p和 p × n p×n p×n的矩阵, B i B_i Bi为 B B B的第 i i i行, U j U_j Uj为 U U U的第 j j j列,下面定义 R = ∑ i = 1 m ∑ j = 1 n ∥ B i − U j ∥ 2 2 Z i j \displaystyle R=\sum_{i=1}^m\sum_{j=1}^n\|B_i-U_j\|_2^2Z_{ij} R=i=1∑mj=1∑n∥Bi−Uj∥22Zij,其中 ∥ a ∥ 2 2 \|\mathbf{a}\|_2^2 ∥a∥22表示向量 a a a的分量平方和 ∑ i a i 2 \sum_i a_i^2 ∑iai2。
现有某人根据如下给定的样例数据计算
R
R
R的值,请充分利用Numpy
中的函数,基于此问题改进这段代码的性能。
# 原方法:
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)
solution(B, U, Z)
100566
改进方法:
令
Y
i
j
=
∥
B
i
−
U
j
∥
2
2
Y_{ij} = \|B_i-U_j\|_2^2
Yij=∥Bi−Uj∥22,则
R
=
∑
i
=
1
m
∑
j
=
1
n
Y
i
j
Z
i
j
\displaystyle R=\sum_{i=1}^m\sum_{j=1}^n Y_{ij}Z_{ij}
R=i=1∑mj=1∑nYijZij,这在Numpy
中可以用逐元素的乘法后求和实现,因此问题转化为了如何构造Y
矩阵。
KaTeX parse error: No such environment: split at position 8: \begin{̲s̲p̲l̲i̲t̲}̲Y_{ij} &= \|B_i…
从上式可以看出,第一第二项分别为 B B B的行平方和与 U U U的列平方和,第三项是两倍的内积。因此, Y Y Y矩阵可以写为三个部分,第一个部分是 m × n m×n m×n的全 1 1 1矩阵每行乘以 B B B对应行的行平方和,第二个部分是相同大小的全 1 1 1矩阵每列乘以 U U U对应列的列平方和,第三个部分恰为 B B B矩阵与 U U U矩阵乘积的两倍。从而结果如下:
(((B**2).sum(1).reshape(-1,1) + (U**2).sum(0) - 2*B@U)*Z).sum()
100566
对比它们的性能:
%timeit -n 30 solution(B, U, Z)
30 loops, best of 3: 78.6 ms per loop
%timeit -n 30 ((np.ones((m,n))*(B**2).sum(1).reshape(-1,1) + np.ones((m,n))*(U**2).sum(0) - 2*B@U)*Z).sum()
30 loops, best of 3: 431 µs per loop
Ex5:连续整数的最大长度
输入一个整数的Numpy
数组,返回其中严格递增连续整数子数组的最大长度,正向是指递增方向。例如,输入[1,2,5,6,7],[5,6,7]为具有最大长度的连续整数子数组,因此输出3;输入[3,2,1,2,3,4,6],[1,2,3,4]为具有最大长度的连续整数子数组,因此输出4。请充分利用Numpy
的内置函数完成。(提示:考虑使用nonzero, diff
函数)
f = lambda x:np.diff(np.nonzero(np.r_[1,np.diff(x)!=1,1])).max()
f([1,2,5,6,7])
f([3,2,1,2,3,4,6])
4