Implementing a Perceptron Classifier¶

About This Project¶

In this project, you will implement your own perceptron. You'll implement a linear classifier and the perceptron update functions. You'll also have a chance to visualize your perceptron.

Evaluation¶

This project must be successfully completed and submitted in order to receive credit for this course. Your score on this project will be included in your final grade calculation.

You are expected to write code where you see # YOUR CODE HERE within the cells of this notebook. Not all cells will be graded; code input cells followed by cells marked with # Auto-graded test cell will be graded. Upon submitting your work, the code you write at these designated positions will be assessed using an "auto-grader" that will run all test cells to assess your code. You will receive feedback from the auto-grader that will identify any errors in your code. Use this feedback to improve your code if you need to resubmit. Be sure not to change the names of any provided functions, classes, or variables within the existing code cells, as this will interfere with the auto-grader. Also, remember to execute all code cells sequentially, not just those you’ve edited, to ensure your code runs properly.

You can resubmit your work as many times as necessary before the submission deadline. If you experience difficulty or have questions about this exercise, use the Q&A discussion board to engage with your peers or seek assistance from the instructor.

Before starting your work, please review eCornell's policy regarding plagiarism (the presentation of someone else's work as your own without source credit).

Submit Code for Auto-Grader Feedback¶

Once you have completed your work on this notebook, you will submit your code for auto-grader review. Follow these steps:

  1. Save your notebook.

  2. Mark as Completed — In the blue menu bar along the top of this code exercise window, you’ll see a menu item called Education. In the Education menu, click Mark as Completed to submit your code for auto-grader/instructor review. This process will take a moment and a progress bar will show you the status of your submission.

  3. Review your results — Once your work is marked as complete, the results of the auto-grader will automatically be presented in a new tab within the code exercise window. You can click on the assessment name in this feedback window to see more details regarding specific feedback/errors in your code submission.

  4. Repeat, if necessary — The Jupyter Notebook will always remain accessible in the first tabbed window of the exercise. To reattempt the work, you will first need to click Mark as Uncompleted in the Education menu and then proceed to make edits to the notebook. Once you are ready to resubmit, follow steps one through three. You can repeat this procedure as many times as necessary.

You can also download a copy of this notebook in multiple formats using the Save and Export Notebook As option in the File menu above.

Getting Started¶

Please run the following code to initialize your Python kernel. You should be running a version of Python 3.x.

In [ ]:
import numpy as np
from sklearn.linear_model import Perceptron
import time

# Interactive plots
%matplotlib ipympl
import matplotlib.pyplot as plt

import sys
sys.path.append("/home/codio/workspace/.modules")
from helper import *

print("Python version:", sys.version.split(" ")[0])

The perceptron is a basic linear classifier. The following cells will walk you through steps and ask you to finish the necessary functions in a pre-defined order. Code cells requiring your input will display # YOUR CODE HERE and graded portions will be adequately labeled. Unless specified otherwise, do not use loops.

Part One: Perceptron Update [Graded]¶

Implement the function below to update the perceptron given an input vector, label, and weight vector. Do not check if an update is necessary. This function can assume that it is only called when an update should be performed. Hint: You simply need to implement $\mathbf{w} \leftarrow \mathbf{w} + y \mathbf{x}$.

In [ ]:
def perceptron_update(x, y, w):
    """
    function w=perceptron_update(x,y,w);

    Updates the perceptron weight vector w using x and y
    Input:
    x : input vector of d dimensions (d)
    y : corresponding label (-1 or +1)
    w : weight vector of d dimensions

    Output:
    w : weight vector after updating (d)
    """
    # YOUR CODE HERE
    w = w + 1 * x * y
    # END OF YOUR CODE

    return w


# Little test
y = -1
x = np.random.randint(low=-2, high=2, size=10)
w = np.random.randint(low=0, high=2, size=10) * 2 - 1
print(f"y     = {y}")
print(f"x     = {x}")
print(f"w_old = {w}")

w_new = perceptron_update(x, y, w)
print(f"w_new = {w_new}")

Run the next cell to check that your function perceptron_update returns the correct values for the input vector [0, 1] (i.e., label -1) and weight vector [1, 1].

