-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdm.py
126 lines (97 loc) · 2.98 KB
/
sdm.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""sdm.py -- Sparse Distributed Memory
Authors:
Jessica Hamrick (jhamrick@berkeley.edu)
Josh Abbott (joshua.abbott@berkeley.edu)
"""
import numpy as np
class SDM(object):
def __init__(self, n, m, D, seed=0):
"""Initialize a SDM.
Parameters
----------
n : length of inputs/addresses
m : number of addresses/storage locations
D : hamming radius
seed : random number generator seed
"""
# save parameters
self.n = n
self.m = m
self.D = D
# random number generator
if isinstance(seed, int):
rso = np.random.RandomState(seed)
else:
rso = seed
# address matrix: random binary matrix, where the kth row
# is the address of the kth storage location
self.A = rso.randint(0, 2, (m, n, 1))
self._A = self.A.copy()
# counter matrix: stores contents of the addressed locations
self.C = np.zeros((n, m))
self._C = self.C.copy()
def reset(self):
"""Reset the SDM to it's original state."""
self.A = self._A.copy()
self.C = self._C.copy()
def _select(self, address):
"""Select addresses with the Hamming radius(self.D) of the
given address
Parameters
----------
address : vector of size n
Returns
-------
theta : binary vector of size m
"""
x = np.sum(self.A ^ address, axis=1)
theta = x <= self.D
return theta
def readM(self, addresses):
"""Read the data at the locations indicated by the given M
addresses.
Parameters
----------
addresses : array of size (n, M)
Returns
-------
data : array of size (n, M)
"""
s = self._select(addresses)
h = np.dot(self.C, s)
data = np.zeros(h.shape, dtype='i4')
data[h > 0] = 1
return data
def read(self, address):
"""Read the data at the location indicated by the given
address.
Parameters
----------
address : vector of size n
Returns
-------
data : vector of size n
"""
data = self.readM(address[:, None])[:, 0]
return data
def writeM(self, addresses, data):
"""Write M vectors of `data` at the locations indicated by the
given M `addresses`.
Parameters
----------
addresses : matrix of size (n, M)
data : matrix of size (n, M)
"""
s = self._select(addresses)
w = (data * 2) - 1
c = np.sum(w[:, None] * s[None, :], axis=2)
self.C += c
def write(self, address, data):
"""Write the given data at the location indicated by the given
address.
Parameters
----------
address : vector of size n
data : vector of size n
"""
self.writeM(address[:, None], data[:, None])