-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathrestricted_boltzmann_machine.py
111 lines (90 loc) · 4.27 KB
/
restricted_boltzmann_machine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import numpy as np
from sklearn.datasets import load_digits, fetch_openml
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class RBM(object):
def __init__(self, n_v, n_h, epochs=50, lr=0.05):
self.w = np.random.randn(n_v, n_h)
self.a = np.random.randn(1, n_v)
self.b = np.random.randn(1, n_h)
self.mom_w, self.cache_w = np.zeros_like(self.w), np.zeros_like(self.w)
self.mom_a, self.cache_a = np.zeros_like(self.a), np.zeros_like(self.a)
self.mom_b, self.cache_b = np.zeros_like(self.b), np.zeros_like(self.b)
self.lr = lr
self.batch_size = 16
self.max_epochs = epochs
self.decay = 1 - 1e-4
def fit(self, v):
beta1 = 0.9
beta2 = 0.999
eps = 1e-20
train_num = v.shape[0]
for j in range(self.max_epochs):
permut = np.random.permutation(
train_num // self.batch_size * self.batch_size).reshape(-1, self.batch_size)
for i in range(permut.shape[0]):
v0 = v[permut[i], :]
p_h0 = self.marginal_h(v0)
h0 = 1 * (p_h0 >= np.random.uniform(0, 1,
(self.batch_size, self.b.shape[1])))
v1 = self.marginal_v(h0)
p_h1 = self.marginal_h(v1)
h1 = 1 * (p_h1 >= np.random.uniform(0, 1,
(self.batch_size, self.b.shape[1])))
grad_w = np.matmul(v1.T, p_h1) - np.matmul(v0.T, p_h0)
grad_b = np.matmul(np.ones((1, self.batch_size)), p_h1 - p_h0)
grad_a = np.matmul(np.ones((1, self.batch_size)), v1 - v0)
alpha = self.lr / self.batch_size
mom_scaler = 1 - beta1 ** (j + 1)
cache_scaler = 1 - beta2 ** (j + 1)
self.mom_w = beta1 * self.mom_w + (1 - beta1) * grad_w
self.cache_w = beta2 * self.cache_w + \
(1 - beta2) * np.square(grad_w)
self.w -= alpha * self.mom_w / mom_scaler / \
(np.sqrt(self.cache_w / cache_scaler) + eps)
self.mom_b = beta1 * self.mom_b + (1 - beta1) * grad_b
self.cache_b = beta2 * self.cache_b + \
(1 - beta2) * np.square(grad_b)
self.b -= alpha * self.mom_b / mom_scaler / \
(np.sqrt(self.cache_b / cache_scaler) + eps)
self.mom_a = beta1 * self.mom_a + (1 - beta1) * grad_a
self.cache_a = beta2 * self.cache_a + \
(1 - beta2) * np.square(grad_a)
self.a -= alpha * self.mom_a / mom_scaler / \
(np.sqrt(self.cache_a / cache_scaler) + eps)
self.w *= self.decay
self.a *= self.decay
self.b *= self.decay
if j % 10 == 9:
print('squared loss', np.square(
self.marginal_v(self.marginal_h(v)) - v).sum())
# print(np.around(self.marginal_v(self.marginal_h(v)), 3))
def marginal_v(self, h):
return sigmoid(self.a + np.matmul(h, self.w.T))
def marginal_h(self, v):
return sigmoid(self.b + np.matmul(v, self.w))
def main():
# data = load_digits()
# x, y = data.data, data.target
x, y = fetch_openml('mnist_784', return_X_y=True, data_home="data", as_frame=False)
test_ratio = 0.2
test_split = np.random.uniform(0, 1, x.shape[0])
train_x, test_x = x[test_split >= test_ratio] / \
x.max(), x[test_split < test_ratio] / x.max()
train_y, test_y = y.astype(np.int_)[test_split >= test_ratio], y.astype(
np.int_)[test_split < test_ratio]
rbm = RBM(x.shape[1], 64)
rbm.fit(train_x)
print(np.square(rbm.marginal_v(rbm.marginal_h(train_x)) - train_x).sum())
print(np.square(rbm.marginal_v(rbm.marginal_h(test_x)) - test_x).sum())
for i in range(10):
plt.subplot(2, 10, i + 1)
plt.imshow(test_x[test_y == i].mean(axis=0).reshape(
28, 28), cmap='gray', vmin=0, vmax=1)
plt.subplot(2, 10, i + 11)
plt.imshow(rbm.marginal_v(rbm.marginal_h(test_x[test_y == i])).mean(
axis=0).reshape(28, 28), cmap='gray', vmin=0, vmax=1)
plt.show()
if __name__ == "__main__":
main()