Due: Saturday, Oct. 17, midnight
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.
You may compete individually or in a team of two. (In the latter case, both students will earn identical scores.)
If you do not already have a Kaggle account, go to:
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.
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.
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 kaggleThen verify that it exists:
kaggle --versionAuthenticate your computer with Kaggle:
kaggle auth loginThis should guide you through the login process.
You only need to do this authentication once on a particular computer unless your credentials later change.
After you have joined the competition, download its files from the command line:
kaggle competitions download -c data-419-mushroom-madnessThis will download a ZIP archive.
Unpack it:
unzip data-419-mushroom-madness.zipYou should obtain three participant-facing files:
train.csv
test.csv
sample_submission.csv
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.
Several of the categorical variables use one-letter codes.
cap_shapeb = bell
c = conical
x = convex
f = flat
s = sunken
p = spherical
o = other
cap_colorn = brown
b = buff
g = gray
r = green
p = pink
u = purple
e = red
w = white
y = yellow
l = blue
o = orange
k = black
gill_colorThe gill-color codes use the same color codes as
cap_color, plus:
f = none
does_bruise_or_bleedt = yes
f = no
habitatg = grasses
l = leaves
m = meadows
p = paths
h = heaths
u = urban
w = waste
d = woods
seasons = spring
u = summer
a = autumn
w = winter
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.
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.
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:
.55 is timid but not disastrous;.95 is excellent;.00001 is the statistical equivalent of
confidently licking the wrong mushroom.This is why you must submit probabilities, not merely class labels.
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:
train.csv.poisonous.test.csv.predict_proba() to estimate (P()).submission.csv.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.
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.
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.
The leaderboard is not asking you to perform sorcery.
Start simple and proceed systematically.
Some reasonable experiments include:
Try the numeric predictors first.
Fit logistic regression using only:
cap_diameter
stem_height
stem_widthAdd categorical information.
One-hot encode one or more categorical predictors and see whether they improve predictive performance.
Compare sensible subsets of predictors.
More predictors do not automatically mean a better model on unseen data.
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.”
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.
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.)
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.
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.
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:
If you are working in a pair, the submission limit belongs to the team.
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:
id and poisonous
columns;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.
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.
Submit the following.
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.
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:
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 #2 help!! or come to office hours.