Ex1:利用列表推导式写矩阵乘法
[[M1[i].dot(M2[:,j]) for j in range(M2.shape[1])] for i in range(M1.shape[0])]
[[sum(M1[i][p]*M2[p][j] for p in range(M1.shape[1]))for j in range(M2.shape[1])] for i in range(M1.shape[0])]
注意:
列表推导式
Ex2:更新矩阵¶
A=np.arange(1,10,1).reshape([3,-1])
print(A)
B=np.sum(1/A,axis=1)
# print(B)
B = A*B.reshape([3,1])
print(B)
A = np.arange(1,10).reshape(3,-1)
B = A*(1/A).sum(1).reshape(-1,1)#注意sum的用法
Ex3:卡方统计量
np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))
B = A.sum(0).reshape(1,5)*A.sum(1).reshape(8,1)/sum(A)
print((((A-B)**2)/B).sum())
这里犯了一个错误:
print(A.sum()) # 577
print(sum(A)) #[120 111 129 116 101]
print(np.sum(A)) #577
要注意三个求和函数的不同
改正:
np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))
B = A.sum(0).reshape(1,5)*A.sum(1).reshape(8,1)/A.sum()
print((((A-B)**2)/B).sum())
Ex4:改进矩阵计算的性能
B1 = (B**2).sum(1)
U1 = (U**2).sum(0)
BU1 = 2 * B.dot(U)
# print(BU1.shape)
# print(U1.shape)
# print(B1.shape)
temp = B1.reshape(-1,1)+U1.reshape(1,-1)-BU1
re = temp*Z
print(np.sum(re))
(((B**2).sum(1).reshape(-1,1) + (U**2).sum(0) - 2*B@U)*Z).sum()
tem = [[((B[i]-U[:,j])**2).sum() for j in range(n)] for i in range(m) ]
tem = np.array(tem)
re = tem * Z
print(re.sum())
了解 %timeit -n 30
%timeit -n 30 solution(B, U, Z)
Ex5:连续整数的最大长度
要学习
f = lambda x:np.diff(np.nonzero(np.r_[1,np.diff(x)!=1,1])).max()