| make | all | num3d | type | |
|---|---|---|---|---|
| 0 | 0.00 | 0.64 | 0.0 | spam |
| 1 | 0.21 | 0.50 | 0.0 | spam |
| 2 | 0.06 | 0.71 | 0.0 | spam |



There are 3 main branches:
| make | all | num3d | type | |
|---|---|---|---|---|
| 0 | 0.00 | 0.64 | 0.0 | spam |
| 1 | 0.21 | 0.50 | 0.0 | spam |
| 2 | 0.06 | 0.71 | 0.0 | spam |
Bag of words of email \(i\).import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
_, ax = plt.subplots(1,1,figsize=(3.5,2))
spam.drop_duplicates(inplace=True)
sns.countplot(
data=spam,
x="type",
hue="type",
stat="percent")
ax.set_title("Barplot of Email Type")
ax.bar_label(ax.containers[0], fmt="%.2f", )
ax.bar_label(ax.containers[1], fmt="%.2f")
plt.show()
Bayes’s Theorem
For any two events \(O,H\) with \(\mathbb{P}(O)\times\mathbb{P}(H)>0,\) \[\begin{equation}\overbrace{\mathbb{P}(H|O)}^{\text{Posterior}}=\frac{\overbrace{\mathbb{P}(O|H)}^{\text{Likelihood}}\times\overbrace{\mathbb{P}(H)}^{\text{Prior}}}{\underbrace{\mathbb{P}(O)}_{\text{Marginal}}}.\end{equation}\]
Main assumption of NBC
Key quantity in NBC
Key quantity in NBC
| Type of \(X_j\) | Distribution | Graphic |
|---|---|---|
| Qualitative | Bernoulli, Multinomial… | barplot, countplot |
| Quantitative | Gausian, Exponential… | displot, hist, density… |
\(^{\text{📚}}\) Chapter 4, Introduction to Statistical Learning with R, James et al. (2021).
Key quantity in NBC
import plotly.figure_factory as ff
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(cols=2, rows=1, subplot_titles=("Exclamation", "CapitalTotal"))
temp1 = px.histogram(spam, x='charExclamation', color='type', nbins=10000)
temp1.data[0].showlegend=False
temp1.data[1].showlegend=False
temp2 = px.histogram(spam, x='capitalTotal', color='type', nbins=2)
fig.add_trace(temp1.data[0], row=1, col=1)
fig.add_trace(temp1.data[1], row=1, col=1)
fig.add_trace(temp2.data[0], row=1, col=2)
fig.add_trace(temp2.data[1], row=1, col=2)
fig.update_yaxes(type='log', row=1, col=1)
# fig.update_xaxes(type='log', row=1, col=2)
fig.update_layout(width=1000, height=230)
fig.show()Key quantity
Classification Rule
\[\text{x}\text{ belongs to class }\color{blue}{k^*}\text{ if }\color{blue}{\mathbb{P}(Y=k^*|X=\text{x})}=\max_{1\leq k\leq M}\color{blue}{\mathbb{P}(Y=k|X=\text{x})}.\]
make, address, capitalTotal\()\).from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
sns.set(style="white")
X_train2, X_test2, y_train2, y_test2 = train_test_split(spam[["make","address", "capitalTotal"]], spam.iloc[:,57], test_size = 0.2, random_state=42)
nb2 = GaussianNB()
_, ax = plt.subplots(1,1, figsize=(2,2))
nb2 = nb2.fit(X_train2, y_train2)
pred2 = nb2.predict(X_test2)
conf2 = confusion_matrix(pred2, y_test2)
con_fig2 = ConfusionMatrixDisplay(conf2)
pr2 = nb2.predict_proba(X_test2)[:,1]
con_fig2.plot(ax=ax)
plt.show()
Accuracy: proportion of correctly classified emails. \[\frac{463+62}{463+62+20+297}\approx 0.624.\]
Misclassification error: \[1-\text{accuracy}\approx0.376.\]
⚠️ This depends on the split
X_train1, X_test1, y_train1, y_test1 = train_test_split(spam.iloc[:,:57], spam.iloc[:,57], test_size = 0.2, random_state=42)
_, ax = plt.subplots(1,1, figsize=(3,3))
nb1 = GaussianNB()
nb1 = nb1.fit(X_train1, y_train1)
pred1 = nb1.predict(X_test1)
conf1 = confusion_matrix(pred1, y_test1)
con_fig1 = ConfusionMatrixDisplay(conf1)
pr1 = nb1.predict_proba(X_test1)[:,1]
con_fig1.plot(ax=ax)
plt.show()
Accuracy: proportion of correctly classified emails. \[\frac{365+348}{365+348+11+118}\approx 0.846.\]
Misclassification error: \[1-\text{accuracy}\approx 0.154.\]
⚠️ This depends on the split
Visualize type against inputs can help us filter useful input features.
There are too many features, we can apply statistical method, for example, ANOVA.
Number of selected features: 38.

