AI Lab8
AI Lab8
AI Lab8
Classification Workflow
Whenever you perform classification, the first step is to understand the problem and
identify potential features and label. Features are those characteristics or attributes
which affect the results of the label. For example, in the case of a loan distribution,
bank managers identify the customer’s occupation, income, age, location, previous
loan history, transaction history, and credit score. These characteristics are known
as features that help the model classify customers.
The classification has two phases, a learning phase and the evaluation phase. In the
learning phase, the classifier trains its model on a given dataset, and in the
evaluation phase, it tests the classifier's performance. Performance is evaluated on
the basis of various parameters such as accuracy, error, precision, and recall.
Naive Bayes classifier assumes that the effect of a particular feature in a class is
independent of other features. For example, a loan applicant is desirable or not
depending on his/her income, previous loan and transaction history, age, and
location. Even if these features are interdependent, these features are still
considered independently. This assumption simplifies computation, and that's why it
is considered as naive. This assumption is called class conditional independence.
P(h): the probability of hypothesis h being true (regardless of the data).
This is known as the prior probability of h.
P(D): the probability of the data (regardless of the hypothesis). This is
known as the prior probability.
P(h|D): the probability of hypothesis h given the data D. This is known as
posterior probability.
P(D|h): the probability of data d given that the hypothesis h was true. This
is known as posterior probability.
Probability of playing:
The probability of a 'Yes' class is higher. So you can determine here if the weather is overcast
than players will play the sport.
Now suppose you want to calculate the probability of playing when the weather is overcast,
and the temperature is mild.
Probability of playing:
The probability of a 'Yes' class is higher. So you can say here that if the weather is overcast
than players will play the sport.
Classifier Building in Scikit-learn
Naive Bayes Classifier with Loan Dataset
Let’s train the Naive Bayes Classifier on the real dataset. We will be repeating most of the
tasks except for preprocessing and data exploration.
Data Loading
In this example, we will be loading Loan Data (Loan Data | DataCamp Workspace) from
DataCamp Workspace using pandas 'read_csv` function.
import pandas as pd
df = pd.read_csv('loan_data.csv')
df.head()
Data Exploration
In this example, we will be developing a model to predict the customers who have not fully
paid the loan. Let’s explore the purpose and target column by using seaborn’s countplot.
sns.countplot(data=df,x='purpose',hue='not.fully.paid')
plt.xticks(rotation=45, ha='right');
Our dataset is an imbalance that will affect the performance of the model. You can check
out Resample an Imbalanced Dataset tutorial to get hands-on experience in handling
imbalanced datasets.
Data Processing
We will now convert the ‘purpose’ column from categorical to integer using pandas
`get_dummies` function.
pre_df = pd.get_dummies(df,columns=['purpose'],drop_first=True)
pre_df.head()
After that, we will define feature (X) and target (y) variables, and split the dataset into
training and testing sets.
X = pre_df.drop('not.fully.paid', axis=1)
y = pre_df['not.fully.paid']
X, y, test_size=0.33, random_state=125
Model building and training is quite simple. We will be training a model on a training dataset
using default hyperparameters.
model = GaussianNB()
model.fit(X_train, y_train);
Model Evaluation
We will use accuracy and f1 score to determine model performance, and it looks like the
Gaussian Naive Bayes algorithm has performed quite well.
accuracy_score,
confusion_matrix,
ConfusionMatrixDisplay,
f1_score,
classification_report,
y_pred = model.predict(X_test)
print("Accuracy:", accuray)
Accuracy: 0.8206263840556786
F1 Score: 0.8686606980013266
Due to the imbalanced nature of the data, we can see that the confusion matrix tells a
different story. On a minority target: `not fully paid`, we have more mislabeled.
cm = confusion_matrix(y_test, y_pred)
disp.plot();
The solution for such an issue is the Laplacian correction or Laplace Transformation.
Laplacian correction is one of the smoothing techniques. Here, you can assume that the
dataset is large enough that adding one row of each class will not make a difference in the
estimated probability. This will overcome the issue of probability values to zero.
For Example: Suppose that for the class loan risky, there are 1000 training tuples in the
database. In this database, the income column has 0 tuples for low income, 990 tuples for
medium income, and 10 tuples for high income. The probabilities of these events, without the
Laplacian correction, are 0, 0.990 (from 990/1000), and 0.010 (from 10/1000)
Now, apply Laplacian correction on the given dataset. Let's add 1 more tuple for each
income-value pair. The probabilities of these events: