# numpy习题

#https://blog.csdn.net/u010156024/article/details/50419338
import numpy as np
import scipy.linalg
import random
from sklearn import random_projection
import time
#generate a matrix with random Gaussian entries
A = np.random.normal(0, 1, size=(200, 500))

#generate a Toeplitz matrix B
r = []
while len(r) != 500:
r.append(random.randint(0, 100))
B = scipy.linalg.toeplitz(r)

#exercise one
print((A+A).shape)
print(np.dot(A, A.T).shape)
print(np.dot(A.T, A).shape)
print(np.dot(A, B).shape)
#A(B-lamta*I)
I = np.eye(500)
def f(lamta):
tmp = B - lamta * I
return np.dot(A, tmp)
# print(f(0.5).shape)

#exercise two
b = np.random.randint(0, 100, size = (500, 1))
print(np.dot(scipy.linalg.inv(B), b).shape)

#exercise three
#https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html
print(np.linalg.norm(A))
print(np.linalg.norm(B, np.inf))
#largest singular values of B
print(np.linalg.norm(B, 2))
#smallest singular values of B
print(np.linalg.norm(B, -2))

#exercise four
#https://blogs.sas.com/content/iml/2012/05/09/the-power-method.html
#generate Z
r = []
while len(r) != 200:
r.append(random.randint(0, 100))
Z = scipy.linalg.toeplitz(r)
t0 = time.clock()
print("eigenvectors:", np.linalg.eigh(Z))
print(time.clock()-t0)

#exercise five
#http://fa.bianp.net/blog/2012/singular-value-decomposition-in-scipy/
n = 5
p = 0.5
C = np.random.ranf(size = (n, n))
i = 0;j = 0
while i < n:
while j < n:
if C[i][j] < p:
C[i][j] = 1
else:
C[i][j] = 0
j += 1
i += 1
j = 0
print(C)
print(scipy.linalg.svd(C))
print(scipy.sparse.linalg.svds(C, 1))

#exercise six
#https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html#numpy.argmin
A_array = np.random.randint(0, 100, size = (5, 5))
z = 40
A_new = np.abs(A_array-z)
ind = np.unravel_index(np.argmin(A_new, axis = None), A_new.shape)
# print(A_array[k/5][k%5])
print(A_array[ind])



• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120