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)')

猜你喜欢

转载自blog.csdn.net/qq_42052864/article/details/81592077