← Lesson
A Linear Classifier
Joeven
Run
Reset
Python loads on first run
import math # x = how many times "down" appears, y = urgent xs = [0.0, 1.0, 2.0, 3.0, 4.0] ys = [0.0, 0.0, 1.0, 1.0, 1.0] def sigmoid(z): z = max(-30.0, min(30.0, z)) return 1.0 / (1.0 + math.exp(-z)) def predict_p(x, w, b): return sigmoid(w * x + b) w, b = 0.0, 0.0 lr = 0.5 for step in range(1, 81): gw = gb = 0.0 for x, y in zip(xs, ys): p = predict_p(x, w, b) gw += (p - y) * x gb += p - y n = len(xs) w -= lr * gw / n b -= lr * gb / n print("w", round(w, 3), "b", round(b, 3)) for x, y in zip(xs, ys): p = predict_p(x, w, b) yhat = 1 if p >= 0.5 else 0 print("downs", int(x), "p", round(p, 3), "pred", yhat, "true", int(y))
Run to execute this in your browser. Nothing is sent to a server.