Numpy技巧

np.argsort(list)

argsort函数返回的是数组值从小到大的索引值

np.log()和np.exp()

1
2
3
4
5
a = np.log(10)
2.30258509299
b = np.exp(a)
10.0

np.bincount()

在非负整数数组中计算每个值的次数。

1
2
3
4
5
6
7
8
9
10
11
x = np.array([0, 1, 1, 3, 2, 1, 7])
# 索引0出现了1次,索引1出现了3次......索引5出现了0次......
np.bincount(x)
#因此,输出结果为:array([1, 3, 1, 1, 0, 0, 0, 1])
x = np.array([7, 6, 2, 1, 4])
# 索引0出现了0次,索引1出现了1次......索引5出现了0次......
np.bincount(x)
#输出结果为:array([0, 1, 1, 0, 1, 0, 1, 1])

如果minlength被指定,那么输出数组中bin的数量至少为它指定的数(如果必要的话,bin的数量会更大,这取决于x)

1
2
3
4
5
6
7
8
9
10
11
# 我们可以看到x中最大的数为3,因此bin的数量为4,那么它的索引值为0->3
x = np.array([3, 2, 1, 3, 1])
# 本来bin的数量为4,现在我们指定了参数为7,因此现在bin的数量为7,所以现在它的索引值为0->6
np.bincount(x, minlength=7)
# 因此,输出结果为:array([0, 2, 1, 2, 0, 0, 0])
# 我们可以看到x中最大的数为3,因此bin的数量为4,那么它的索引值为0->3
x = np.array([3, 2, 1, 3, 1])
# 本来bin的数量为4,现在我们指定了参数为1,那么它指定的数量小于原本的数量,因此这个参数失去了作用,索引值还是0->3
np.bincount(x, minlength=1)
# 因此,输出结果为:array([0, 2, 1, 2])

np.ones_like()

返回与给定数组一样形状的各个位置均为1的矩阵

1
2
3
大专栏  Numpy技巧 class="line">4
5
6
7
8
x = np.arange(6)
x = x.reshape((2, 3))
x
array([[0, 1, 2],
[3, 4, 5]])
np.ones_like(x)
array([[1, 1, 1],
[1, 1, 1]])

np.eye()

生成单位矩阵

1
2
3
4
5
6
np.eye(5, dtype=float)
[[ 1. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0.]
[ 0. 0. 1. 0. 0.]
[ 0. 0. 0. 1. 0.]
[ 0. 0. 0. 0. 1.]]

numpy.random.RandomState.uniform

从均匀分布中抽取样本。

样品均匀分布在半开区间[low,high)(包括低,但不包括高)。换句话说,给定区间内的任何值都同样可能被均匀抽取。

1
2
3
4
5
6
7
matrix = np.random.uniform(low=-0.1, high=0.1,size=(5,5))
[[-0.00600973 -0.00504933 0.02940658 0.08732409 -0.06275549]
[ 0.03665056 -0.05661787 -0.04970316 0.04048853 0.03820367]
[ 0.00304319 0.03092026 0.09509651 0.07155621 0.06756137]
[ 0.01997299 -0.08168592 0.09852984 0.03795403 0.00385968]
[-0.0735317 0.01449163 -0.04123698 0.03660972 0.03571927]]

numpy.random.RandomState.binomial(n, p, size=None)

表示对一个二项分布进行采样(size表示采样的次数,draw samples from a binomial distribution.),参数中的n, p分别对应于公式中的n,p,函数的返回值表示n中成功(success)的次数(也即N)。

原文地址:https://www.cnblogs.com/lijianming180/p/12284734.html