numpy是一个数据处理模块,其底层是用C写的,可以高效的对数组和矩阵进行运算。
目录
ndarray类型
numpy中主要的类型,表示n-dim array。
ndarray对象的创建
- numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
以列表对象等创建ndarray对象。 - numpy.eye(N, M=None, k=0, dtype=float, order='C')
创建单位矩阵(2维数组). - numpy.zeros(shape, dtype = float, order = 'C')
创建指定大小的数组,数组元素为0. - numpy.arange(start, stop, step, dtype)
根据数值范围创建一维数组。参数意义与range()一样。 - numpy.random.normal(loc=0.0, scale=1.0, size=None)
创建正态分布的ndarray对象。size表示形状。
Exercise:
Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A 2 Rn×m and B 2 Rm×m, for n = 200, m = 500
首先是初始化过程:
import numpy
import time
from scipy.linalg import toeplitz
n = 200
m = 500
# numpy.random.normal(loc=0.0, scale=1.0, size=None) 返回正态分布矩阵或向量
# loc表示均值(默认为0),scale表示标准差(默认为1)
A = numpy.random.normal(size=(n, m))
c = numpy.random.normal(size = m)
r = numpy.random.normal(size = m)
r[0] = c[0]
B = toeplitz(c, r)
#numpy.eye(arg) 返回一个arg*arg的单位矩阵
#numpy.matmul() 进行矩阵乘法
# transpose()返回矩阵的转置
def fun1(r):
I = numpy.eye(m)
return numpy.matmul(A, B - I * r)
A_T = A.transpose()
print(A+A)
print(numpy.matmul(A, A_T))
print(numpy.matmul(A_T, A))
print(numpy.matmul(A, B))
print(fun1(2))
b = numpy.random.normal(size = m)
inv_B = numpy.linalg.inv(B)
x = numpy.matmul(inv_B, b)
print(x)
#numpy.linalg.norm(x, ord=None) 是计算范数的函数
#第一个参数是传入的矩阵,第二个参数代表要计算的范数
#numpy.linalg.svd(arg) 返回矩阵arg的奇异值分解的三个矩阵,
#最左边是左奇异向量,中间是一个降序的奇异值组成的向量,最右边是右奇异向量
A_F = numpy.linalg.norm(A)
print(A_F)
B_inf = numpy.linalg.norm(B, numpy.inf)
print(B_inf)
U, sigma, VT = numpy.linalg.svd(B)
print(min(sigma))
print(max(sigma))
def dominant_eigenvalue(n, e = 0.005):
Z = numpy.random.normal(size=(n, n))
#合适的x0
x = [1] * n
count = 0
begin_time = time.clock()
#开始迭代
while True:
count += 1
c = max(-min(x), max(x))
y = numpy.matmul(Z, x)
x = 1/c * y
c_next = max(-min(x), max(x))
if abs(c_next - c) < e:
break
#c_next 是主特征值, x_next 是主特征向量
using_time = time.clock() - begin_time
print("using time: " + str(using_time))
print("iteration count: " + str(count))
print(c_next)
#print(x)
for i in range(0, 3):
a = 5 * (10 ** i)
print("n = ", a)
dominant_eigenvalue(a)
运行结果如下:
#numpy.random.rand返回一个[0.0, 1.0]之间的随机浮点数
def singular_value(n, p = 0.8):
C = numpy.random.rand(n, n)
for i in range(0, n):
for j in range(0, n):
if C[i][j] < p:
C[i][j] = 1
else :
C[i][j] = 0
U, sigma, VT = numpy.linalg.svd(C)
max_singular_value = sigma[0]
return max_singular_value
for i in range(0, 3):
a = 5 * (10 ** i)
for j in range(1, 4):
p = 0.25 * j
ans = singular_value(a, p)
print("n = ", a)
print("p = ", p)
print("max singular value = ", ans)
运行结果如下:
观察可知,当n足够大时,最大奇异值等于n*p
# numpy.argmin(matrix)返回扁平化的矩阵的最小元素的下标
def nearest_neighbor(z, A):
index = numpy.argmin(abs(A-z))
row = index // len(A)
col = index % len(A)
return row, col
z = 3
row, col = nearest_neighbor(z, A)
print(A[row][col])