# Training data: (input, expected output) training_data = [ (3, 21), (4, 28), (5, 35), (6, 42) ] # Initial parameters weight = 1.0 bias = 0.0 learning_rate = 0.01 epochs = 100 def predict(x, weight, bias): return x * weight + bias def loss(expected, predicted): return (expected - predicted) ** 2 # Training loop for epoch in range(epochs): total_loss = 0 # Calculate gradients over all examples weight_gradient = 0 bias_gradient = 0 for x, expected in training_data: prediction = predict(x, weight, bias) error = prediction - expected total_loss += error ** 2 weight_gradient += 2 * error * x bias_gradient += 2 * error # Average gradients and loss weight_gradient /= len(training_data) bias_gradient /= len(training_data) total_loss /= len(training_data) # Update parameters weight -= learning_rate * weight_gradient bias -= learning_rate * bias_gradient if epoch % 10 == 0: print( "Epoch:", epoch, "Loss:", round(total_loss, 6), "Weight:", round(weight, 4), "Bias:", round(bias, 4) ) print("\nFinal weight:", weight) print("Final bias:", bias) # Test predictions print("\nTesting:") for x, expected in training_data: result = predict(x, weight, bias) print( x, "->", round(result, 2), "(expected:", expected, ")" )