In [ ]:
def perceptron_update_test1():
    x = np.array([0, 1])
    y = -1
    w = np.array([1, 1])
    w1 = perceptron_update(x, y, w)
    return (w1.reshape(-1,) == np.array([1, 0])).all()


def perceptron_update_test2():
    x = np.random.rand(25)
    y = 1
    w = np.zeros(25)
    w1 = perceptron_update(x, y, w)
    return np.linalg.norm(w1 - x) < 1e-8


def perceptron_update_test3():
    x = np.random.rand(25)
    y = -1
    w = np.zeros(25)
    w1 = perceptron_update(x, y, w)
    return np.linalg.norm(w1 + x) < 1e-8


runtest(perceptron_update_test1, "perceptron_update_test1")
runtest(perceptron_update_test2, "perceptron_update_test2")
runtest(perceptron_update_test3, "perceptron_update_test3")

Skip over the auto-graded test cells below (see Evaluation for details).

In [ ]:
# Auto-graded test cell worth one point (perceptron_update_test1)
In [ ]:
# Auto-graded test cell worth one point (perceptron_update_test2)
In [ ]:
# Auto-graded test cell worth one point (perceptron_update_test3)

Part Two: Implement Perceptron [Graded]¶

Implement function perceptron. This should contain a loop that calls perceptron_update until it converges or the maximum iteration count, 100, has been reached. Make sure you randomize the order of the training data on each iteration (you can use np.random.permutation() to do this.)

Note that the pseudocode below assumes that $b$ is absorbed into $\mathbf{w}$. In other words, the last dimension of $\mathbf{x}_i$ is 1 and the last dimension of $\mathbf{w}$ is the bias term. When implementing the perceptron function, make sure to take this into consideration and modify the data and weight vector accordingly.

Pseudocode:

Perceptron pseudocode
In [ ]:
def perceptron(xs, ys):
    """
    function w=perceptron(xs,ys);

    Returns the weight vector learned by the Perceptron classifier.

    Input:
        xs: n input vectors of d dimensions (nxd matrix)
        ys: n labels (-1 or +1)

    Output:
        w: weight vector (d)
        b: bias term
    """
    n, d = xs.shape  # So we have n input vectors with d dimensions
    w = np.zeros(d)
    b = 0.0

    # YOUR CODE HERE
    while True:
        cnt = 0
        for x, y in zip(xs,ys):
            resp = np.dot(w,x) + b
            if y * resp <=0:
                w = w + y * x
                b = b + y
                cnt += 1
        if cnt == 0:
            break
    # END OF YOUR CODE

    return (w, b)

Run the next cell to check that your perceptron function successfully classifies points in two different linearly separable dataset.

In [ ]:
def perceptron_test1():
    N = 100
    d = 10
    x = np.random.rand(N, d)
    w = np.random.rand(1, d)
    y = np.sign(w.dot(x.T))[0]
    w, b = perceptron(x, y)
    preds = classify_linear_grader(x, w, b)
    return np.array_equal(preds.reshape(-1,), y.reshape(-1,))


def perceptron_test2():
    x = np.array(
        [
            [-0.70072, -1.15826],
            [-2.23769, -1.42917],
            [-1.28357, -3.52909],
            [-3.27927, -1.47949],
            [-1.98508, -0.65195],
            [-1.40251, -1.27096],
            [-3.35145, -0.50274],
            [-1.37491, -3.74950],
            [-3.44509, -2.82399],
            [-0.99489, -1.90591],
            [0.63155, 1.83584],
            [2.41051, 1.13768],
            [-0.19401, 0.62158],
            [2.08617, 4.41117],
            [2.20720, 1.24066],
            [0.32384, 3.39487],
            [1.44111, 1.48273],
            [0.59591, 0.87830],
            [2.96363, 3.00412],
            [1.70080, 1.80916],
        ]
    )
    y = np.array([1] * 10 + [-1] * 10)
    w, b = perceptron(x, y)
    preds = classify_linear_grader(x, w, b)
    return np.array_equal(preds.reshape(-1,), y.reshape(-1,))


runtest(perceptron_test1, "perceptron_test1")
runtest(perceptron_test2, "perceptron_test2")

