我无法理解numpy中使用的伯努利随机数生成器是如何计算的,并希望对此进行一些解释。例如:
np.random.binomial(size=3, n=1, p= 0.5)
Results:
[1 0 0]
n =步数
p =发生的概率
大小=实验次数
如何确定生成的数字/结果“0”或“1”?
================================更新================= ==================
我创建了一个受限的Boltzmann机器,尽管它在多个代码执行中是“随机的”,但始终可以显示相同的结果。随机种子使用
np.random.seed(10)
import numpy as np
np.random.seed(10)
def sigmoid(u):
return 1/(1+np.exp(-u))
def gibbs_vhv(W, hbias, vbias, x):
f_s = sigmoid(np.dot(x, W) + hbias)
h_sample = np.random.binomial(size=f_s.shape, n=1, p=f_s)
f_u = sigmoid(np.dot(h_sample, W.transpose())+vbias)
v_sample = np.random.binomial(size=f_u.shape, n=1, p=f_u)
return [f_s, h_sample, f_u, v_sample]
def reconstruction_error(f_u, x):
cross_entropy = -np.mean(
np.sum(
x * np.log(sigmoid(f_u)) + (1 - x) * np.log(1 - sigmoid(f_u)),
axis=1))
return cross_entropy
X = np.array([[1, 0, 0, 0]])
#Weight to hidden
W = np.array([[-3.85, 10.14, 1.16],
[6.69, 2.84, -7.73],
[1.37, 10.76, -3.98],
[-6.18, -5.89, 8.29]])
hbias = np.array([1.04, -4.48, 2.50]) #<= 3 bias for 3 neuron in hidden
vbias = np.array([-6.33, -1.68, -1.25, 3.45]) #<= 4 bias for 4 neuron in input
k = 2
v_sample = X
for i in range(k):
[f_s, h_sample, f_u, v_sample] = gibbs_vhv(W, hbias, vbias, v_sample)
start = v_sample
if i < 2:
print('f_s:', f_s)
print('h_sample:', h_sample)
print('f_u:', f_u)
print('v_sample:', v_sample)
print(v_sample)
print('iter:', i, ' h:', h_sample, ' x:', v_sample, ' entropy:%.3f'%reconstruction_error(f_u, v_sample))
结果:
[[1 0 0 0]]
f_s: [[ 0.05678618 0.99652957 0.97491304]]
h_sample: [[0 1 1]]
f_u: [[ 0.99310473 0.00139984 0.99604968 0.99712837]]
v_sample: [[1 0 1 1]]
[[1 0 1 1]]
iter: 0 h: [[0 1 1]] x: [[1 0 1 1]] entropy:1.637
f_s: [[ 4.90301318e-04 9.99973278e-01 9.99654440e-01]]
h_sample: [[0 1 1]]
f_u: [[ 0.99310473 0.00139984 0.99604968 0.99712837]]
v_sample: [[1 0 1 1]]
[[1 0 1 1]]
iter: 1 h: [[0 1 1]] x: [[1 0 1 1]] entropy:1.637
最佳答案
I am asking on how the algorithm works to produce the numbers. – WhiteSolstice 35 mins ago
非技术说明
如果将
n=1
传递给二项分布,则等效于Bernoulli分布。在这种情况下,可以考虑模拟硬币翻转功能。 size=3
告诉它将硬币翻转三下,并且p=0.5
使其成为具有相同概率的正面(1)或背面(0)的公平硬币。[1 0 0]
的结果意味着硬币一次掉头一次,尾部朝上两次。这是随机的,因此再次运行将导致不同的序列,例如[1 1 0]
,[0 1 0]
甚至[1 1 1]
。尽管在三个运行中无法获得相同的1和0,但是平均而言,您将获得相同的数字。技术说明
Numpy在C语言中实现随机数生成。二项式分布的源代码可以在here中找到。实际上,实现了两种不同的算法。
n * p <= 30
,则使用inverse transform sampling。 n * p > 30
,则使用(Kachitvichyanukul和Schmeiser 1988)的BTPE算法。 (出版物为not freely available。)我认为这两种方法都可以依靠随机数生成器来产生均匀分布的随机数,但当然可以逆变换采样。 Numpy内部使用Mersenne Twister伪随机数生成器。然后将统一的随机数转换为所需的分布。
关于numpy - 伯努利随机数发生器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47012474/