# Step 4: distillation. A small student learns from the teacher's chances,
# not only from the right answers, so it learns how sure the teacher was.
from tiny_nn import Random, load_windows, split, new_layer, forward, softmax, best, train, accuracy, count, save, load

TEMPERATURE = 2.0

xs, ys = load_windows("windows.csv")
train_x, train_y, test_x, test_y = split(xs, ys)
teacher = load("teacher.txt")

# The teacher's soft answers, for example 0.80 brake, 0.15 cruise, 0.05 accelerate.
soft = [softmax(forward(teacher, x)[1], TEMPERATURE) for x in train_x]
unsure = 0
for i in range(len(soft)):
    if soft[i][best(soft[i])] < soft[unsure][best(soft[unsure])]:
        unsure = i
c = soft[unsure]
print(f"The teacher's least sure window: {c[0]:.2f} accelerate, {c[1]:.2f} cruise, {c[2]:.2f} brake")

rng = Random(7)
student = [new_layer(4, 4, rng), new_layer(4, 3, rng)]
print(f"Training the student: 4 inputs, 4 hidden, 3 outputs, temperature {TEMPERATURE}")
train(student, train_x, soft, epochs=1000, rate=0.5, temperature=TEMPERATURE)

agree = 0
for x in test_x:
    if best(forward(student, x)[1]) == best(forward(teacher, x)[1]):
        agree += 1
print(f"Student got {accuracy(student, test_x, test_y)} of {len(test_y)} test windows right")
print(f"It agrees with the teacher on {agree} of {len(test_x)}")
print(f"Teacher: {count(teacher)} numbers. Student: {count(student)} numbers.")

save(student, "student.txt")
print("Saved the student to student.txt")
