DATA 419 homework #3: Feature Engineering (+40XP)

Due: Tuesday, Oct. 27, midnight

What’s in a name?

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.

Participation

You may compete individually or in a team of two. (In the latter case, both students will earn identical scores.)


Getting started

(Read the “Getting Started” section of the Mushroom Madness homework if you didn’t do that assignment.)

Download the competition data

After you have joined the competition, download its files from the command line:

kaggle competitions download -c data-419-whats-in-a-name

This will download a ZIP archive.

Unpack it:

unzip data-419-whats-in-a-name.zip

You should obtain three participant-facing files:

train.csv
test.csv
sample_submission.csv

The data

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.


1. Getting off the ground

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.


Submit it

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.


2. What exactly is Kaggle scoring?

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:

This is why you must submit probabilities, not merely class labels.


3. Look at the data

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?”


4. Build an actual model

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:

  1. Load train.csv.
  2. Separate the name predictor from female.
  3. Invent features that extract useful information from each name.
  4. Encode and/or scale those features as appropriate.
  5. Fit a model.
  6. Evaluate candidate choices using only the labeled training data.
  7. Fit your chosen final model using the competition training data.
  8. Apply the same feature engineering and preprocessing to test.csv.
  9. Use predict_proba() to estimate (P()).
  10. Write those probabilities to submission.csv.
  11. Submit the file to Kaggle.

4.1. Feature engineering

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.


4.2. Numeric and categorical 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:

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.


4.3. Which probability do you submit?

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.


5. How should we try to improve our score?

The leaderboard is not asking you to perform sorcery.

Start simple and proceed systematically.

Some reasonable experiments include:

  1. Start with just one or two features.

For example, try predicting gender using only the last letter of a name.

How much better than .5 can you get?

  1. Add more information.

Try including the first letter, name length, or vowel count.

Do these actually improve predictive performance?

  1. Experiment with character sequences.

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.

  1. Experiment with transformed predictors.

Maybe including quadratic/cubic terms and/or interaction terms would help?

  1. Compare sensible subsets of predictors.

More predictors do not automatically mean a better model on unseen data.

  1. Try different regularization strengths.

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:

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.

  1. Use the labeled training data to compare models.

Cross-validation is much better evidence than “I submitted it to Kaggle and the number moved slightly.”

  1. Inspect what your model is doing.

Look at coefficients, predicted probabilities, and the distribution of predictions.

Which features seem particularly associated with male or female names?


6. How often can I submit?

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:

  1. evaluate candidate ideas locally;
  2. choose a model that looks genuinely promising;
  3. generate a submission;
  4. send it to Kaggle;
  5. observe the public score;
  6. continue working.

If you are working in a pair, the submission limit belongs to the team.


7. Creating your real submission file

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:

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.


8. Seeing your score

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:

Do not panic if a sensible model occasionally scores slightly worse than a previous one. Random variation exists.


Notes

The competition training set is not the Kaggle test set

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.)


Public leaderboard vs. private leaderboard

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.


Why do they have a private leaderboard?

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.


What to turn in

You will submit the following.

1. Your Kaggle submission

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.


2. Your Python program

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:


3. A short report

Attach a short PDF describing what you did.

It should include:

  1. Your name, and your teammate’s name if applicable.
  2. Your Kaggle team name.
  3. A brief description of the features you engineered.
  4. Which features you ultimately used.
  5. How you encoded/scaled the features.
  6. How you evaluated candidate models before submitting them.
  7. The public leaderboard score of your selected final submission.
  8. A brief comparison with the .5 baseline.
  9. One or two things you tried that improved the score, failed to improve it, or surprised you.
  10. A short explanation of why repeatedly optimizing against the public leaderboard could lead to overfitting.

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.


Questions?

Send email with subject line DATA 419 Homework #3 help!! or come to office hours.