Skip over the auto-graded test cells below (see Evaluation for details).

In [ ]:
# Auto-graded test cell worth one point (perceptron_test1)
In [ ]:
# Auto-graded test cell worth one point (perceptron_test2)

Part Three: Visualize Your Perceptron [Ungraded]¶

Once you have perceptron implemented, we can visualize how it finds w that classify points in a 2-dimensional plane. In this example, we center the data by subtracting the common mean vector of $\mathbf{x}_i$ from each of $\mathbf{x}_i$. Consequently, the perceptron algorithm will learn the bias term (the last dimension of $\mathbf{w}$ as 0).

The next cell defines a function plot_perceptron_2D that you will use to visualize your perceptron model.

In [ ]:
def plot_perceptron_2D(x, y_true, w_true, y_pred, w_pred, b):
    w_pred = w_pred.flatten()
    w_true = w_true.flatten()

    fig = plt.figure()
    plt.scatter(x[:, 0], x[:, 1], c=y_true, cmap="viridis")  # Plot points
    grid_lim = np.max(abs(x[:, :-1]))

    def calc_x2(b, x1, w):
        return -(b + w[0] * x1) / w[1]

    # Make arrow for w_true: normalize by magnitude, then stretch to grid lim
    w_true_mag = np.sqrt(np.sum(w_true[:-1] ** 2))
    plt.quiver(
        [0],
        [0],
        [(w_true[0] / w_true_mag) * grid_lim],
        [(w_true[1] / w_true_mag) * grid_lim],
        scale=1,
        units="xy",
        color="black",
    )
    plt.annotate(
        "w_true",
        xy=w_true[:-1] / w_true_mag * grid_lim + [0.05, 0.0],
        fontsize=12,
        color="black",
    )

    # Make decision line perpendicular to arrow
    plt.plot(
        [grid_lim, -grid_lim],
        [calc_x2(b, grid_lim, w_true), calc_x2(b, -grid_lim, w_true)],
        color="black",
        label="True decision line",
    )

    # Repeat for w_pred
    w_pred_mag = np.sqrt(np.sum(w_pred[:-1] ** 2))
    plt.quiver(
        [0],
        [0],
        [(w_pred[0] / w_pred_mag) * grid_lim],
        [(w_pred[1] / w_pred_mag) * grid_lim],
        scale=1,
        units="xy",
        color="red",
    )
    plt.annotate(
        "w_pred",
        xy=w_pred[0] / w_pred_mag * grid_lim + [0.0, 0.1],
        fontsize=12,
        color="red",
    )
    plt.plot(
        [grid_lim, -grid_lim],
        [calc_x2(b, grid_lim, w_pred), calc_x2(b, -grid_lim, w_pred)],
        color="red",
        label="Pred decision line",
    )

    plt.title(f"True and Predicted Decision Line")
    plt.xlim(-grid_lim, grid_lim)
    plt.ylim(-grid_lim, grid_lim)
    plt.legend(bbox_to_anchor=(1, 1), loc="upper right")
    #plt.grid()
    plt.show()

Run the next cell to visualize your perceptron classifier.

In [ ]:
# Number of observations and features
N, d = 500, 2

# Create random dataset
np.random.seed(1)
x = np.random.rand(N, d)
x -= np.mean(x)  # Subtracting mean puts features in range [-0.5, 0.5]

# Generate w from which labels are computed
w_true = np.random.rand(1, d)
w_true -= np.mean(w_true)  # Only rotates weight vector in 2D space
y_true = np.sign(w_true.dot(x.T))[0]

# Make the separation line impossible to compute so that 
# both w_true and w_pred can be plotted distinctly.
y_true[0] = -1 * y_true[0]

# Compute predictions
w_pred, b = perceptron(x, y_true)
y_pred = classify_linear_grader(x, w_pred, b).astype(int)

plot_perceptron_2D(x, y_true, w_true, y_pred, w_pred, b)

The next cell will check to see if your perceptron correctly classified all the points in a linearly separable dataset.

In [ ]:
# Number of input vectors
N = 100

# Generate random (linarly separable) data
xs = np.random.rand(N, 2) * 10 - 5

