1.numpy.random.randn
numpy.random.randn(d0, d1, ..., dn)
d0, d1, …, dn:应该为正整数,表示维度。
如果没有参数,则返回一个值,如果有参数,则返回(d0, d1, …, dn)个值,这些值都是从标准正态分布中随机取样得到的。
For random samples from , use:
sigma * np.random.randn(...) + mu
2.numpy.random.rand
numpy.random.rand(d0, d1, ..., dn)
d0, d1, ..., dn :返回数组的尺寸,都应该是正的。
创建一个给定类型的数组,将其填充在一个均匀分布的随机样本[0, 1)中
3.numpy.reshape
Gives a new shape to an array without changing its data.
>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
[3, 4],
[5, 6]])
4.shape函数
shape函数是numpy.core.fromnumeric中的函数,它的功能是查看矩阵或者数组的维数。
>>> e = eye(3) >>> e array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> e.shape (3, 3)
建立一个4×2的矩阵c, c.shape[1] 为第一维的长度,c.shape[0] 为第二维的长度。
>>> c = array([[1,1],[1,2],[1,3],[1,4]]) >>> c.shape (4, 2) >>> c.shape[0] 4 >>> c.shape[1] 2
5.numpy.zeros
用法:zeros(shape, dtype=float, order='C')
返回:返回来一个给定形状和类型的用0填充的数组;
参数:shape:形状
dtype:数据类型,可选参数,默认numpy.float64
dtype类型:t ,位域,如t4代表4位
b,布尔值,true or false
i,整数,如i8(64位)
u,无符号整数,u8(64位)
f,浮点数,f8(64位)
c,浮点负数,
o,对象,
s,a,字符串,s24
u,unicode,u24
order:可选参数,c代表与c语言类似,行优先;F代表列优先
例子:
np.zeros(5)
array([ 0., 0., 0., 0., 0.])
s = (2,2)
np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
6.argsort()
1.先定义一个array数据
import numpy as np x=np.array([1,4,3,-1,6,9])
2.现在我们可以看看argsort()函数的具体功能是什么:
x.argsort()
输出定义为y=array([3,0,2,1,4,5])。
我们发现argsort()函数是将x中的元素从小到大排列,提取其对应的index(索引),然后输出到y。
3.由于在程序中遇到了类似于np.argsort()[num]的形式,一直看不明白,就自己去python环境自己试了下:
ps:这里的num的绝对值小于等于x中元素的个数
当num>=0时,np.argsort()[num]就可以理解为y[num];
当num<0时,np.argsort()[num]就是把数组y的元素反向输出,例如np.argsort()[-1]即输出x中最大值对应的index,np.argsort()[-2]即输出x中第二大值对应的index,依此类推。。
直观的实验才能看到效果,下面是我拿上面例子做的验证:
这是当num为负值时的输出。
这个是num>=0时的输出。
7.dot()
dot()函数是矩阵乘,而*则表示逐个元素相乘
8.random.choice()
可以从一个int数字或1维array里随机选取内容,并将选取结果放入n维array中返回。
numpy.random.choice(a, size=None, replace=True, p=None)
a : 1-D array-like or int If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n)
size : int or tuple of ints, optional
replace : boolean, optional Whether the sample is with or without replacement
p : 1-D array-like, optional The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.
9.numpy.flatnonzero():
该函数输入一个矩阵,返回扁平化后矩阵中非零元素的位置(index)
这是官方文档给出的用法,非常正规,输入一个矩阵,返回了其中非零元素的位置
>>> x = np.arange(-2, 3) >>> x array([-2, -1, 0, 1, 2]) >>> np.flatnonzero(x) array([0, 1, 3, 4])
用来返回某个特定元素的位置:
对向量元素的判断d==3返回了一个和向量等长的由0/1组成的矩阵,然后调用函数,返回的位置,就是对应要找的元素的位置。
d = np.array([1,2,3,4,4,3,5,3,6]) haa = np.flatnonzero(d == 3) print haa