Numpy 學習筆記二

from __future__ import division
from numpy.random import randn
import numpy as np

arr=np.arange(10) #np.arange()支持步長爲小數,np.range()不允許
np.sqrt(arr),np.exp(arr)

x=randn(8) #從標準正態分佈中返回8個樣本值
y=randn(8)
x,y,np.maximum(x,y) #np.maximum取x,y元素級的最大值,等價np.fmax(x,y)

a=randn(7)*5
a,np.modf(a) #modf 返回小數部分和整數部分

#arrange產生等差數列
#meshgrid從座標向量返回座標矩陣,xs是矩陣的行,ys是矩陣的列
points=np.arange(-5,5,0.01)
xs,ys=np.meshgrid(points,points)
xs,ys
#將條件邏輯表達爲數組運算  result1==result2 巧用where
xarr=np.array([1.1,1.2,1.3,1.4,1.5])
yarr=np.array([2.1,2.2,2.3,2.4,2.5])
cond=np.array([True,False,True,True,False])
result1=[(x if c else y)for x,y,c in zip(xarr,yarr,cond)]
result2=np.where(cond,xarr,yarr)
result1,result2

arr=np.random.randn(5,4)
print(arr)
arr.mean(),np.mean(arr),arr.sum()

#cumsum計算軸累計和,返回由中間結果組成的數組 0代表列的計算,1代表行的計算 cumprod計算累計積
arr=np.array([[0,1,2],[3,4,5],[6,7,8]])
arr.cumsum(0),arr.cumprod(1)

arr.transpose()

arr=randn(100)
(arr > 0).sum()#計算正值的數量

#用於布爾型數組的方法
bools=np.array([True,False,True,True,False])
bools.any(),bools.all()

arr1=randn(8)
arr1.sort()

arr2=randn(5,3)
arr2.sort(1)

large_arr=randn(1000)
large_arr.sort()

large_arr[int(0.05*len(large_arr))]

排序
out31:[-1.18435555 -1.0711439  -0.96742122 -0.95486272 -0.02291184  0.15253479 0.36490602  0.55358519]       
out32:
[[-1.2165557   0.49978544  2.30722855]
 [-0.69453541 -0.65799656  0.52711461]
 [-0.20238465  0.20138149  1.66760431]
 [-1.18971958 -0.29613649  0.58725235]
 [-0.8482853  -0.78455075  1.63901916]]                                                 
 out34:-1.633230818465833 5%分位數

#唯一化以及其他的集合邏輯
names=np.array(['Bob','Joe','Will','Bob','Will','Joe','Joe'])
ints=np.array([3,3,3,2,2,1,1,4,4])
np.unique(names),np.unique(ints),sorted(set(names))

x=np.array([[1., 2., 3.], [4., 5., 6.]])
y=np.array([[6., 23.], [-1, 7], [8, 9]])
x.dot(y)#x.dot(y)相當於np.dot(x,y)  矩陣相乘 (2×3)×(3×2)=(2×2),求內積

#np.ones(3) 產生元素都爲1的一行3列的矩陣 np.random.seed()指定seed產生相同的隨機數
np.dot(x,np.ones(3)),np.random.seed(12345)

from numpy.linalg import inv,qr
X=randn(5,5)
mat=X.T.dot(X)
inv(mat)
mat.dot(inv(mat))
q,r=qr(mat)
r #特徵向量

inv:矩陣求逆

qr:計算矩陣的QR分解。把矩陣A作爲QR,q是正交的,r是上三角形

QR分解:

如果實(復)非奇異矩陣A能夠化成正交(酉)矩陣Q與實(復)非奇異上三角矩陣R的乘積,即A=QR,則稱其爲A的QR分解。
QR(正交三角)分解法是目前求一般矩陣全部特徵值的最有效並廣泛應用的方法,一般矩陣先經過正交相似變化成爲Hessenberg矩陣,然後再應用QR方法求特徵值和特徵向量。它是將矩陣分解成一個正規正交矩陣Q與上三角形矩陣R,所以稱爲QR分解法,與此正規正交矩陣的通用符號Q有關。

#numpy.random.normal(loc=0.0, scale=1.0, size=None) 正態分佈 均值,標準差,大小
samples=np.random.normal(size=(4,4))
samples

from random import normalvariate
N=1000000
get_ipython().magic(u'timeit samples = [normalvariate(0, 1) for _ in range(N)]')
get_ipython().magic(u'timeit np.random.normal(size=N)')

 

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