Due: Tuesday, Oct. 27, midnight
Okay, folks, it’s time for our second Kaggle competition! Note that as with Mushroom Madness, you’ll need to get the link from the Canvas announcement to join this private competition.
You will receive a training data set containing first names, together with information about whether each name is traditionally associated with a male or female person. You will also receive a test data set containing names whose classifications are not revealed to you.
Your job is to build a model that estimates:
\[ P(\text{name is female}) \]
for every name in the test set.
You will then submit those probabilities to Kaggle. Kaggle will compare your predictions with the hidden answers and give you a score.
Lower scores are better.
You may compete individually or in a team of two. (In the latter case, both students will earn identical scores.)
(Read the “Getting Started” section of the Mushroom Madness homework if you didn’t do that assignment.)
After you have joined the competition, download its files from the command line:
kaggle competitions download -c data-419-whats-in-a-nameThis will download a ZIP archive.
Unpack it:
unzip data-419-whats-in-a-name.zipYou should obtain three participant-facing files:
train.csv
test.csv
sample_submission.csv
The data consist of first names traditionally associated with males or females. The collection includes both real-world names and fictional character names drawn from literature, television, and other sources.
Each row represents one name.
The columns are:
| Column | Type | Meaning |
|---|---|---|
id |
identifier | arbitrary ID number for the observation |
name |
string | first name of a person or fictional character |
female |
target | 1 = female, 0 = male |
The female column appears in train.csv.
The female column does not appear in
test.csv.
The id column is used to identify observations and match
predictions to the correct names. Do not treat it as a predictive
feature.
Unlike Mushroom Madness, this data set provides only one actual predictor: the name itself.
This means that you’ll need to invent your own features!
For example, you might investigate whether the length of a name, its first or last letter, or particular combinations of letters are useful predictors of whether the name is male or female.
The goal is not to memorize particular names. It is to discover patterns that generalize to names your model has never encountered before.
Before you fit any model whatsoever, make sure that you can successfully submit something to Kaggle.
For your first submission, just stupidly predict:
\[ P(\text{female}) = 0.5 \]
for every name in the test set. To do this, construct your own
submission.csv file using test.csv. For
example:
import pandas as pd
test = pd.read_csv("test.csv")
submission = pd.DataFrame({
"id": test["id"],
"female": 0.5,
})
submission.to_csv("submission.csv", index=False)Your file should have exactly two columns:
id,female
and exactly one row for every name in test.csv.
The IDs must correspond to the correct names.
Do not accidentally write the DataFrame index into the file.
From the command line:
kaggle competitions submit \
-c data-419-whats-in-a-name \
-f submission.csv \
-m "stupid 0.5 baseline"Kaggle should tell you that the submission was accepted.
Then visit the competition web page and look at your submission / leaderboard score.
A model that predicts .5 for every observation should
obtain a log loss of approximately:
\[ 0.69315 \]
If you get approximately that score, congratulations: your submission pipeline works.
This is not an impressive machine-learning accomplishment, but it is a plumbing accomplishment. And plumbing matters.
Our competition uses binary cross-entropy loss \(L_CE\), also called log-loss.
For name \(i\),
The competition score is:
\[ L_{\textrm{CE}} = -\frac{1}{n} \sum_{i=1}^{n} \left[ y_i\log(p_i) + (1-y_i)\log(1-p_i) \right]. \]
Lower is better.
A perfect model approaches 0.
A model that says .5 for everything gets about
.69315.
Log loss rewards models that assign high probability to the correct outcome, but it also punishes unjustified confidence.
For example, if a name is actually female:
.55 is timid but not disastrous;.95 is excellent;.00001 is the statistical equivalent of
confidently insisting that Hermione is a man’s name.This is why you must submit probabilities, not merely class labels.
Duh. Take a looksie at train.csv to see what you’re up
against. Browse through the names and mull this over: “what sorts of
things make me think Melodia is a female name, but
Rock is a male name?”
Okay, now improve on the .5 baseline.
For this homework, your submitted predictions must come from either a logistic regression model or a nearest neighbors model (for any value of \(k\)).
Your basic workflow should look something like:
train.csv.name predictor from
female.test.csv.predict_proba() to estimate (P()).submission.csv.This is the heart of the assignment.
In Mushroom Madness, the dataset already supplied useful numeric and categorical predictors.
Here, you start with a string.
Your job is to transform that string into features that a logistic regression or nearest neighbors model can use.
Some possibilities:
These are merely suggestions. Feel free to invent your own.
Remember that your ultimate goal is to find patterns that predict gender, not simply to come up with the largest possible number of features.
Some engineered features will naturally be numeric.
For example:
name_length
num_vowels
proportion_vowels
Others will be categorical.
For example:
first_letter
last_letter
Still others might be binary indicators.
For example:
ends_in_a
contains_th
starts_with_m
Think about how each type of feature should be represented for your model.
You may want to use:
StandardScaler for numeric features;OneHotEncoder for categorical features;ColumnTransformer to process different types of
features;Pipeline to organize the complete modeling
process.You may also find CountVectorizer or other
text-processing tools useful for constructing features from character
sequences.
Whatever preprocessing you perform on the training data must also be applied consistently to the test data.
Suppose:
model.classes_is:
[0 1]
Then:
model.predict_proba(X)returns two probability columns:
P(y=0) P(y=1)
For this competition:
0 = male
1 = female
Therefore, what Kaggle wants in the female column
is:
model.predict_proba(X_test)[:, 1]That is:
\[ P(y=1)=P(\text{female}) \]
Do not submit model.predict().
That gives hard 0/1 class predictions, and the competition is explicitly asking for probabilities.
The leaderboard is not asking you to perform sorcery.
Start simple and proceed systematically.
Some reasonable experiments include:
For example, try predicting gender using only the last letter of a name.
How much better than .5 can you get?
Try including the first letter, name length, or vowel count.
Do these actually improve predictive performance?
Perhaps the last two letters are more informative than the last one.
Or perhaps certain combinations of letters appearing anywhere in a name are useful.
Maybe including quadratic/cubic terms and/or interaction terms would help?
More predictors do not automatically mean a better model on unseen data.
Logistic regression supports regularization, which
can be especially useful when you generate a large number of features.
You can control this using parameters to the LogisticRegression
class:
C controls the strength of
regularization. Counterintuitively, smaller values mean stronger
regularization. The default is C=1.l1_ratio controls the type of
regularization:
0 means pure ridge (L2) regularization;1 means pure lasso (L1) regularization;Note that not every choice of solver supports every type
of regularization. The saga solver supports all three.
Try different values of these parameters and use cross-validation to determine which choices perform best on unseen data.
Cross-validation is much better evidence than “I submitted it to Kaggle and the number moved slightly.”
Look at coefficients, predicted probabilities, and the distribution of predictions.
Which features seem particularly associated with male or female names?
This competition allows 5 submissions per team per day.
After each submission, the Kaggle CLI will tell you how many submissions remain for that day.
Use them thoughtfully.
You do not need to submit every microscopic variation of your code.
A reasonable workflow is:
If you are working in a pair, the submission limit belongs to the team.
After fitting your final candidate model:
p_female = model.predict_proba(X_test)[:, 1]create a DataFrame containing:
id
female
For example:
submission = pd.DataFrame({
"id": test["id"],
"female": p_female,
})
submission.to_csv("submission.csv", index=False)Before submitting it, inspect it.
For example:
print(submission.head())
print(submission.shape)It should:
test.csv;id and female
columns;Then submit it:
kaggle competitions submit \
-c data-419-whats-in-a-name \
-f submission.csv \
-m "brief description of this model"Use a useful submission message.
For example:
last letter only
or:
character bigrams with logistic regression
is more informative than:
asdf
Future You will appreciate Current You naming your attempts sensibly.
After Kaggle processes the submission, go to the competition web site and look at the leaderboard / submissions area.
You should see your public log-loss score.
Remember:
.69315 is the all-.5 baseline;Do not panic if a sensible model occasionally scores slightly worse than a previous one. Random variation exists.
This distinction is important.
Kaggle gives you:
train.csv
where you know the true labels, and:
test.csv
where you do not.
Do not use test.csv as though it were
the ordinary test split we have used in earlier assignments.
You cannot evaluate your predictions directly on it, because you do not know the answers.
Instead, use the labeled data in train.csv to make
modeling decisions.
For example, you may:
Only after you have made those decisions should you fit the final model and generate predictions for the Kaggle test set.
(If you’re using cross-validation, remember that any preprocessing that learns from the data should be fitted separately within each training fold. A Pipeline is particularly useful for this.)
There is one more wrinkle.
You submit predictions for every name in
test.csv.
However, Kaggle secretly divides those test observations into two groups:
Public leaderboard: approximately 30% of test names
Private leaderboard: approximately 70% of test names
You do not know which names belong to which group.
While the competition is running, the score you see on the leaderboard is computed using only the public portion.
But at the end, surprise! the final ranking is based on the private portion.
This means your public leaderboard score is itself only an estimate of how well your model generalizes.
Suppose you try Model A and obtain:
0.421
Then you change something and submit Model B:
0.414
Then C:
0.409
Then D:
0.405
It is tempting to conclude:
Aha! I shall continue changing things until the leaderboard bends to my will.
But every time you use the public leaderboard to choose among models, you are indirectly learning something about those public test observations.
If you do this enough times, you can begin to overfit the public leaderboard, even though Kaggle never shows you the actual labels.
A model that happens to perform unusually well on the public cases may perform worse on the private cases.
Therefore:
do most of your model comparison using the labeled training data, not by repeatedly poking the Kaggle leaderboard with a stick.
The public leaderboard is useful feedback.
It is not divine revelation.
You will submit the following.
You or your team must have at least one valid non-baseline logistic-regression or nearest-neighbor submission on the competition leaderboard.
The .5 baseline submission does not
count as your final model.
Send me an email with subject line “DATA 419 Homework #3 turn-in.”
If you’re working on a team, only one of you should send this
email, and that person should Cc: their
partner.
Attached to this email should be your .py file that:
train.csv and test.csv;submission.csv.Attach a short PDF describing what you did.
It should include:
.5 baseline.This does not need to be a long formal paper.
A page or two of clear prose, tables, and/or compact output is plenty.
As always, your work should be committed to your own local
git repository before you turn it in.
Send email with subject line DATA 419 Homework #3 help!! or come to office hours.