-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcatConnection.py
More file actions
80 lines (68 loc) · 2.15 KB
/
Copy pathConcatConnection.py
File metadata and controls
80 lines (68 loc) · 2.15 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
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
from typing import Union, Tuple, Optional, Sequence, Dict
import numpy as np
import torch
from torch.nn import Module, Parameter
from bindsnet.network.nodes import Nodes
from bindsnet.network.topology import AbstractConnection
class ConcatConnection(AbstractConnection):
def __init__(
self,
source: Dict[str, Nodes],
target: Nodes,
nu: Optional[Union[float, Sequence[float]]] = None,
reduction: Optional[callable] = None,
weight_decay: float = 0.0,
**kwargs
) -> None:
super().__init__(source, target, nu, reduction, weight_decay, **kwargs)
w = kwargs.get("w", None)
source_n = np.sum(nodes.n for nodes in list(source.values()))
if w is None:
if self.wmin == -np.inf or self.wmax == np.inf:
w = torch.clamp(
torch.zeros(source_n, target.n), self.wmin, self.wmax
)
else:
w = self.wmin + torch.zeros(source_n, target.n) * (
self.wmax - self.wmin
)
else:
if self.wmin != -np.inf or self.wmax != np.inf:
w = torch.clamp(w, self.wmin, self.wmax)
self.w = Parameter(w, requires_grad=False)
self.b = Parameter(
kwargs.get("b", torch.zeros(target.n)), requires_grad=False
)
def compute(self, s: torch.Tensor) -> torch.Tensor:
# language=rst
"""
Compute pre-activations given spikes using connection weights.
:param s: Incoming spikes.
:return: Incoming spikes multiplied by synaptic weights (with or without
decaying spike activation).
"""
# Compute multiplication of spike activations by weights and add bias.
post = s.float().view(s.size(0), -1) @ self.w + self.b
return post.view(s.size(0), *self.target.shape)
def update(self, **kwargs) -> None:
# language=rst
"""
Compute connection's update rule.
"""
super().update(**kwargs)
def normalize(self) -> None:
# language=rst
"""
Normalize weights so each target neuron has sum of connection weights equal to
``self.norm``.
"""
if self.norm is not None:
w_abs_sum = self.w.abs().sum(0).unsqueeze(0)
w_abs_sum[w_abs_sum == 0] = 1.0
self.w *= self.norm / w_abs_sum
def reset_state_variables(self) -> None:
# language=rst
"""
Contains resetting logic for the connection.
"""
super().reset_state_variables()