-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
52 lines (38 loc) · 1.4 KB
/
Copy pathexample.py
File metadata and controls
52 lines (38 loc) · 1.4 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
from perceptron_rust import Perceptron
import random
import math
def main():
dimensions = 3
sample_count = 100
# For demonstration purposes, we generate a random theta and a bunch of data that matches that theta.
# This guarantees our data is linearly separable.
goal_theta = normalize(random_vector(dimensions))
samples = generate_samples(goal_theta, dimensions, sample_count)
p = Perceptron(dimensions)
p.add_samples(samples)
actual_theta = p.train(100)
print("Generated model:", actual_theta)
## Helper functions
def vector_length(v):
return math.sqrt(sum(x * x for x in v))
def normalize(v):
length = vector_length(v)
return [x / length for x in v]
def signed_distance(point, hyperplane):
dot_prod = sum(a * b for a, b in zip(hyperplane, point))
normal = vector_length(hyperplane)
return dot_prod / normal
def vector_distance(vector1, vector2):
# A.k.a. Euclidean distance
return math.sqrt(sum((v1 - v2) ** 2 for v1, v2 in zip(vector1, vector2)))
def random_vector(size = 2,):
return [random.uniform(-1, 1) for _ in range(size)]
def generate_samples(goal_theta, dimensions, count = 1):
samples = []
for _ in range(count):
point = random_vector(dimensions)
label = -1 if signed_distance(point, goal_theta) < 0 else 1
samples.append((point, label))
return samples
if __name__ == "__main__":
main()