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.
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- The requested result, with the values, labels and row order described by this task.
competitorname | chocolate | fruity | caramel | peanutyalmondy | nougat | crispedricewafer | hard | bar | pluribus | sugarpercent | pricepercent | winpercent | popular |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 100 Grand | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0.732 | 0.86 | 66.9717 | 50% or above |
| 3 Musketeers | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0.604 | 0.511 | 67.6029 | 50% or above |
| One dime | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011 | 0.116 | 32.2611 | below 50% |
| One quarter | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011 | 0.511 | 46.1165 | below 50% |
| Air Heads | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.906 | 0.511 | 52.3415 | 50% or above |
| Almond Joy | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0.465 | 0.767 | 50.3475 | 50% or above |
| Baby Ruth | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0.604 | 0.767 | 56.9145 | 50% or above |
| Boston Baked Beans | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0.313 | 0.511 | 23.4178 | below 50% |
- Fit
BernoulliNBto Candy’s binaryflagsand predict held-away rows.
answerHints
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.