DATA 419 homework #2: Logistic Regression (+40XP)

Due: Saturday, Oct. 17, midnight

Welcome to the mushroom arena

For this homework, we are going to do something a little different. I have created a private Kaggle competition for DATA 419.

Kaggle is a platform on which people compete to build machine-learning models that make good predictions on data whose answers they cannot see. It is used for everything from beginner tutorials to very serious international data science competitions populated by bleary-eyed competitors.

Our competition is called:

DATA 419 Mushroom Madness

You will receive a training data set containing biologically-realistic mushrooms, together with information about whether eating that mushroom is safe, or toxic. You will also receive a test data set containing mushrooms whose edibility is not revealed to you.

Your job is to build a logistic regression model that estimates:

\[ P(\text{mushroom is poisonous}) \]

for every mushroom 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

0. Create a Kaggle account

If you do not already have a Kaggle account, go to:

https://www.kaggle.com/

and create one.

(Kaggle may distinguish between your account username and the display name that appears in some parts of the site. Do not be alarmed if these are not identical.)

Once you have an account you can join our private competition using the invitation link posted in Canvas.

You will need to accept the competition rules before Kaggle will allow you to download the data or submit predictions.


0.1. Decide whether you are working alone or in a pair

You may compete:

If you work in a pair, use Kaggle’s Team tab to form a single team.

Both members of a team are responsible for understanding the entire solution. “Jordan wrote the mysterious part with the matrices and I provided emotional support” is not an adequate explanation of your model.

Do not create multiple Kaggle accounts in order to obtain extra submissions.


0.2. Install the Kaggle command-line program

We will use Kaggle’s command-line interface rather than relying entirely on pointing and clicking in the web site.

Inside your DATA 419 Python environment:

pip install kaggle

Then verify that it exists:

kaggle --version

Authenticate your computer with Kaggle:

kaggle auth login

This should guide you through the login process.

You only need to do this authentication once on a particular computer unless your credentials later change.


0.3. Download the competition data

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

kaggle competitions download -c data-419-mushroom-madness

This will download a ZIP archive.

Unpack it:

unzip data-419-mushroom-madness.zip

You should obtain three participant-facing files:

train.csv
test.csv
sample_submission.csv

The data

The data are freshly generated synthetic mushrooms based on the biologically-based generation procedure associated with the UCI Secondary Mushroom data set.

Each row represents one mushroom. The training set contains about 42,000 mushrooms. The test set contains about 18,000 more.

The columns are:

Column Type Meaning
id identifier arbitrary ID number for the mushroom
cap_diameter numeric cap diameter, in centimeters
stem_height numeric stem height, in centimeters
stem_width numeric stem width, in millimeters
cap_shape categorical shape of the cap
cap_color categorical color of the cap
does_bruise_or_bleed categorical whether it bruises or bleeds
gill_color categorical color of the gills
habitat categorical habitat in which it grows
season categorical season
poisonous target 1 = poisonous, 0 = edible

The poisonous column appears in train.csv.

The poisonous column does not appear in test.csv.

There are no missing values in the predictor columns used for this competition, so you do not need to perform missing-value imputation for this homework. We will save that delight for later.


Categorical codes

Several of the categorical variables use one-letter codes.

cap_shape

b = bell
c = conical
x = convex
f = flat
s = sunken
p = spherical
o = other

cap_color

n = brown
b = buff
g = gray
r = green
p = pink
u = purple
e = red
w = white
y = yellow
l = blue
o = orange
k = black

gill_color

The gill-color codes use the same color codes as cap_color, plus:

f = none

does_bruise_or_bleed

t = yes
f = no

habitat

g = grasses
l = leaves
m = meadows
p = paths
h = heaths
u = urban
w = waste
d = woods

season

s = spring
u = summer
a = autumn
w = winter

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{poisonous}) = 0.5 \]

for every mushroom 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"],
    "poisonous": 0.5,
})

submission.to_csv("submission.csv", index=False)

Your file should have exactly two columns:

id,poisonous

