Perceptron — the learning rule
Background
The perceptron learns by fixing its mistakes. Starting from zero weights, it sweeps the data for epochs passes; on each example it predicts and nudges the parameters toward the truth:
If the prediction is right, and nothing changes. If wrong, the weights move toward the misclassified point. For linearly separable data this is guaranteed to converge to a perfect separator.
Problem statement
Implement train_perceptron(X, y, epochs, lr) that runs the rule above from a zero start and returns the learned (w, b).
Input
X— array-like of shape(m, n): one example per row.y— array-like ofmlabels (0/1).epochs—int: number of full passes over the data.lr—float: the learning rate .
Output
Returns a tuple (w, b) where w is an np.ndarray of shape (n,) and b is a float.
Examples
Example — the AND gate becomes separable
Input: X = [[0,0],[0,1],[1,0],[1,1]], y = [0,0,0,1], epochs = 20, lr = 1.0
Output: (w, b) that classify all four points correctly:
perceptron([0,0], w, b)=0, [0,1]=0, [1,0]=0, [1,1]=1
Explanation: AND is linearly separable, so the rule converges to a valid boundary.
Constraints
- Initialise
w = zeros(n)andb = 0.0. - Process examples in order within each epoch, updating after each one.
- Use the step prediction inside the loop.
- Return
was shape(n,)andbas afloat.
Notes
- A single perceptron can only separate linearly separable classes — it will never fit XOR, no matter how many epochs. That limitation is what motivates hidden layers and depth.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Example — learns the AND gate
- •Reference learns the OR gate
- •Sample zero learning rate stays at zero init