# Defining random hyperplane
w0 = np.random.rand(2)
b0 = np.random.rand() * 2 - 1

# Assigning labels (+1 or -1) depending on what side of the plane they lie on
ys = np.sign(xs.dot(w0) + b0)

# Call perceptron to find w from data
w, b = perceptron(xs.copy(), ys.copy())

# Test if all points are classified correctly
assert all(np.sign(ys * (xs.dot(w) + b)) == 1.0)  # Should be +1.0 for every input
print("Looks like you passed the perceptron test!")

# We can make a pretty visualization
visboundary(w, b, xs, ys)

Your Perceptron Model in Action¶

The following script generates a plot where you can manually add positive and negative values. Simply click on the plot space to add negative points and shift+click to add positive points. Once you have added at least one positive and one negative value each, the plot will generate a decision boundary from your perceptron model.

In [ ]:
# Initialize empty array of width 3 to store two-dimensional training points
# and a third dimension that has a constant value of 1 (to incorporate bias).
xy_data = np.empty((0, 3))

# Initialize empty array of width 1 to store training labels
label_data = np.empty((0, 1))


def onclick(event):
    """
    Assume the last dimension of each training point is 1,
    so the last dimension of w represents the bias term.
    """
    global xy_data, label_data

    # Shift+click to add a negative point.
    # Click to add a positive point.
    if event.key == "shift":
        label = -1
    else:
        label = 1

    # Create position vector for new point with
    # x-coord, y-coord, and constant value of 1.
    pos = np.array([[event.xdata, event.ydata, 1]])

    # Add new point and label to training data
    xy_data = np.vstack((xy_data, pos))
    label_data = np.append(label_data, label)

    # Get class values from training labels
    classvals = np.unique(label_data)

    # Plot configuration
    plt.cla()                  # Clear axes
    plt.xlim((0, 1))           # x-axis limits
    plt.ylim((0, 1))           # y-axis limits
    labels = ["$-1$", "$+1$"]  # Labels for training points
    symbols = ["x", "o"]       # "x" for -1 and "o" for +1 (training)
    colors = ["red", "blue"]   # Red for -1 and blue for +1 (predictions)

    if len(classvals) == 1 and 1 in classvals:
        # Plot points with "o" markers because only +1 points have been added
        for idx, c in enumerate(classvals):
            plt.scatter(
                xy_data[label_data == c, 0],  # x-coordinate of training point
                xy_data[label_data == c, 1],  # y-coordinate of training point
                label="$+1$",                 # Label of training point
                marker="o",                   # Marker of training point
                color="blue",                 # Color of training point
            )
    else:
        # Plot training data: "x" for -1 and "o" for +1
        for idx, c in enumerate(classvals):
            plt.scatter(
                xy_data[label_data == c, 0],  # x-coordinate of training point
                xy_data[label_data == c, 1],  # y-coordinate of training point
                label=labels[idx],            # Label of training point (-1 or +1)         
                marker=symbols[idx],          # Marker of training point ("x" or "o")
                color=colors[idx],            # Color of training point
            )
    
    # Call perceptron function to get trained weights and bias
    w, b = perceptron(xy_data, label_data)

    # Plot decision boundary using trained weights and bias
    x = np.linspace(start=0, stop=1, num=1000)
    y = -(w[0] * x + b) / w[1]
    plt.plot(x, y, color="black", linestyle="--")
    
    plt.title("Click: Positive Point, Shift+Click: Negative Point")
    plt.legend(loc="upper left")
    plt.show()


# Plot interactive demo
print("Please keep in mind:")
print("1. You must run (or rerun) this cell right before interacting with the plot.")
print("2. Start the interactive demo by clicking the grid to add a positive point.")
print("3. Click to add a positive point or shift+click to add a negative point.")
print("4. You may notice a slight delay when adding points to the visualization.")
fig = plt.figure()
plt.title("Start by Clicking the Grid to Add a Positive Point")
plt.xlim(0, 1)
plt.ylim(0, 1)
cid = fig.canvas.mpl_connect("button_press_event", onclick)

Part Three: Make Predictions [Graded]¶

