-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoltzmann_Machine.py
More file actions
44 lines (35 loc) · 1.56 KB
/
Boltzmann_Machine.py
File metadata and controls
44 lines (35 loc) · 1.56 KB
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
import numpy as np
class BoltzmannMachine:
def __init__(self, num_nodes):
self.num_nodes = num_nodes
self.weights = np.random.rand(num_nodes, num_nodes) - 0.5
self.weights = 0.5 * (self.weights + self.weights.T) # Make the matrix symmetric
np.fill_diagonal(self.weights, 0) # No self-connections
def energy(self, state):
return -0.5 * np.dot(state, np.dot(self.weights, state))
def sample(self):
state = np.random.choice([0, 1], size=self.num_nodes)
for _ in range(100): # Sampling iterations
i = np.random.randint(0, self.num_nodes)
activation = np.dot(self.weights[i], state)
probability = 1 / (1 + np.exp(-activation))
state[i] = 1 if np.random.rand() < probability else 0
return state
def train(self, data, epochs, learning_rate):
for epoch in range(epochs):
for sample in data:
# Data phase
positive_correlations = np.outer(sample, sample)
# Model phase
state = self.sample()
negative_correlations = np.outer(state, state)
# Update weights
self.weights += learning_rate * (positive_correlations - negative_correlations)
np.fill_diagonal(self.weights, 0) # No self-connections
# Example usage
num_nodes = 10
bm = BoltzmannMachine(num_nodes)
# Dummy data
data = np.random.choice([0, 1], (5, num_nodes))
# Training
bm.train(data, epochs=100, learning_rate=0.1)