Skip to content

Commit ffb747a

Browse files
optimization(demo:perceptron): Clean perceptron code, optimize memory usage and clean comments.
1 parent 2758e69 commit ffb747a

1 file changed

Lines changed: 5 additions & 4 deletions

File tree

demo/runtime/perceptron.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
"""
2-
Recreation of the simple perceptron algorithm maintaining the exact application of Rosenblatt.
2+
Recreation of the simple perceptron algorithm maintaining the exact application of Rosenblatt (where could solve linear separable problems).
33
Rosenblatt, F. (1958). The perceptron: A probabilistic model for information storage and organization in the brain. Psychological Review, 65(6), 386–408.
44
"""
55

66
from "./lib/format.py" import report
77

88
class SimplePerceptron:
99
def __init__(self, seed: int = 42) -> None:
10+
if seed == 0:
11+
raise ValueError("LCG seed cannot be zero: it is a fixed point of the generator.")
12+
1013
self.weights: list[float] = []
1114
self.bias: float = 0.0
1215
self.seed = seed
1316

1417
def train(self, labeled_data: dict[tuple[float | int, ...], int], epochs: int = 30, learning_rate: float = 0.1) -> None:
15-
input_dim = len(next(iter(labeled_data))) # Send the pointer to the first memory register.
18+
input_dim = len(next(iter(labeled_data))) # Get input dimensionality from the first training example.
1619
self.weights = [self._lcg() for _ in range(input_dim)]
1720
self.bias = self._lcg()
1821

@@ -47,8 +50,6 @@ def _binary_step(self, pred: float) -> int:
4750
return 1 if pred >= 0.0 else 0
4851

4952
def _lcg(self) -> float: # Congruential linear generator.
50-
if self.seed == 0.0:
51-
raise ValueError("LCG seed cannot be zero: it is a fixed point of the generator.")
5253
self.seed = (self.seed * 16807) % 2147483647
5354
return (self.seed / 2147483647) - 0.5 # Normalized between -0.5 and 0.5 to avoid data scaling problems.
5455

0 commit comments

Comments
 (0)