Implement classify_linear that applies the weight vector (with implicit bias term) to the input vector. Make sure that the predictions returned are either 1 or -1.

In [ ]:
def classify_linear(xs, w, b=None):
    """
    function preds=classify_linear(xs,w,b)

    Make predictions with a linear classifier
    
    Input:
        xs: n input vectors of d dimensions (nxd) [could also be a single vector of d dimensions]
        w: weight vector of dimensionality d
        b: bias (scalar)

    Output:
        preds: predictions (1xn)
    """
    w = w.flatten()
    predictions = np.zeros(xs.shape[0])

    # YOUR CODE HERE
    if b is None:
        b = 0
    w = w.flatten()
    resp = xs@w + b
    predictions = np.where(resp >=0,1,-1)
    # END OF YOUR CODE
    
    return predictions

Run the next cell to check that your linear classifier correctly classifies the points in a linearly separable dataset.

In [ ]:
def linear_test1():
    """
    Check that predictions are only -1 or 1
    """
    xs = np.random.rand(50000, 20) - 0.5  # Draw random data
    xs = np.hstack([xs, np.ones((50000, 1))])
    w0 = np.random.rand(20 + 1)
    w0[-1] = -0.1                         # Assign bias of -0.1
    ys = classify_linear(xs, w0)
    uniquepredictions = np.unique(ys)
    return set(uniquepredictions) == {-1, 1}


def linear_test2():
    """
    Check that all predictions are correct for linearly separable data
    """
    xs = np.random.rand(1000, 2) - 0.5  # Draw random data
    xs = np.hstack([xs, np.ones((1000, 1))])

    # Define a random hyperplane with bias -0.1
    w0 = np.array([0.5, -0.3, -0.1])
    
    # Assign labels according to this hyperplane (so you know it is linearly separable)
    ys = np.sign(xs.dot(w0))

    # Original hyperplane (w0, b0) should classify all ones correctly
    result = all(np.sign(ys * classify_linear(xs, w0)) == 1.0)
    
    return result


runtest(linear_test1, "linear_test1")
runtest(linear_test2, "linear_test2")

Skip over the auto-graded test cells below (see Evaluation for details).

In [ ]:
# Auto-graded test cell worth one point (linear_test1)
In [ ]:
# Auto-graded test cell worth one point (linear_test2)

Scikit-Learn Approach¶

Scikit-learn (or sklearn) is a Python library with implementations for numerous machine learning and data science models. Scikit-learn provides a standard step-by-step training procedure across different machine learning models, simplifying model training and prediction. The typical process for selecting, training, and predicting with a model of your choice is as follows:

  1. Define the classifier clf using a call to the model class.

  2. Train clf using clf.fit on training data.

  3. Predict on test data using clf.predict, getting predictions as output.

Scikit-learn provides a perceptron model. We provide a brief demonstration of its usage below.

In [ ]:
N, d = 500, 2
np.random.seed(1)
x = np.random.rand(N, d)

# Subtracting mean puts features in range [-0.5, 0.5]
x -= np.mean(x)

# Add constant dimension -- a column of 1s at the end
x = np.hstack([x, np.ones((N, 1))])

w_true = np.random.rand(d)
w_true -= np.mean(w_true)  # Only rotates weight vector in 2D space
w_true = np.append(w_true, [0.0])  # Add bias term equal to 0
y_true = classify_linear_grader(x, w_true).astype(int)

# Change label of a data point.
# This way perceptron will never learn w_true,
# and we can plot both w_true and w_pred distinctly.
y_true[np.random.randint(N)] *= -1
In [ ]:
# Initialize the Perceptron
clf = Perceptron(max_iter=100, fit_intercept=True)

# Train on all features except the constant feature that was manually added
clf.fit(x[:, :-1], y_true)
w_pred_sklearn = np.concatenate([clf.coef_.flatten(), clf.intercept_.flatten()])

# The function classify_linear_grader() expects x to have 1s as the last column
y_pred_sklearn = classify_linear_grader(x, w_pred_sklearn).astype(int)
In [ ]:
plot_perceptron_2D(x, y_true, w_true, y_pred_sklearn, w_pred_sklearn, 0)