Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Classification lessons
Class distributions · ML-C16 · 18–25 MIN

Match Naive Bayes to feature types

Use each production Naive Bayes preparation path.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeCompute and inspect the evidence
  3. PractiseAdapt the Python
  4. TransferCompute and inspect the evidence

Understand the idea

Production selects GaussianNB for continuous inputs, BernoulliNB for binary flags and OHE–BernoulliNB for categorical inputs. It does not expose arbitrary mixed inputs or CategoricalNB.

Use each production Naive Bayes preparation path.Binary flags: 0 / 1BernoulliNBClass evidenceGaussianNB models continuous measurements instead.
Use each production Naive Bayes preparation path.Scroll the diagram horizontally if needed.

What the syntax does

BernoulliNB()
  • Uses presence and absence of binary indicators.

Supplied for this practice

These objects are prepared afresh before your editor runs.

train / test
Supplied train; its definition below specifies the values and role. Supplied test; its definition below specifies the values and role.
train, test = train_test_split(df, test_size=0.2, random_state=42, stratify=df.popular)

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
candy_class · first 8 rows
competitornamechocolatefruitycaramelpeanutyalmondynougatcrispedricewaferhardbarpluribussugarpercentpricepercentwinpercentpopular
100 Grand1010010100.7320.8666.971750% or above
3 Musketeers1000100100.6040.51167.602950% or above
One dime0000000000.0110.11632.2611below 50%
One quarter0000000000.0110.51146.1165below 50%
Air Heads0100000000.9060.51152.341550% or above
Almond Joy1001000100.4650.76750.347550% or above
Baby Ruth1011100100.6040.76756.914550% or above
Boston Baked Beans0001000010.3130.51123.4178below 50%
Your task
  1. Fit BernoulliNB to Candy’s binary flags and predict held-away rows.
answer
Hints

Think: The declared target must stay separate from the presence/absence indicators.

Tools: BernoulliNB and an explicit flags list.

Approach: Fit only the nine permitted flags to the training popular labels and predict the same test schema.

Explained solution
from sklearn.naive_bayes import BernoulliNB
flags=['chocolate','fruity','caramel','peanutyalmondy','nougat','crispedricewafer','hard','bar','pluribus']
model=BernoulliNB().fit(train[flags],train.popular)
answer=model.predict(test[flags])

The binary likelihood matches the feature meanings and excludes the target-derived winpercent source.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.