Accuracy: \[\frac{359+350}{359+350+9+124}\approx 0.842.\]
Misclassification error: \[1-\text{accuracy}\approx 0.158.\]
⚠️ This depends on the split
Pros
independence is violeted.Cons
independence assumption.nonspam, always guessing nonspam gives \(0.95\) accuracy!Accuracy isn’t the right metric for imbalanced data!

import plotly.graph_objects as go
x = np.linspace(0,1,20)
y = np.linspace(0,1,20)
z1 = [[2*x[i]*y[j]/(x[i]+y[j]) for j in range(len(y))] for i in range(len(x))]
z2 = [[(x[i]+y[j])/2 for j in range(len(y))] for i in range(len(x))]
camera = dict(
eye=dict(x=1.7, y=-1.2, z=1.2)
)
fig = go.Figure(go.Surface(x = x,
y = y,
z = z1,
name = "F1-score",
colorscale = "Blues",
showscale = False))
fig.add_trace(go.Surface(x = x,
y = y,
z = z2,
name = "Average",
colorscale = "Electric",
showscale = False))
avg = (0.2 + 0.9)/2
f1 = 2*0.2*0.9/(0.2+0.9)
fig.add_trace(
go.Scatter3d(
x = [0.2] * 4,
y = [0.9] * 4,
z = [0, avg, f1, 1],
mode="markers + lines",
showlegend=False,
marker=dict(
color='red',
size=5),
line=dict(color='red',
width=2,
dash='dot'))
)
fig.update_layout(scene = dict(
xaxis_title='Precision',
yaxis_title='Recall',
zaxis_title='Scores'),
title = dict(text="F1-score vs Average",
y=0.9,
x=0.5,
font=dict(size = 30,
color = "#1C66B5")
),
scene_camera=camera,
width = 500,
height = 420)
fig.show()
from sklearn.metrics import roc_curve, RocCurveDisplay
from plotly.tools import mpl_to_plotly
# Method 2: Using roc_curve and Matplotlib directly
y1 = 1*(y_test1 == "spam")
fpr, tpr, thresholds = roc_curve(y1.values, pr1.flatten())
plt.plot([0, 1], [0, 1], 'k--', label='Random Classifier') # Diagonal line
plt.plot(fpr, tpr, label='ROC Curve')
# Figures
fig_full = plt.gcf()
pl_1 = mpl_to_plotly(fig_full)
pl_1.update_layout(width=500, height=420,
title=dict(text="ROC Curve of Full model",
font=dict(size=25)),
xaxis_title = dict(font=dict(size=20, color = "red")),
yaxis_title = dict(text='True Positive Rate (Recall)', font=dict(size=20, color = "#EBB31D")),
template='plotly_white')
pl_1.show()
\(\bullet\) ROC \(=\{(\)FPR\(_{\delta}\),TPR\(_{\delta}):\delta\in[0,1]\}\).
\(\bullet\) Better model = Larger Area Under the Curve (AUC).
fpr, tpr, thresholds = roc_curve(y1.values, pr2.flatten())
plt.plot(fpr, tpr, label='ROC Curve')
plt.plot([0, 1], [0, 1], 'k--', label='Random Classifier') # Diagonal line
# Figures
fig_2 = plt.gcf()
pl_2 = mpl_to_plotly(fig_2)
pl_2.update_layout(width=500, height=420,
title=dict(text="ROC Curve of 3-input model",
font=dict(size=25)),
xaxis_title = dict(font=dict(size=20, color = "red")),
yaxis_title = dict(text='True Positive Rate (Recall)', font=dict(size=20, color = "#EBB31D")),
template='plotly_white')
pl_2.show()Confusion matrix

ROC Curve & AUC

