Machine Learning Concepts, Classification, Part: 1
By Gencay
Published: 2024-02-02
URL: https://www.learnwithmeai.com/p/starting-with-basics-introduction

Welcome to the first part of the #LearnAI series. This series will continue until the end of this year, and if you want to know more about the learning plan, you can read this one.
In this article, we will start with Classification. All of the information in this article can be reached via LearnAIWithMe GPT, which is available for our paid subscribers.
After reading this one, you will have a general understanding of Classification, which is an important part of Machine Learning. Let’s start!
Here is the link to LearnAIWithMe GPT.
Section 1: Overview
Understanding Classification

Imagine you have a collection of objects, and you want to sort them into different groups based on certain attributes or properties.
For example, you might have a dataset of flowers, and your goal is to determine the species of each flower (e.g., Iris setosa, Iris versicolor, or Iris virginica) based on measurements like sepal length, sepal width, petal length, and petal width.

Section 2: Most Used Classification Algorithms

To apply these most used classification algorithms, let’s use IRIS Dataset.
The Iris dataset is commonly used in machine learning. It consists of 150 samples from three species of Iris flowers, each with four features (sepal length, sepal width, petal length, and petal width).
The goal is to classify the species of the Iris flowers based on these features.
Logistic Regression
Logistic Regression is a straightforward classification algorithm that is used when we want to predict a binary outcome (1 / 0, Yes / No, True / False) based on one or more independent variables. It estimates the probability of a particular event happening.
Where Logistic Regression Can be Used?
Logistic Regression is widely used in various fields, including healthcare for disease prediction, marketing for customer churn analysis, and sentiment analysis in natural language processing.
Application of Logistic Regression
To apply Logistic regression, let’s use a built-in IRIS dataset.
First, we’ll load the Iris dataset and split it into training and test sets, which is a standard procedure, before applying the Machine Learning to see how our model works, by applying our model to both afterward.
Next, we are using a logistic regression model from sci-kit learn, and calculate the precision and recall. Don’t worry, all of these terms will be explained to you afterward. This one is here for you to be familiar with the code.
# Import necessary libraries
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score
# Load the Iris dataset
iris = load_iris()
X, y = iris.data, iris.target
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create a Logistic Regression model
model = LogisticRegression()
# Fit the model to the training data
model.fit(X_train, y_train)
# Predict on the test data
y_pred = model.predict(X_test)
# Calculate precision and recall
precision = precision_score(y_test, y_pred, average='weighted')
recall = recall_score(y_test, y_pred, average='weighted')
print("Precision:", precision)
print("Recall:", recall)
Let’s see the result.

Now, having one from both precision and recall shows that your model is possibly overfitting. What is overfitting? Simply, your model said to you that the result is too good to be true.
There are techniques, like the following, which we will go through.
- Regularization: Adjust model hyperparameters to control model complexity and prevent it from fitting noise in the data.
- Cross-Validation: Assess model performance using multiple data splits to get a better estimate of its generalization ability.
- Feature Selection: Choose relevant features and exclude irrelevant ones to reduce model complexity.
- Ensemble Methods: Combine multiple models to improve predictions and reduce overfitting.
- Early Stopping: Halt model training when its performance on validation data starts to degrade to prevent overfitting.
- Simpler Models: Use models with fewer parameters to reduce complexity.
Decision Trees

Decision Trees are a simple yet powerful algorithm used for both classification and regression tasks. They work by splitting the dataset into subsets based on the most significant attribute at each node, forming a tree-like structure.
Where Decision Trees Can Be Used?
Decision Trees are employed in various domains, such as finance for credit scoring, healthcare for disease diagnosis, and business for customer segmentation.
Application of Decision Trees
Now, let’s use Decision Trees on the Iris Dataset.
Here, to avoid overfitting, we will select some of our features(feature selection) and also use the Test and Evaluation set.
- Feature Selection: We perform feature selection to reduce the complexity of the model by using only the most relevant features, preventing the model from fitting noise in the data and improving generalization.
- Test and Evaluation Sets: The separation of data into test and evaluation sets allows us to assess the model's performance on unseen data, ensuring that it can generalize well and doesn't overfit to the training data by providing a more robust evaluation of its capabilities.
Now, let’s see the code.
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Select a subset of features, e.g., the first two features (Sepal Length and Sepal Width)
X_subset = X[:, :2]
# Split the data into training, evaluation, and test sets
X_train, X_temp, y_train, y_temp = train_test_split(X_subset, y, test_size=0.3, random_state=42)
X_eval, X_test, y_eval, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
# Normalize the features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_eval_scaled = scaler.transform(X_eval)
X_test_scaled = scaler.transform(X_test)
# Create a Random Forest model
rf_model = RandomForestClassifier(random_state=42) # You can adjust n_estimators as needed
# Fit the model to the training data
rf_model.fit(X_train_scaled, y_train)
# Predict on the evaluation data
y_eval_pred = rf_model.predict(X_eval_scaled)
# Calculate precision and recall on the evaluation set
precision_eval = precision_score(y_eval, y_eval_pred, average='weighted')
recall_eval = recall_score(y_eval, y_eval_pred, average='weighted')
print("Precision (Random Forest) on Evaluation Set:", precision_eval)
print("Recall (Random Forest) on Evaluation Set:", recall_eval)
# Now, let's test the model on the test set
y_test_pred = rf_model.predict(X_test_scaled)
# Calculate precision and recall on the test set
precision_test = precision_score(y_test, y_test_pred, average='weighted')
recall_test = recall_score(y_test, y_test_pred, average='weighted')
print("Precision (Random Forest) on Test Set:", precision_test)
print("Recall (Random Forest) on Test Set:", recall_test)
Here is the output.

Well, as you can see, we managed to solve the overfitting issue.
If you had roadblocks while applying machine learning, welcome to the club. You’ll continue having roadblocks; the situation here is to be prepared for them.
Support Vector Machines

Support Vector Machines (SVMs) are a machine learning algorithm used for both classification and regression tasks. It works by finding a hyperplane that best separates different classes of data points while maximizing the margin between them.
Where Support Vector Machines Can Be Used?
SVM is applied in various fields, including image classification, text classification, and bioinformatics, where it's used for protein classification and gene expression analysis.
Application of SVM
Now, let’s apply SVM to the Iris Dataset.
from sklearn.svm import SVC
from sklearn.metrics import precision_score, recall_score
# Create an SVM model
svm_model = SVC(kernel='linear', random_state=42) # You can choose different kernels like 'linear', 'poly', 'rbf', etc.
# Fit the model to the training data
svm_model.fit(X_train_scaled, y_train)
# Predict on the evaluation data
y_svm_pred = svm_model.predict(X_eval_scaled)
# Calculate precision and recall on the evaluation set
precision_svm = precision_score(y_eval, y_svm_pred, average='weighted')
recall_svm = recall_score(y_eval, y_svm_pred, average='weighted')
print("Precision (SVM) on Evaluation Set:", precision_svm)
print("Recall (SVM) on Evaluation Set:", recall_svm)
Let’s see the output.

Section 3: Initial Steps in Classification
Data Preprocessing

\Photo byUX IndonesiaonUnsplash\
Data preprocessing involves cleaning and preparing your data for machine learning. This includes handling missing values, dealing with outliers, and ensuring that the data is in a suitable format.
Since our Irisi dataset is already ready, you might save this information for the raw data you’ll create.
Feature Selection and Engineering

\Photo byChristopher BurnsonUnsplash\
Now we did feature selection to prevent overfitting, you know. This technique will be even better when you have a massive dataset. Because when your data gets bigger and bigger, the algorithm you wrote needs more time to process.
Here, feature selection and engineering become more relevant.
In the case of the Iris dataset, you can evaluate which features (e.g., Sepal Length, Sepal Width, Petal Length, and Petal Width) are most informative for classifying the iris species. Feature selection methods like correlation analysis or feature importance from tree-based models can assist in this process.
All of these will be expanded for you in the later sections, so don’t feel overwhelmed right now.
Splitting Data for Training and Testing

\Photo byDrew BeameronUnsplash\
This step is crucial for assessing how well your machine-learning model generalizes to unseen data. It involves dividing your dataset into at least two subsets: training and testing sets.
The training set is used to train your model, and the testing set is reserved for evaluating its performance.
The split ratio between the training and testing sets can vary, but a common choice is to use 70-80% of the data for training and the remaining 20-30% for testing.
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Here are the advanced steps in Classification.

How to Learn These By Using LearnAIWithME GPT
To learn what you saw in this section, please use this prompt inside LearnAIWithMeGPT.
Let's start with classification
Now, here is the potential output you will see.

\LearnAIWithMe is available for paid subscribers,here\
Now, at this stage, you saw the resemblance. Use this prompt
Go with section 1. Introduction to Classification
Final Thoughts
Thanks for reading this one!