Building a Baby Name Classifier¶
About This Project¶
In this project, you will use Naïve Bayes to build a baby name classifier. Your classifier will use the features commonly found in names to distinguish whether a name is likely to be given to a baby girl or boy. You'll train your classifier to identify these certain qualities of names and classify new examples based on those qualities.
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:
Save your notebook.
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.
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.
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¶
Prepare Text for Machine Learning¶
If we are to create a classifier for text, we'll first need to think about the format of our data. Take a look at the files girls.train and boys.train. For example, if you open a terminal by selecting File > New > Terminal from the top menu, executing the command cat girls.train will return
...
Addisyn
Danika
Emilee
Aurora
Julianna
Sophia
Kaylyn
Litzy
Hadassah
This file contains names that are more or less commonly used for girls. The problem with the current data in this file is that the names are in plain text, which is not a format our machine learning algorithm can work with effectively. You need to transform these plain text names into some vector format, where each name becomes a vector that represents a point in some high dimensional input space. That is exactly what the Python function name2features does (defined below), by arbitrarily chunking and hashing different string extractions from each baby name inputted, thus transforming the string into a quantitative feature vector.
Python Initialization¶
Please run the following code to initialize your Python kernel. You should be running a version of Python 3.x.
import numpy as np
import pandas as pd
import seaborn as sns
# Non-interactive plots
%matplotlib inline
import matplotlib.pyplot as plt
import sys
sys.path.append("/home/codio/workspace/.modules")
from helper import *
print("Python version:", sys.version.split(" ")[0])
Python version: 3.12.5
The hashfeatures and name2features Functions¶
Below, the hashfeatures and name2features functions will take the plain text names and convert them to binary feature vectors (vectors with 0s and 1s) so that you'll be able to work with the data effectively.
Converting Non-numeric Training Data to Numeric Vectors¶
The hashfeatures function relies on Python's inbuilt hash function, which converts any data type in Python to a large integer. The hash function ensures that the same objects have the same hash output in a single Python session. Across different Python sessions, you can ensure hash outputs the same integer for the same objects by seeding it.
In our case, hash will convert string objects to integers, which we will "truncate" to our desired dimension d.
hashfeatures has been implemented for you. It works as follows: It splits the baby name FIX times such that split 0 < m <= FIX gives 2 strings. The first is a prefix of baby of length m and the second is the suffix of baby of length m.
For example, with debug=True, calling hashfeatures on Addisyn with d=128 and FIX=3 will give strings:
(A>, <n)(Ad>, <yn)(Add>, <syn)
Let's call each split's output (prefix, suffix). hashfeatures then converts both prefix and suffix to large integers P and S using hash. However, since we need a binary feature vector of d dimensions, hashfeatures takes the remainder of P and S with d, and sets the (P % d)-th and (S % d)-th dimensions of the feature vector to 1.
We define the hashfeatures function to output binary vectors, but they need not be binary; they can also have floating point values. In the Challenge section later in this assignment, you will be able to try your own name2features function to improve the model's performance.
def hashfeatures(baby, d, FIX, debug=False):
"""
Input:
baby: String representing the baby's name to be hashed
d: Number of dimensions to be in the feature vector
FIX: Number of chunks to extract and hash from each string
debug: Boolean for printing debug values (default False)
Output:
v: Feature vector representing the input string
"""
v = np.zeros(d)
for m in range(1, FIX + 1):
prefix = baby[:m] + ">"
P = hash(prefix) % d
v[P] = 1
suffix = "<" + baby[-m:]
S = hash(suffix) % d
v[S] = 1
if debug:
print(f"Split {m}/{FIX}:\t({prefix}, {suffix}),\t1s at indices [{P}, {S}]")
if debug:
print(f"Feature vector for {baby}:\n{v.astype(int)}\n")
return v
Changing hashfeatures arguments¶
Changing d¶
It is likely that different strings get hashed to different numbers, but trigger the same dimension in the feature vector to be 1, thus causing collisions. This is because the length of our feature vector d is generally much smaller than the magnitudes of hash outputs. We can reduce the number of collisions by increasing d and reducing the likelihood of P % d or S % d for different strings being equal. If FIX is left unchanged, then short baby names will trigger fewer dimensions of this longer feature vector, resulting in sparsity. Although the resulting vectors are more expressive, we will likely face the curse of dimensionality if we carelessly increase d. Moreover, if the model is also expressive enough, expressive feature vectors often result in model overfitting: model not generalizing well to unseen test data because it fits training data almost too well.
On the other hand, reducing d causes the number of collisions to generally increase by increasing the likelihood of P % d or S % d of different strings to be equal. This creates dense vectors that are not very expressive (feature vectors for different baby names will start having 1s in the same dimensions as d decreases). When feature vectors are not very expressive, it becomes difficult for models to learn classification boundaries between different classes, causing model underfitting: model not generalizing well to unseen test data because it cannot learn decision boundaries effectively.
Changing FIX¶
On the lines of overfitting and underfitting, take some time and think what the effect of changing FIX will be on feature vector density, and possibly model performance down-the-road.
In the trivial case, we do not want FIX to be very large. If FIX is larger than the length of baby name, then we will be running the loop in hashfeatures for extra iterations but computing the same prefixes and suffixes (running Max with FIX=5 will give (Max>, <Max) for iterations m=3 onwards.
The non-trivial case is when FIX is generally smaller than lengths of most baby names. FIX=1 will only split once and give sparse feature vectors if d is reasonably large, whereas FIX=5 will split 5 times and give denser vectors.
Let's test hashfeatures on a few examples, varying baby, d, and FIX.
v = hashfeatures("Addisyn", d=128, FIX=3, debug=True)
v = hashfeatures("Addisyn", d=4, FIX=3, debug=True)
v = hashfeatures("Addisyn", d=128, FIX=7, debug=True)
v = hashfeatures("Max", d=128, FIX=4, debug=True)
Split 1/3: (A>, <n), 1s at indices [28, 57] Split 2/3: (Ad>, <yn), 1s at indices [1, 73] Split 3/3: (Add>, <syn), 1s at indices [33, 93] Feature vector for Addisyn: [0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Split 1/3: (A>, <n), 1s at indices [0, 1] Split 2/3: (Ad>, <yn), 1s at indices [1, 1] Split 3/3: (Add>, <syn), 1s at indices [1, 1] Feature vector for Addisyn: [1 1 0 0] Split 1/7: (A>, <n), 1s at indices [28, 57] Split 2/7: (Ad>, <yn), 1s at indices [1, 73] Split 3/7: (Add>, <syn), 1s at indices [33, 93] Split 4/7: (Addi>, <isyn), 1s at indices [32, 32] Split 5/7: (Addis>, <disyn), 1s at indices [29, 111] Split 6/7: (Addisy>, <ddisyn), 1s at indices [76, 10] Split 7/7: (Addisyn>, <Addisyn), 1s at indices [52, 100] Feature vector for Addisyn: [0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Split 1/4: (M>, <x), 1s at indices [112, 35] Split 2/4: (Ma>, <ax), 1s at indices [54, 82] Split 3/4: (Max>, <Max), 1s at indices [90, 52] Split 4/4: (Max>, <Max), 1s at indices [90, 52] Feature vector for Max: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
The key takeaway here is that the feature extraction process is highly tunable and will almost always impact model performance. While you may sometimes be able to manually select key features by perusing training data, it is often good practice to run multiple experiments with different approaches to define the set of features.
def name2features(filename, d=128, FIX=3, LoadFile=True, debug=False):
"""
Output:
X : n feature vectors of dimension d, (nxd)
"""
# Read in baby names
if LoadFile:
with open(filename) as f:
babynames = [x.rstrip() for x in f.readlines() if len(x) > 0]
else:
babynames = filename.split("\n")
n = len(babynames)
X = np.zeros((n, d))
for i in range(n):
X[i, :] = hashfeatures(babynames[i], d, FIX)
return (X, babynames) if debug else X
In the code cell above, name2features reads every name in the given file and converts it into a 128-dimensional feature vector by first assembling substrings (based on the parameter FIX), then hashing these assembled substrings and modifying the feature vector index (the modulo of the number of dimensions d) that corresponds to this hash value.
More often than not, having a good understanding of the training data can help in training a good Machine Learning model. Let's check out the feature matrix visually. On the vertical axis are baby names, and on the horizontal axis are features for each baby name. The heatmap is white when the feature value is 1 and black otherwise.
You will notice that certain feature indices are white for many baby names. What could be the reason?
Xboys, namesBoys = name2features("boys.train", d=128, FIX=3, debug=True)
Xgirls, namesGirls = name2features("girls.train", d=128, FIX=3, debug=True)
X = np.concatenate([Xboys[:20], Xgirls[:20]], axis=0)
plt.figure(figsize=(12, 8))
ax = sns.heatmap(X.astype(int), cbar=False)
ax.set_xlabel("Feature Indices", fontsize=12)
ax.set_ylabel("Baby Names", fontsize=12)
ticks = ax.set_yticks(np.arange(40, dtype=int))
ticklabels = ax.set_yticklabels(namesBoys[:20] + namesGirls[:20])
plt.show()
The genTrainFeatures Function¶
We have provided you with a python function genTrainFeatures, which transforms the names into features and loads them into memory.
def genTrainFeatures(dimension=128):
"""
Input:
dimension: Desired dimension of the features
Output:
X: n feature vectors of dimensionality d (nxd)
Y: n labels (-1 = girl, +1 = boy) (n)
"""
# Load in the data
Xgirls = name2features("girls.train", d=dimension)
Xboys = name2features("boys.train", d=dimension)
X = np.concatenate([Xgirls, Xboys])
# Generate labels
Y = np.concatenate([-np.ones(len(Xgirls)), np.ones(len(Xboys))])
# Shuffle data into random order
ii = np.random.permutation([i for i in range(len(Y))])
return X[ii, :], Y[ii]
You can call the following command to return two vectors, one holding all the concatenated feature vectors and one holding the labels of all boys and girls names.
X, Y = genTrainFeatures(128)
print(f"Shape of training data: {X.shape}")
print(f"X:\n{X.astype(int)}")
print(f"Y:\n{Y.astype(int)}")
Shape of training data: (1200, 128) X: [[0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] ... [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0]] Y: [ 1 1 -1 ... 1 1 -1]
The Naïve Bayes Classifier¶
The Naïve Bayes classifier is a linear classifier based on Bayes Rule. The following cells will walk you through steps and ask you to finish the necessary functions in a pre-defined order. As a general rule, you should avoid tight loops at all costs.
Part One: Class Probability [Graded]¶
Estimate the class probabilities $P(y=1)$ and $P(y=-1)$ in naivebayesPY. This should return the probability that a sample in the training set is positive or negative, independent of its features. The output of naivebayesPY should be a list of the form $[P(y=1), P(y=-1)]$.
def naivebayesPY(X, Y):
"""
naivebayesPY(X, Y) returns [pos,neg]
Computation of P(Y)
Input:
X : n input vectors of d dimensions (nxd)
Y : n labels (-1 or +1) (nx1)
Output:
pos: probability p(y=1)
neg: probability p(y=-1)
"""
# Add one positive and negative example to avoid division by zero ("plus-one smoothing")
Y = np.concatenate([Y, [-1, 1]])
n = len(Y)
# YOUR CODE HERE
pos = np.sum(Y == 1) / n
neg = np.sum(Y== -1) /n
# END OF YOUR CODE
return pos, neg
Run the next cell to check that the probabilities returned by your naivebayesPY function sum to 1 (naivebayesPY_test1) and return the correct probabilities for a given set of input vectors (naivebayesPY_test2 through naivebayesPY_test4).
def naivebayesPY_test1():
"""
Check that probabilities sum to 1
"""
pos, neg = naivebayesPY(X, Y)
return np.linalg.norm(pos + neg - 1) < 1e-5
def naivebayesPY_test2():
"""
Test the naivebayesPY function on a simple example
"""
x = np.array([[0, 1], [1, 0]])
y = np.array([-1, 1])
pos, neg = naivebayesPY(x, y)
pos0, neg0 = 0.5, 0.5
test = np.linalg.norm(pos - pos0) + np.linalg.norm(neg - neg0)
return test < 1e-5
def naivebayesPY_test3():
"""
Test the naivebayesPY function on another example
"""
x = np.array(
[
[0, 1, 1, 0, 1],
[1, 0, 0, 1, 0],
[1, 1, 1, 1, 0],
[0, 1, 1, 0, 1],
[1, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[1, 1, 1, 0, 1],
]
)
y = np.array([1, -1, 1, 1, -1, -1, 1])
pos, neg = naivebayesPY(x, y)
pos0, neg0 = 5 / 9.0, 4 / 9.0
test = np.linalg.norm(pos - pos0) + np.linalg.norm(neg - neg0)
return test < 1e-5
def naivebayesPY_test4():
"""
Test plus-one smoothing
"""
x = np.array([[0, 1, 1, 0, 1], [1, 0, 0, 1, 0]])
y = np.array([1, 1])
pos, neg = naivebayesPY(x, y)
pos0, neg0 = 3 / 4.0, 1 / 4.0
test = np.linalg.norm(pos - pos0) + np.linalg.norm(neg - neg0)
return test < 1e-5
runtest(naivebayesPY_test1, "naivebayesPY_test1")
runtest(naivebayesPY_test2, "naivebayesPY_test2")
runtest(naivebayesPY_test3, "naivebayesPY_test3")
runtest(naivebayesPY_test4, "naivebayesPY_test4")
Running Test: naivebayesPY_test1 ... ✔ Passed! Running Test: naivebayesPY_test2 ... ✔ Passed! Running Test: naivebayesPY_test3 ... ✔ Passed! Running Test: naivebayesPY_test4 ... ✔ Passed!
Skip over the auto-graded test cells below (see Evaluation for details).
# Auto-graded test cell worth one point (naivebayesPY_test1)
# Auto-graded test cell worth one point (naivebayesPY_test2)
# Auto-graded test cell worth one point (naivebayesPY_test3)
# Auto-graded test cell worth one point (naivebayesPY_test4)
Part Two: Conditional Probability [Graded]¶
Estimate the conditional probabilities $P([\mathbf{x}]_{\alpha} = 1 | y = 1)$ and $P([\mathbf{x}]_{\alpha} = 1 | y = -1)$ in
naivebayesPXY. Notice that by construction, our features are binary categorical features. Use a categorical distribution as model and return the probability vectors for each feature being 1 given a class label. Note that the result will be two vectors of length d (the number of features), where the values represent the probability that feature $\alpha$ is equal to 1.
Here we compute the fraction of counts that a feature is hot or not (i.e., $[\mathbf{x}]_{\alpha} = 1$ or $[\mathbf{x}]_{\alpha} = 0$) conditioned on gender. For example, if $[\mathbf{x}]_1 = [1, 0, 1, 0, 1]$ and $y = [1, 1, 1, 1, -1]$, where "boy" corresponds to the label $y=1$ and "girl" corresponds to the label $y=-1$, then
$$ P([\mathbf{x}]_1 = 1 | y = 1) = \frac{1 + 0 + 1 + 0}{4} = 0.5 \quad \text{and} \quad P([\mathbf{x}]_1 = 1 | y = -1) = \frac{1}{1} = 1 $$
You need to compute this for each dimension 0 <= alpha < d for each gender.
def naivebayesPXY(X, Y):
"""
naivebayesPXY(X, Y) returns [posprob,negprob]
Input:
X : n input vectors of d dimensions (nxd)
Y : n labels (-1 or +1) (n)
Output:
posprob: probability vector of p(x_alpha = 1|y=1) (d)
negprob: probability vector of p(x_alpha = 1|y=-1) (d)
"""
# Add one positive and negative example to avoid division by zero ("plus-one smoothing")
n, d = X.shape
X = np.concatenate([X, np.ones((2, d)), np.zeros((2, d))])
Y = np.concatenate([Y, [-1, 1, -1, 1]])
# YOUR CODE HERE
pos = X[Y == 1]
neg = X[Y == -1]
posprob = np.mean(pos, axis=0)
negprob = np.mean(neg, axis=0)
return posprob, negprob
# END OF YOUR CODE
We can plot the positive and negative probabilities for each feature. You might notice some features having higher conditional probabilities given gender (spikes of one color but low probability of the other color). This could imply that those features are particularly "indicative" in the baby-name classification task. The Naïve Bayes classifier will help us flip the conditional probability $P(\mathbf{x}|y)$ to get $P(y|\mathbf{x})$.
X, Y = genTrainFeatures(128)
posprob, negprob = naivebayesPXY(X, Y)
probs = pd.DataFrame(
{"feature": np.arange(128, dtype=int), "boys": posprob, "girls": negprob}
)
plt.figure(figsize=(12, 4))
ax = sns.lineplot(
x="feature", y="value", hue="variable", data=pd.melt(probs, ["feature"])
)
ax.set_xlabel("Feature Indices", fontsize=12)
ax.set_ylabel("Probability", fontsize=12)
plt.show()
Run the next cell to check that your implementation of naivebayesPXY returns the same posterior probabilities as the correct implementation, in the correct dimensions.
def naivebayesPXY_test1():
"""
Test a simple toy example with two points (one positive, one negative)
"""
x = np.array([[0, 1], [1, 0]])
y = np.array([-1, 1])
pos, neg = naivebayesPXY(x, y)
pos0, neg0 = naivebayesPXY_grader(x, y)
test = np.linalg.norm(pos - pos0) + np.linalg.norm(neg - neg0)
return test < 1e-5
def naivebayesPXY_test2():
"""
Test the probabilities P(X|Y=+1)
"""
pos, neg = naivebayesPXY(X, Y)
posprobXY, negprobXY = naivebayesPXY_grader(X, Y)
test = np.linalg.norm(pos - posprobXY)
return test < 1e-5
def naivebayesPXY_test3():
"""
Test the probabilities P(X|Y=-1)
"""
pos, neg = naivebayesPXY(X, Y)
posprobXY, negprobXY = naivebayesPXY_grader(X, Y)
test = np.linalg.norm(neg - negprobXY)
return test < 1e-5
def naivebayesPXY_test4():
"""
Check that the dimensions of the posterior probabilities are correct
"""
pos, neg = naivebayesPXY(X, Y)
posprobXY, negprobXY = naivebayesPXY_grader(X, Y)
return pos.shape == posprobXY.shape and neg.shape == negprobXY.shape
runtest(naivebayesPXY_test1, "naivebayesPXY_test1")
runtest(naivebayesPXY_test2, "naivebayesPXY_test2")
runtest(naivebayesPXY_test3, "naivebayesPXY_test3")
runtest(naivebayesPXY_test4, "naivebayesPXY_test4")
Running Test: naivebayesPXY_test1 ... ✔ Passed! Running Test: naivebayesPXY_test2 ... ✔ Passed! Running Test: naivebayesPXY_test3 ... ✔ Passed! Running Test: naivebayesPXY_test4 ... ✔ Passed!
Skip over the auto-graded test cells below (see Evaluation for details).
# Auto-graded test cell worth one point (naivebayesPXY_test1)
# Auto-graded test cell worth one point (naivebayesPXY_test2)
# Auto-graded test cell worth one point (naivebayesPXY_test3)
# Auto-graded test cell worth one point (naivebayesPXY_test4)
Part Three: Log Likelihood [Graded]¶
Calculate the log likelihoods $\log P(\mathbf{x}|y = 1)$ and $\log P(\mathbf{x}|y = -1)$ for each point in X_test given label Y_test in loglikelihood.
Recall¶
- Naïve Bayes assumption: the likelihood $P(\mathbf{x} | y = c)$ of a data point $\mathbf{x}$ is equal to the product of the conditional probabilities of each feature $[\mathbf{x}]_\alpha$ having value $x_\alpha$, i.e.,
$$ P(\mathbf{x} | y = c) = \prod_{\alpha=1}^d P([\mathbf{x}]_\alpha = x_\alpha | y = c) $$
For example, with $\mathbf{x} = [1, 0, 1]$ and corresponding label $y=1$, you will calculate likelihood $P(\mathbf{x} | y = 1)$ as the product
$$ P([\mathbf{x}]_1 = 1 | y = 1) \cdot P([\mathbf{x}]_2 = 0 | y = 1) \cdot P([\mathbf{x}]_3 = 1 | y = 1) $$
Given probabilities:
posprobvector has entries $P([\mathbf{x}]_\alpha = 1 | y = 1)$negprobvector has entries $P([\mathbf{x}]_\alpha = 1 | y = -1)$
Useful fact to simplify your calculations: $\log(ab) = \log(a) + \log(b)$
To simplify your code, we recommend calculating log likelihoods for positive points ($\mathbf{x}$ with $y = 1$) and those for negative points ($\mathbf{x}$ with $y = -1$) separately.
def loglikelihood(posprob, negprob, X_test, Y_test):
"""
Function: loglikelihood(posprob, negprob, X_test, Y_test)
Returns: Log-likelihood of each point in X_test
Input:
posprob: Conditional probabilities for the positive class (d)
negprob: Conditional probabilities for the negative class (d)
X_test: Features (nxd)
Y_test: Labels (-1 or +1) (n)
Output:
loglikelihood: Log-likelihood of each point in X_test (n)
"""
n, d = X_test.shape
loglikelihood = np.zeros(n)
# YOUR CODE HERE
pos = (Y_test == 1)
neg = (Y_test == -1)
loglikelihood[pos] = np.sum(X_test[pos] * np.log(posprob) + (1 - X_test[pos]) * np.log(1-posprob), axis=1)
loglikelihood[neg] = np.sum(X_test[neg] * np.log(negprob) + (1 - X_test[neg]) * np.log(1-negprob), axis=1)
# END OF YOUR CODE
return loglikelihood
Run the next cell to check that your implementation of loglikelihood returns the same values as the correct implementation for three different datasets.
X, Y = genTrainFeatures(128)
posprob, negprob = naivebayesPXY_grader(X, Y)
def loglikelihood_test1():
"""
Test if the log-likelihood of the training data are all negative
"""
ll = loglikelihood(posprob, negprob, X, Y)
return all(ll < 0)
def loglikelihood_test2():
"""
Test if the log-likelihood of the training data matches the solution
"""
ll = loglikelihood(posprob, negprob, X, Y)
llgrader = loglikelihood_grader(posprob, negprob, X, Y)
return np.linalg.norm(ll - llgrader) < 1e-5
def loglikelihood_test3():
"""
Test if the log-likelihood of the training data matches the solution
(positive points only)
"""
ll = loglikelihood(posprob, negprob, X, Y)
llgrader = loglikelihood_grader(posprob, negprob, X, Y)
return np.linalg.norm(ll[Y == 1] - llgrader[Y == 1]) < 1e-5
def loglikelihood_test4():
"""
Test if the log-likelihood of the training data matches the solution
(negative points only)
"""
ll = loglikelihood(posprob, negprob, X, Y)
llgrader = loglikelihood_grader(posprob, negprob, X, Y)
return np.linalg.norm(ll[Y == -1] - llgrader[Y == -1]) < 1e-5
def loglikelihood_test5():
"""
Little toy example with two data points (1 positive, 1 negative)
"""
x = np.array([[0, 1], [1, 0]])
y = np.array([-1, 1])
posprobXY, negprobXY = naivebayesPXY_grader(X, Y)
loglike = loglikelihood(posprobXY[:2], negprobXY[:2], x, y)
loglike0 = loglikelihood_grader(posprobXY[:2], negprobXY[:2], x, y)
test = np.linalg.norm(loglike - loglike0)
return test < 1e-5
def loglikelihood_test6():
"""
Little toy example with four data points (2 positive, 2 negative)
"""
x = np.array(
[[1, 0, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1], [1, 0, 0, 1, 1, 1], [1, 1, 0, 0, 1, 1]]
)
y = np.array([-1, 1, 1, -1])
posprobXY, negprobXY = naivebayesPXY_grader(X, Y)
loglike = loglikelihood(posprobXY[:6], negprobXY[:6], x, y)
loglike0 = loglikelihood_grader(posprobXY[:6], negprobXY[:6], x, y)
test = np.linalg.norm(loglike - loglike0)
return test < 1e-5
def loglikelihood_test7():
"""
One more toy example with 5 positive and 2 negative points
"""
x = np.array(
[
[1, 1, 1, 1, 1, 1],
[0, 0, 1, 0, 0, 0],
[1, 1, 0, 1, 1, 1],
[0, 1, 0, 0, 0, 1],
[0, 1, 1, 0, 1, 1],
[1, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 1, 1],
]
)
y = np.array([1, 1, 1, 1, -1, -1, 1])
posprobXY, negprobXY = naivebayesPXY_grader(X, Y)
loglike = loglikelihood(posprobXY[:6], negprobXY[:6], x, y)
loglike0 = loglikelihood_grader(posprobXY[:6], negprobXY[:6], x, y)
test = np.linalg.norm(loglike - loglike0)
return test < 1e-5
runtest(
loglikelihood_test1,
"loglikelihood_test1 (all log-likelihoods must be negative)",
)
runtest(loglikelihood_test2, "loglikelihood_test2 (training data)")
runtest(loglikelihood_test3, "loglikelihood_test3 (positive points)")
runtest(loglikelihood_test4, "loglikelihood_test4 (negative points)")
runtest(loglikelihood_test5, "loglikelihood_test5")
runtest(loglikelihood_test6, "loglikelihood_test6")
runtest(loglikelihood_test7, "loglikelihood_test7")
Running Test: loglikelihood_test1 (all log-likelihoods must be negative) ... ✔ Passed! Running Test: loglikelihood_test2 (training data) ... ✔ Passed! Running Test: loglikelihood_test3 (positive points) ... ✔ Passed! Running Test: loglikelihood_test4 (negative points) ... ✔ Passed! Running Test: loglikelihood_test5 ... ✔ Passed! Running Test: loglikelihood_test6 ... ✔ Passed! Running Test: loglikelihood_test7 ... ✔ Passed!
Skip over the auto-graded test cells below (see Evaluation for details).
# Auto-graded test cell worth one point (loglikelihood_test1)
# Auto-graded test cell worth one point (loglikelihood_test1)
# Auto-graded test cell worth one point (loglikelihood_test3)
# Auto-graded test cell worth one point (loglikelihood_test4)
# Auto-graded test cell worth one point (loglikelihood_test5)
# Auto-graded test cell worth one point (loglikelihood_test6)
# Auto-graded test cell worth one point (loglikelihood_test7)
Part Four: Naïve Bayes Prediction [Graded]¶
For a given test point input $\mathbf{x}_{\text{test}}$, we classify it as positive if the log ratio
$$ \log\left(\frac{P(y=1 | \mathbf{x}_{\text{test}})}{P(y=-1|\mathbf{x}_{\text{test}})}\right) $$
is positive and negative otherwise. That is,
$$ h(\mathbf{x}_{\text{test}}) = \begin{cases} 1 & \text{if } \log\left(\frac{P(y=1 | \mathbf{x}_{\text{test}})}{P(y=-1|\mathbf{x}_{\text{test}})}\right) > 0 \\[5pt] -1 & \text{if } \log\left(\frac{P(y=1 | \mathbf{x}_{\text{test}})}{P(y=-1|\mathbf{x}_{\text{test}})}\right) \leq 0 \end{cases} $$
Implement naivebayes_pred by first calculating the log ratio for each test point in the matrix X_test using Bayes' Rule and predict the label of the test points by looking at the log ratio.
Recall¶
- Bayes' Rule:
$$ P(y = c | \mathbf{x}_{\text{test}}) = \frac{ P(\mathbf{x}_{\text{test}} | y = c) \cdot P(y = c) }{ P(\mathbf{x}_{\text{test}}) } $$
Note that Bayes' Rule can be stated in a more useful form for our purposes:
$$ \underbrace{P(y = c | \mathbf{x}_{\text{test}})}_\text{posterior} \propto \underbrace{P(\mathbf{x}_{\text{test}} | y = c)}_\text{likelihood} \cdot \underbrace{P(y = c)}_\text{prior} $$
Here, $\propto$ is the proportionality symbol. Proportionality applies because we have dropped the denominator $P(\mathbf{x}_{\text{test}})$, which is just a multiplicative constant when finding $y$ that maximixes the posterior.
Given probabilities:
pos: $P(y = 1)$neg: $P(y = -1)$posprobvector has entries $P([\mathbf{x}]_\alpha = 1 | y = 1)$negprobvector has entries $P([\mathbf{x}]_\alpha = 1 | y = -1)$
loglikelihoodfunction you just implemented.Useful facts to simplify your calculations: $\log(ab) = \log(a) + \log(b)$ and $\log\left(\frac{a}{b}\right) = \log(a) - \log(b)$
def naivebayes_pred(pos, neg, posprob, negprob, X_test):
"""
Function: naivebayes_pred(pos, neg, posprob, negprob, X_test)
Returns: The prediction of each point in X_test
Input:
pos: Class probability for the negative class
neg: Class probability for the positive class
posprob: Conditional probabilities for the positive class (d)
negprob: Conditional probabilities for the negative class (d)
X_test: Features (nxd)
Output:
preds: Prediction of each point in X_test (n)
"""
n, d = X_test.shape
preds = np.empty(n)
# YOUR CODE HERE
pos_info = np.ones(n)
neg_info = -np.ones(n)
log_pos = loglikelihood(posprob, negprob, X_test, pos_info)
log_neg = loglikelihood(posprob, negprob, X_test, neg_info)
log_pos += np.log(pos)
log_neg += np.log(neg)
preds = np.where(log_pos > log_neg, 1, -1)
# END OF YOUR CODE
return preds
Run the next cell to check that your implementation of naivebayes_pred returns only 1 and -1 (naivebayes_pred_test1), and that it returns the same predicted values as the correct implementation for three different datasets (naivebayes_pred_test2 through naivebayes_pred_test4).
X, Y = genTrainFeatures_grader(128)
posY, negY = naivebayesPY_grader(X, Y)
posprobXY, negprobXY = naivebayesPXY_grader(X, Y)
def naivebayes_pred_test1():
"""
Check whether the predictions are +1 or neg 1
"""
preds = naivebayes_pred(posY, negY, posprobXY, negprobXY, X)
return np.all(np.logical_or(preds == -1, preds == 1))
def naivebayes_pred_test2():
x_test = np.array([[0, 1], [1, 0]])
preds = naivebayes_pred_grader(posY, negY, posprobXY[:2], negprobXY[:2], x_test)
student_preds = naivebayes_pred(posY, negY, posprobXY[:2], negprobXY[:2], x_test)
acc = analyze_grader("acc", preds, student_preds)
return np.abs(acc - 1) < 1e-5
def naivebayes_pred_test3():
x_test = np.array(
[
[1, 0, 1, 0, 1, 1],
[0, 0, 1, 0, 1, 1],
[1, 0, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 1],
]
)
preds = naivebayes_pred_grader(posY, negY, posprobXY[:6], negprobXY[:6], x_test)
student_preds = naivebayes_pred(posY, negY, posprobXY[:6], negprobXY[:6], x_test)
acc = analyze_grader("acc", preds, student_preds)
return np.abs(acc - 1) < 1e-5
def naivebayes_pred_test4():
x_test = np.array(
[
[1, 1, 1, 1, 1, 1],
[0, 0, 1, 0, 0, 0],
[1, 1, 0, 1, 1, 1],
[0, 1, 0, 0, 0, 1],
[0, 1, 1, 0, 1, 1],
[1, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 1, 1],
]
)
preds = naivebayes_pred_grader(posY, negY, posprobXY[:6], negprobXY[:6], x_test)
student_preds = naivebayes_pred(posY, negY, posprobXY[:6], negprobXY[:6], x_test)
acc = analyze_grader("acc", preds, student_preds)
return np.abs(acc - 1) < 1e-5
runtest(naivebayes_pred_test1, "naivebayes_pred_test1")
runtest(naivebayes_pred_test2, "naivebayes_pred_test2")
runtest(naivebayes_pred_test3, "naivebayes_pred_test3")
runtest(naivebayes_pred_test4, "naivebayes_pred_test4")
Running Test: naivebayes_pred_test1 ... ✔ Passed! Running Test: naivebayes_pred_test2 ... ✔ Passed! Running Test: naivebayes_pred_test3 ... ✔ Passed! Running Test: naivebayes_pred_test4 ... ✔ Passed!
Skip over the auto-graded test cells below (see Evaluation for details).
# Auto-graded test cell worth one point (naivebayes_pred_test1)
# Auto-graded test cell worth one point (naivebayes_pred_test2)
# Auto-graded test cell worth one point (naivebayes_pred_test3)
# Auto-graded test cell worth one point (naivebayes_pred_test4)
You can now test your code with the following interactive name classification script.
NOTE: When you are ready to stop the baby name prompt and move on, press the Enter key while the name entry box is empty.
DIMS = 128
print("Loading data...")
X, Y = genTrainFeatures(DIMS)
print("Training classifier...")
pos, neg = naivebayesPY(X, Y)
posprob, negprob = naivebayesPXY(X, Y)
error = np.mean(naivebayes_pred(pos, neg, posprob, negprob, X) != Y)
print(f"Training error: {100 * error:.2f}%")
while True:
print("Please enter a baby name (press Enter key with empty box to stop prompt)>")
yourname = input()
if len(yourname) < 1:
break
xtest = name2features(yourname, d=DIMS, LoadFile=False)
pred = naivebayes_pred(pos, neg, posprob, negprob, xtest)
if pred > 0:
print(f"{yourname}, I am sure you are a baby boy.\n")
else:
print(f"{yourname}, I am sure you are a baby girl.\n")
Loading data... Training classifier... Training error: 23.17% Please enter a baby name (press Enter key with empty box to stop prompt)>
victor, I am sure you are a baby boy. Please enter a baby name (press Enter key with empty box to stop prompt)>
jen, I am sure you are a baby boy. Please enter a baby name (press Enter key with empty box to stop prompt)>
jenny, I am sure you are a baby girl. Please enter a baby name (press Enter key with empty box to stop prompt)>
alice, I am sure you are a baby boy. Please enter a baby name (press Enter key with empty box to stop prompt)>
samantha, I am sure you are a baby girl. Please enter a baby name (press Enter key with empty box to stop prompt)>
charley, I am sure you are a baby girl. Please enter a baby name (press Enter key with empty box to stop prompt)>
mike, I am sure you are a baby girl. Please enter a baby name (press Enter key with empty box to stop prompt)>
Challenge: Feature Extraction¶
Let's test how well your Naïve Bayes classifier performs on a secret test set. If you want to improve your classifier modify name2features2 below. The automatic reader will use your Python script to extract features and train your classifier on the same names training set by calling the function with only one argument--the name of a file containing a list of names. The given implementation is the same as the given name2features above.
From your experience, what features of a baby name would be predictive of the baby being a boy or a girl? You might hypothesize that the count of vowel sounds is indicative of a gender, in which case you could append binary feature is_vowel_count_gt_1 (greater than 1) or is_vowel_count_gt_2, etc.. Ideally, you would want to add features that help your model catch those pesky misclassified cases that existing hash features did not catch. So, it helps to investigate the misclassified baby names first. You might also consider ignoring hash features and instead using 5-10 amazing features that (maybe) give you very high accuracy on the test set. We do not know if such a set of features exists; it remains an open challenge.
def hashfeatures(baby, d, FIX):
"""
Input:
baby : a string representing the baby's name to be hashed
d: the number of dimensions to be in the feature vector
FIX: the number of chunks to extract and hash from each string
Output:
v: a feature vector representing the input string
"""
v = np.zeros(d)
for m in range(1, FIX + 1):
prefix = baby[:m] + ">"
P = hash(prefix) % d
v[P] = 1
suffix = "<" + baby[-m:]
S = hash(suffix) % d
v[S] = 1
return v
def name2features2(filename, d=128, FIX=3, LoadFile=True):
"""
Output:
X : n feature vectors of dimension d, (nxd)
"""
# read in baby names
if LoadFile:
with open(filename) as f:
babynames = [x.rstrip() for x in f.readlines() if len(x) > 0]
else:
babynames = filename.split("\n")
n = len(babynames)
nu_nu = 29
X = np.zeros((n, d+nu_nu))
for i in range(n):
X[i, :] = hashfeatures(babynames[i], d+nu_nu, FIX)
# YOUR CODE HERE
FIX = 2
X[i, :] = hashfeatures(babynames[i][-3:], d+nu_nu, FIX)
if babynames[i].lower().endswith("ke"):
X[i,d+1] = 0
else:
X[i,d+1] = 1
if "ee" in babynames[i].lower():
X[i,d+2] = 1
else:
X[i,d+2] = 0
if babynames[i].lower().endswith("a"):
X[i,d+3] = 1
else:
X[i,d+3] = 0
if babynames[i].lower().endswith("y"):
X[i,d+4] = 1
else:
X[i,d+4] = 0
if babynames[i].lower().endswith("ie"):
X[i,d+5] = 1
else:
X[i,d+5] = 0
if babynames[i].lower().endswith("ia"):
X[i,d+6] = 1
else:
X[i,d+6] = 0
if babynames[i].lower().endswith("na"):
X[i,d+7] = 1
else:
X[i,d+7] = 0
if babynames[i].lower().endswith("n"):
X[i,d+8] = 0
else:
X[i,d+8] = 1
if babynames[i].lower().endswith("r"):
X[i,d+9] = 0
else:
X[i,d+9] = 1
if babynames[i].lower().endswith == "ke":
X[i,d+10] = 0
else:
X[i,d+10] = 1
if "nn" in babynames[i].lower():
X[i,d+11] = 1
else:
X[i,d+11] = 0
if "ee" in babynames[i].lower():
X[i,d+12] = 1
else:
X[i,d+15] = 0
if "ss" in babynames[i].lower():
X[i,d+16] = 1
else:
X[i,d+16] = 0
if babynames[i].lower().endswith("ly"):
X[i,d+17] = 1
else:
X[i,d+17] = 0
if babynames[i].lower().endswith("yn"):
X[i,d+18] = 1
else:
X[i,d+18] = 0
if babynames[i].lower().startswith("lil"):
X[i,d+22] = 1
else:
X[i,d+22] = 0
if babynames[i].lower()[1:3] == "va":
X[i,d+23] = 1
else:
X[i,d+23] = 0
if babynames[i].lower().startswith("ben"):
X[i,d+24] = 0
else:
X[i,d+24] = 1
if babynames[i].lower().startswith("tim"):
X[i,d+25] = 0
else:
X[i,d+25] = 1
if babynames[i].lower().endswith("son"):
X[i,d+26] = 0
else:
X[i,d+26] = 1
if babynames[i].lower().startswith("sen"):
X[i,d+27] = 0
else:
X[i,d+27] = 1
if babynames[i].lower().startswith("us"):
X[i,d+28] = 0
else:
X[i,d+28] = 1
# END OF YOUR CODE
return X
Run the following cell to test your implementation of name2features2.
boy_train_file = "boys.train"
girl_train_file = "girls.train"
boy_test_file = "boys.test"
girl_test_file = "girls.test"
def genTrainFeatures_comp(g=girl_train_file, b=boy_train_file):
with open(b) as f:
boysList = [x.rstrip() for x in f.readlines() if len(x) > 0]
with open(g) as f:
girlsList = [x.rstrip() for x in f.readlines() if len(x) > 0]
xTrStr = np.concatenate([girlsList, boysList])
yTr = np.concatenate([-np.ones(len(girlsList)), np.ones(len(boysList))])
ii = np.random.permutation([i for i in range(len(yTr))])
xTrStr = xTrStr[ii]
yTr = yTr[ii]
with open("shuffled.test", "w") as f:
for name in xTrStr:
f.write(f"{name}\n")
return name2features2("shuffled.test"), yTr
def competition_test():
XTr, YTr = genTrainFeatures_comp()
pos, neg = naivebayesPY_grader(XTr, YTr)
posprob, negprob = naivebayesPXY_grader(XTr, YTr)
XTe, YTe = genTrainFeatures_comp(g=girl_test_file, b=boy_test_file)
preds = naivebayes_pred(pos, neg, posprob, negprob, XTe)
return analyze_grader("acc", YTe, preds)
print(f"The accuracy of your features on the test set is {competition_test()*100:.2f}%")
The accuracy of your features on the test set is 80.90%
HINT: You should be able to get more than 80% accuracy just by changing some of the default arguments in the function. If you'd like to try something more sophisticated, you can add to name2features2.
Credits¶
The name classification idea originates from Nick Montfort.