處理 NumPy 矩陣和 ufunc
# 來源:NumPy Biginner's Guide 2e ch5
創(chuàng)建矩陣
import numpy as np
# mat 函數(shù)創(chuàng)建矩陣
# 空格分割行,分號分隔列
A = np.mat('1 2 3; 4 5 6; 7 8 9')
print "Creation from string", A
'''
Creation from string [[1 2 3]
[4 5 6]
[7 8 9]]
'''
# 矩陣轉置
print "transpose A", A.T
'''
transpose A [[1 4 7]
[2 5 8]
[3 6 9]]
'''
# 求逆(O(n^3)復雜度)
print "Inverse A", A.I
'''
Inverse A [[ -4.50359963e+15 9.00719925e+15 -4.50359963e+15]
[ 9.00719925e+15 -1.80143985e+16 9.00719925e+15]
[ -4.50359963e+15 9.00719925e+15 -4.50359963e+15]]
'''
print "Check Inverse", A * A.I
# 從 ndarray 創(chuàng)建矩陣
print "Creation from array", np.mat(np.arange(9).reshape(3, 3))
'''
Creation from array [[0 1 2]
[3 4 5]
[6 7 8]]
'''
從其它矩陣創(chuàng)建矩陣
import numpy as np
# eye 創(chuàng)建單位矩陣
A = np.eye(2)
print "A", A
'''
A [[ 1. 0.]
[ 0. 1.]]
'''
# 數(shù)乘是乘每個元素
B = 2 * A
print "B", B
'''
B [[ 2. 0.]
[ 0. 2.]]
'''
# 復合矩陣
print "Compound matrix\n", np.bmat("A B; A B")
'''
Compound matrix
[[ 1. 0. 2. 0.]
[ 0. 1. 0. 2.]
[ 1. 0. 2. 0.]
[ 0. 1. 0. 2.]]
'''
通用函數(shù)(ufunc)
import numpy as np
def ultimate_answer(a):
# 創(chuàng)建與 a 形狀相同的零數(shù)組
result = np.zeros_like(a)
# 每個值都賦為 42
result.flat = 42
return result
# 創(chuàng)建 ultimate_answer 的通用函數(shù)
ufunc = np.frompyfunc(ultimate_answer, 1, 1)
print "The answer", ufunc(np.arange(4))
# The answer [42 42 42 42]
print "The answer", ufunc(np.arange(4).reshape(2, 2))
'''
The answer [[42 42]
[[42 42]
[42 42]]
'''
通用函數(shù)的方法
import numpy as np
a = np.arange(9)
# a[0] op a[1] op ... op a[n]
print "Reduce", np.add.reduce(a)
# Reduce 36
# s[i] = a[0] + ... + a[i]
print "Accumulate", np.add.accumulate(a)
# Accumulate [ 0 1 3 6 10 15 21 28 36]
print "Reduceat", np.add.reduceat(a, [0, 5, 2, 7])
# Reduceat [10 5 20 15]
print "Reduceat step I", np.add.reduce(a[0:5])
# Reduceat step I 10
print "Reduceat step II", a[5]
# Reduceat step II 5
print "Reduceat step III", np.add.reduce(a[2:7])
# Reduceat step III 20
print "Reduceat step IV", np.add.reduce(a[7:])
# Reduceat step IV 15
# 返回 a[i] op b[j] 的矩陣
print "Outer", np.add.outer(np.arange(3), a)
'''
Outer [[ 0 1 2 3 4 5 6 7 8]
[ 1 2 3 4 5 6 7 8 9]
[ 2 3 4 5 6 7 8 9 10]]
'''
數(shù)組除法
# 導入 Py3 的除法特性
# 除法運算符變?yōu)檎娉?# 整數(shù)除以整數(shù)產生浮點
from __future__ import division
import numpy as np
a = np.array([2, 6, 5])
b = np.array([1, 2, 3])
# divide 經典除法
# divide(1, 2): 0, divide(1.0, 2): 0.5
print "Divide", np.divide(a, b), np.divide(b, a)
# Divide [2 3 1] [0 0 0]
# true_divide 真除法
# true_divide(1, 2): 0.5, true_divide(1.0, 2): 0.5
print "True Divide", np.true_divide(a, b), np.true_divide(b, a)
# True Divide [ 2. 3. 1.66666667] [ 0.5 0.33333333 0.6 ]
# floor_divide 地板除法
# floor_divide(1, 2): 0, floor_divide(1.0, 2): 0.0
print "Floor Divide", np.floor_divide(a, b), np.floor_divide(b, a)
# Floor Divide [2 3 1] [0 0 0]
c = 3.14 * b
print "Floor Divide 2", np.floor_divide(c, b), np.floor_divide(b, c)
# Floor Divide 2 [ 3. 3. 3.] [ 0. 0. 0.]
# 除法運算符已變成真除法
print "/ operator", a/b, b/a
# / operator [ 2. 3. 1.66666667] [ 0.5 0.33333333 0.6 ]
# 地板除法
print "http:// operator", a//b, b//a
# // operator [2 3 1] [0 0 0]
# 地板除法
print "http:// operator 2", c//b, b//c
# // operator 2 [ 3. 3. 3.] [ 0. 0. 0.]
求余數(shù)
import numpy as np
# 余數(shù)的符號由除數(shù)決定
# 3 除以 2 商 1 余 1
# -3 除以 2 商 -2 余 1
# 3 除以 -2 商 -2 余 -1
# -3 除以 -2 商 1 余 -1
a = np.arange(-4, 4)
print "Remainder", np.remainder(a, 2)
# Remainder [0 1 0 1 0 1 0 1]
print "Mod", np.mod(a, 2)
# Mod [0 1 0 1 0 1 0 1]
print "% operator", a % 2
# % operator [0 1 0 1 0 1 0 1]
# fmod 會將被除數(shù)和除數(shù)的符號交換
# 根據(jù)被除數(shù)來決定余數(shù)符號
print "Fmod", np.fmod(a, 2)
# Fmod [ 0 -1 0 -1 0 1 0 1]
斐波那契數(shù)
import numpy as np
F = np.matrix([[1, 1], [1, 0]])
print "F", F
'''
F [[1 1]
[1 0]]
'''
print "8th Fibonacci", (F ** 7)[0, 0]
# 8th Fibonacci 21
n = np.arange(1, 9)
# 計算黃金比例數(shù)
sqrt5 = np.sqrt(5)
phi = (1 + sqrt5)/2
# 斐波那契數(shù)的通項公式
# rint 對浮點數(shù)取整,但不改變浮點類型
fibonacci = np.rint((phi**n - (-1/phi)**n)/sqrt5)
print "Fibonacci", fibonacci
# Fibonacci [ 1. 1. 2. 3. 5. 8. 13. 21.]
利薩茹曲線
# x 和 y 都是 t 的正弦函數(shù)
# 但是頻率和初相不同
import numpy as np
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
import sys
a = float(sys.argv[1])
b = float(sys.argv[2])
t = np.linspace(-np.pi, np.pi, 201)
x = np.sin(a * t + np.pi/2)
y = np.sin(b * t)
plot(x, y)
show()
(a 為 9,b 為 8)
方波
import numpy as np
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
import sys
t = np.linspace(-np.pi, np.pi, 201)
'''
array([-3.14159265, -3.11017673, -3.0787608 , ... ,
3.11017673, 3.14159265])
'''
k = np.arange(1, float(sys.argv[1]))
k = 2 * k - 1
# 假設傳入 99:
# array([1, 3, ..., 195])
f = np.zeros_like(t)
# array([0] * 201)
for i in range(len(t)):
f[i] = np.sum(np.sin(k * t[i])/k)
f = (4 / np.pi) * f
plot(t, f)
show()
三角波
import numpy as np
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
import sys
t = np.linspace(-np.pi, np.pi, 201)
k = np.arange(1, float(sys.argv[1]))
f = np.zeros_like(t)
for i in range(len(t)):
f[i] = np.sum(np.sin(2 * np.pi * k * t[i])/k)
f = (-2 / np.pi) * f
plot(t, f, lw=1.0)
plot(t, np.abs(f), lw=2.0)
show()
位操作
import numpy as np
# 對于一個非零的數(shù),取反之后符號位會發(fā)生變化
# 異或之后符號位為 1,一定小于 0
x = np.arange(-9, 9)
y = -x
print "Sign different?", (x ^ y) < 0
print "Sign different?", np.less(np.bitwise_xor(x, y), 0)
'''
Sign different? [ True True True True True True True True True False True True
True True True True True True]
Sign different? [ True True True True True True True True True False True True
True True True True True True]
'''
# 檢查是否是 2 的冪
# 2 的冪只有一位是 1,其它都是 0
# 減一之后,右邊都是 1,其它都是 0
# 位與操作之后得 0
# 但是這里并沒有排除 0
print "Power of 2?\n", x, "\n", (x & (x - 1)) == 0
print "Power of 2?\n", x, "\n", np.equal(np.bitwise_and(x, (x - 1)), 0)
'''
Power of 2?
[-9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8]
[False False False False False False False False False True True True
False True False False False True]
Power of 2?
[-9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8]
[False False False False False False False False False True True True
False True False False False True]
'''
# m % 4 相當于 m & 0b11,只保留后兩位
print "Modulus 4\n", x, "\n", x & ((1 << 2) - 1)
print "Modulus 4\n", x, "\n", np.bitwise_and(x, np.left_shift(1, 2) - 1)
'''
Modulus 4
[-9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8]
[3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0]
Modulus 4
[-9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8]
[3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0]
'''