python學習第11周:python numpy

numpy是一個數據處理模塊,其底層是用C寫的,可以高效的對數組和矩陣進行運算。

目錄

ndarray類型

ndarray對象的創建

Exercise:


ndarray類型

numpy中主要的類型,表示n-dim array。

 

ndarray對象的創建

 

  1. numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
    以列表對象等創建ndarray對象。
  2. numpy.eye(N, M=None, k=0, dtype=float, order='C')
    創建單位矩陣(2維數組).
  3. numpy.zeros(shape, dtype = float, order = 'C')
    創建指定大小的數組,數組元素爲0.
  4. numpy.arange(start, stop, step, dtype) 
    根據數值範圍創建一維數組。參數意義與range()一樣。
  5. 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])

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章