and exactly one row for every mushroom in test.csv.

The IDs must correspond to the correct mushrooms.

Do not accidentally write the DataFrame index into the file.


Submit it

From the command line:

kaggle competitions submit \
    -c data-419-mushroom-madness \
    -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 mushroom (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 mushroom is actually poisonous:

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


3. Build an actual logistic regression model

Now improve on the .5 baseline.

For this homework, your submitted predictions must come from a logistic regression model.

Your basic workflow should look something like:

  1. Load train.csv.
  2. Separate the predictors from poisonous.
  3. Decide how to preprocess the numeric and categorical predictors.
  4. Fit a logistic regression model.
  5. Evaluate candidate choices using only the labeled training data.
  6. Fit your chosen final model using the competition training data.
  7. Apply the same preprocessing to test.csv.
  8. Use predict_proba() to estimate (P()).
  9. Write those probabilities to submission.csv.
  10. Submit the file to Kaggle.

3.1. Numeric predictors

The numeric predictors are:

cap_diameter
stem_height
stem_width

If you’re normalizing/scaling for any of these, you may fit your scaler using the entire labeled train.csv, then use that same fitted scaler to transform test.csv.


3.2. Categorical predictors

The categorical predictors are:

cap_shape
cap_color
does_bruise_or_bleed
gill_color
habitat
season

None of these categories have a natural ordering to them. So I’m betting you’ll want to one-hot encode them.


3.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 = edible
1 = poisonous

Therefore, what Kaggle wants in the poisonous column is:

model.predict_proba(X_test)[:, 1]

That is:

\[ P(y=1)=P(\text{poisonous}) \]

Do not submit model.predict().

That gives hard 0/1 class predictions, and the competition is explicitly asking for probabilities.


4. How should I try to improve my score?

The leaderboard is not asking you to perform sorcery.

Start simple and proceed systematically.

Some reasonable experiments include:

  1. Try the numeric predictors first.

    Fit logistic regression using only:

    cap_diameter
    stem_height
    stem_width
  2. Add categorical information.

    One-hot encode one or more categorical predictors and see whether they improve predictive performance.

  3. Compare sensible subsets of predictors.

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

  4. 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.”

  5. Inspect what your model is doing.

    Look at coefficients, predicted probabilities, and the distribution of predictions. If your model predicts .999999 for almost everything, perhaps ask why before releasing it into the wild.

A very simple intermediate baseline is also worth thinking about:

instead of predicting .5 for everybody, what if you predicted the training set’s overall proportion of poisonous mushrooms for everybody?

That still ignores all predictors, but it may beat .5 slightly if the classes are not exactly balanced.


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

(This distinction is one of the central ideas behind prediction competitions: the actual test answers remain external to the modeling process.)


6. Public leaderboard vs. private leaderboard

There is one more wrinkle.

The Kaggle test set contains 18,321 mushrooms.

You submit predictions for all 18,321.

However, Kaggle secretly divides those test observations into two groups:

Public leaderboard:   5,496 mushrooms
Private leaderboard: 12,825 mushrooms

You do not know which mushrooms 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 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 those 5,496 public cases may perform worse on the 12,825 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.


7. How often can I submit?

This competition allows four 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.


8. Creating your real submission file

After fitting your final candidate model:

p_poisonous = model.predict_proba(X_test)[:, 1]

create a DataFrame containing:

id
poisonous

For example:

submission = pd.DataFrame({
    "id": test["id"],
    "poisonous": p_poisonous,
})

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-mushroom-madness \
    -f submission.csv \
    -m "brief description of this model"

Use a useful submission message.

For example:

numeric predictors only

or:

all predictors, one-hot encoded

is more informative than:

asdf

Future You will appreciate Current You naming your attempts sensibly.


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


What to turn in

Submit the following.

1. Your Kaggle submission

You or your team must have at least one valid non-baseline logistic-regression 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 #2 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 your preprocessing.
  4. Which predictors you used.
  5. How you encoded the categorical variables.
  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 #2 help!! or come to office hours.