FG - Machine Learning Methods Using Python and R-II Edited
FG - Machine Learning Methods Using Python and R-II Edited
Programme Overview:
This programme is designed to equip participants with critical skills to understand the
importance of programming and get acquainted with various concepts.
Module Learning Goals
Terminal Objectives:
Participants will be able to comprehend the importance of programming and get acquainted
with various concepts.
Enabling objectives:
● Understand and explain the definition of Artificial Intelligence and Machine Learning
● Identify the concept of entities and terms involved in Programming
● Describe the Machine Learning Methods Using R and Python
● Understand and explain the qualities of a High-Level Language
● Familiarize themselves with the relationship between Programming with ML Python and
R.
Programme Preparation
Programme requires a significant amount of preparation. It is crucial that Programme
facilitators familiarize themselves with the material they designed or are expected to deliver
and have adequate time to adapt the content to the specific audience.
The Role of the Facilitator
Who is a facilitator?
A facilitator is someone who is present to assist a group reach its objectives; the group, not the
facilitator, may determine the objectives.
____________________________________________________________________________________
2 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
3 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Session Preparation
Questions
What
● What is the subject I have been asked to present on/lead/arrange?
Why
● Why I have been asked to do it?
● What is the purpose of the session or the training course?
● To communicate information and knowledge
● To make a proposition
● To test existing knowledge
● To practice skills
● To inspire and motivate
● The first thing to get clear in your mind is the objectives of the entire
course or one session.
When
● At what time of the day will my session (s) take place? After lunch is
known as the graveyard slot; therefore, you should consider making it more
active than, say, a morning session.
How
● How much time have I got?
● How am I going to present my subject?
● Straight talk
● Talk with overheads
● Talk with PowerPoint presentation
● Talk with video
● Give the participants a period in which to discuss aspects of the subject, e.g., by
using a case study
● Combination of any of these methods
● Should I allow questions during the session?
● Always leave time at the end for questions and discussion
Where
● Where is the presentation due to take place?
● How do the windows open/air conditioning work? If using PowerPoint or video,
how do we darken the room?
● What equipment have they got, e.g., video, computer, projector, overhead
projector, etc.?
● Decide on seating arrangements
● Are there likely to be any distractions, e.g., loud air-conditioning, things
happening outside the window, etc.
● Can I be heard at the back of the room?
____________________________________________________________________________________
4 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Who
● Who are the participants? How senior/junior are they?
● How many participants will be present?
● What is the extent of their existing knowledge of the subject I am going to present?
● What will be of interest to them?
● What will their attitudes, preconceptions or expectations be?
● Is there a gender balance within the group?
● Can you foresee or expect any kind of dynamics or potential resistance due to
group composition?
● What can you glean overall from the participants’ list and profile without making
too many assumptions?
____________________________________________________________________________________
5 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Icon Description/Guidelines
Facilitator Information
Show a slide < Used to denote the slide to be shown>. Even better,
paste the image of the slide being discussed.
Show a video
Distribute Handouts
____________________________________________________________________________________
6 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Materials required
Group Discussion
Play music
____________________________________________________________________________________
7 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Table of Contents
Unit Topic/Sub-topic Duration Page No.
I Time Series Forecasting 3 Hrs. 9-24
II Clustering and Classification 6 Hrs. 25-40
III Advanced Data Visualization Using 3 Hrs. 41-57
Matplotlib
IV Data Visualization Using Seaborn, 3 Hrs. 58-63
Bokeh
V Dimension Reduction Methods 3 Hrs. 64-75
VI Model Selection and Evaluation 3 Hrs. 76-96
VII Neural Networks, Text Mining 6 Hrs. 97-123
VIII Reinforcement Learning 3 Hrs. 124-137
References 138
Credits: 2
Hours: 30
____________________________________________________________________________________
8 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
The ARIMA model stands for Auto-Regressive Integrated Moving Normal. It is utilized to
anticipate the long-term values of a time arrangement, using its past values and figure
blunders. Here, the graph shows the components of an ARIMA model:
Moving Average: Moving Average could be a strategy that takes the upgraded normal of
values to reduce noise. It takes the average over a particular interval by taking diverse subsets
of the information and finding their specific averages. A bunch of information focuses and
takes their average to discover another normal by expelling the primary esteem of the
information and counting the other values of the series.
1. p: Past slacked values for each time point. Determined from the Auto-Regressive Model.
2. q: Previous slacked values for the blunder term. It was determined from the Moving
Average.
3. d: The number of times information is differentiated to form it stationary. It is the
number of times it performs integration.
____________________________________________________________________________________
11 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
For time as the independent variable, Time Series Analysis (TSA) examines the nature of
the response variable. The time variable is the reference point for estimating the target
variable in forecasting or prediction. A range of time-based orders, including years, months,
weeks, days, hours, minutes, and seconds, are represented by TSA. This observation is
derived from the discrete temporal sequence of subsequent intervals. Examples of TSA's
practical uses are weather forecasting models, stock market forecasts, signal processing, and
control systems.
____________________________________________________________________________________
12 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
The following procedures must be followed to complete the time series analysis:
● Collecting the data and cleaning it
● Display of time versus significant features
● To observe the stationarity of the series
● Develop charts to comprehend its nature.
● Model construction: ARMA, ARIMA, MA, and AR
● Concluding forecasts
TSA is the foundation of forecasting and prediction analysis, particularly for time-based
problem statements such as the following;
● Examining the trends in the historical dataset
● To understand and match the current situation with patterns derived from the previous
stage. To be aware of the variables that influence particular variables at different times.
We can generate various time-based studies and findings using "Time Series."
● Forecasting: It is the process of estimating any future value.
● Segmentation: Assemble related things into groups.
● Sorting: A group of things into designated classes is called classification.
● To ascertain the contents of a given dataset, use descriptive analysis.
● Analysis of the intervention: Impact of modifying a specific variable on the result.
● Trend: A continuous timeline with no fixed period when there is divergence within the
provided dataset. There would be a neutral, positive, or negative trend.
● Seasonality: A continuous timeline with frequent or defined interval shifts within the
dataset, resembling a saw tooth or bell curve.
● Cyclical: When there is no set.
The time series includes the following constraints, which we must consider when analyzing
the data. Like other models, TSA does not support the missing.
● The relationships between the data points must be linear.
● Data transformations are expensive since they are required.
● Models primarily work on uni-variate data.
There are two significant time series data types: stationary and non-stationary.
Stationary: A dataset should follow the thumb rules below without having the time series'
trend, seasonality, cyclical, and irregularity components.
● Their mean value should be utterly constant in the data during the analysis.
● The variance should be constant to the time frame
● Covariance measures the relationship between two variables.
____________________________________________________________________________________
13 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Python and R, handling date and time data is essential, especially in time series analysis.
Timestamps represent a specific time point and include date and time information. Time
Intervals and Periods: Represent continuous periods, such as "1 month" or "1 year". Time
Durations: Represent a length of time independent of any specific start or end point.
Functions like pd.to_datetime() can convert strings or numerical values to DateTime objects,
providing functionalities for date/time arithmetic, slicing, and resampling.
DateTime Module:
Python's built-in datetime module provides classes for manipulating dates and times. Includes
classes like DateTime, date, time, and time delta for representing and performing various
operations on date and time values.
____________________________________________________________________________________
14 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
The Zoo package provides tools for handling ordered observations, including time series data.
It offers functionalities for indexing, merging, and aggregating time series data.
Everyday Operations for Date and Time Data:
Parsing: Converting date and time data from string or numerical formats into datetime
objects.
Formatting: To represent datetime objects in different formats for display or storage.
Arithmetic Operations: Performing operations on datetime objects, such as addition,
subtraction, and comparison.
Indexing and Slicing: Selecting specific date/time ranges or intervals from time series data
for analysis.
Resampling and Aggregation: Using resampling techniques, changing the frequency or
granularity of time series data.
import pandas as pd
date_obj = pd.to_datetime('2024-02-07')
____________________________________________________________________________________
15 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Both examples demonstrate creating datetime objects and performing arithmetic operations.
Ranges
In time series analysis, ranges refer to the period the data covers. It includes the start and end
dates or timestamps of the dataset. Understanding the range of the data is crucial for
determining the overall period under consideration.
import pandas as pd
In machine learning, "range" typically refers to the range of values a feature (or variable) can
take within a dataset. It can also refer to scaling or normalizing features to a specific range to
improve the performance of machine learning algorithms.
Range of Values:
Understanding the range of values for each feature in the dataset is essential for various
reasons:
Data Understanding: Knowing the range of values to understand the distribution and
characteristics of the data.
Feature Selection: It can aid in feature selection by identifying features with a narrow or
wide range of values that may be relevant to the task at hand.
Preprocessing: It guides preprocessing steps such as scaling or normalization, ensuring that
features are appropriately transformed for modeling.
Scaling and Normalization
Scaling and normalization are preprocessing techniques to transform features to a specific
range or distribution. Common methods include the following;
Min-Max Scaling: Rescales features to a fixed range, typically [0, 1] or [-1, 1], preserving
the original shape of the distribution.
Standardization (Z-score normalization): Scales feature for mean value 0 and standard
deviation value of 1 results in a distribution centered around 0.
Robust Scaling: Scales features using robust statistics to mitigate the effect of outliers.
X_scaled = scaler.fit_transform(X)
library(caret)
The range of values in features impacts the performance and behavior of machine
learning algorithms:
Gradient Descent: Algorithms like gradient descent may converge faster when features are
within a similar range.
Regularization: Regularization techniques penalize significant coefficients, so scaling
features to a standard range can prevent certain features from dominating the model.
Distance-Based Algorithms: Algorithms that rely on distance metrics, such as k-nearest
neighbors (KNN) or support vector machines (SVM), can be sensitive to the scale of features.
Data Understanding: Knowing the range of values and understanding the distribution and
characteristics of the data.
Feature Selection: It can aid in feature selection by identifying features with a narrow or
wide range of values that may be relevant to the task at hand.
Preprocessing: It guides preprocessing steps such as scaling or normalization, ensuring that
features are appropriately transformed for modeling.
Scaling and Normalization:
Scaling and normalization are preprocessing techniques to transform features to a specific
range or distribution. Common methods include:
Min-Max Scaling: Rescales features to a fixed range, typically [0, 1] or [-1, 1], preserving
the original shape of the distribution.
Standardization (Z-score normalization): Scaling features to a mean of zero and a standard
deviation of one results in a distribution centered around 0.
Robust Scaling: Scales features using robust statistics to mitigate the effect of outliers.
Python (Pandas):
weekly_data = time_series_data.resample('W').sum()
Shifting time series data involves moving the data forward or backward in time. IT can help
create lag features or align features with the target variable in supervised learning tasks.
Python (Pandas):
lagged_data = time_series_data.shift(periods=1)
R (xts or zoo):
Time Zones
When working with data collected from different time zones, it is essential to adjust the
timestamps to a standard time zone to ensure consistency in analysis or modeling.
Python (Pandas):
# Assuming 'time_series_data' is in UTC and you want to convert it to US/Eastern time zone
time_series_data = time_series_data.tz_localize('UTC').tz_convert('US/Eastern)
R (xts or zoo):
# Assuming 'time_series_data' is in UTC and you want to convert it to US/Eastern time zone
____________________________________________________________________________________
18 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Using Python:
1. Handling Time Series Data:
Python provides libraries such as pandas and statsmodels for time series analysis.
Create time series objects using the pandas. Series or [Link] class.
Pandas provides the pd.date_range() function for generating date indices with specified
frequencies.
2. Periodic Arithmetic Sampling:
Pandas provides various methods for periodic arithmetic sampling, including slicing
using datetime indices.
Here, use functions like loc[] or slicing with datetime indices to extract data corresponding to
specific periods.
Import pandas as pd
sampled_data = data[::2]
print(sampled_data)
This example creates a time series with daily frequency and then performs periodic arithmetic
sampling to extract data every two days.
Both R and Python offer robust capabilities for handling time series data and performing
periodic arithmetic sampling, with libraries like statsmodels (for R) and pandas (for Python)
being popular choices for such tasks.
Resampling
Resampling in machine learning refers to creating new datasets from an existing dataset
through various sampling techniques. It's commonly used to assess machine learning models'
performance, improve model generalization, and handle imbalanced datasets. Two standard
techniques for resampling are:
Cross-Validation: This technique involves partitioning the dataset into subsets, training the
model on some subsets, and evaluating it on the remaining subset(s). Cross-validation helps
to estimate the model's performance and generalization ability.
Cross-Validation:
Cross-validation is a widely used resampling technique for estimating the performance of
machine learning models.
The standard form of cross-validation is k-fold, where a dataset is divided into k subsets
(folds). The k times trained model uses k-1 folds as the training data set and the remaining
fold as the validation data.
____________________________________________________________________________________
20 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
import numpy as np
# Assuming 'X' is your feature matrix and 'y' is your target vector
model = LogisticRegression()
R (using caret):
library(caret)
# Assuming 'X' is your feature matrix and 'y' is your target vector
model <- train(X, y, method = "glm", trControl = train control(method = "cv", number = 5,
verboseIter = TRUE))
print(model)
Bootstrapping is a resampling technique that involves repeating the sampling data from the
dataset with replacement to create multiple bootstrap samples. These samples are then used to
train and evaluate multiple models, and the results are aggregated to estimate the model's
performance.
y_pred = [Link](X_test)
____________________________________________________________________________________
21 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
bootstrap_scores.append(accuracy)
Using R:
Bootstrapping in R can be implemented using various packages, such as boot or caret.
library(boot)
# Assuming 'X' is your feature matrix and 'y' is your target vector
# 'glm' is your base model
boot_results <- boot(data = [Link](X, y), statistic = function(data, indices) {
model <- glm(y ~ ., data = data[indices, ])
return(model)
}, R = 100)
print(boot_results)
These are basic examples of performing resampling techniques like cross-validation and
bootstrapping in machine learning using Python, and R. Resampling is an essential aspect of
model evaluation and can provide more robust estimates of a model's performance and
generalization ability.
Frequency Conversion
In machine learning, converting frequencies refers to transforming time series data from one
frequency (e.g., daily) to another (e.g., weekly, monthly). This conversion is often used for
feature engineering or data preprocessing purposes. With the given example, we can perform
frequency conversion in Python and R:
Frequency Conversion in Python (using Pandas):
import pandas as pd
# Assuming 'time_series_data' is a Pandas DataFrame or Series with a DateTimeIndex
# Convert daily data to weekly data by summing up the values for each week
weekly_data = time_series_data.resample('W').sum()
# Convert daily data to monthly data by averaging the values for each month
monthly_data = time_series_data.resample('M').mean()
# Convert daily data to quarterly data by taking the maximum value for each quarter
quarterly_data = time_series_data.resample('Q').max()
Frequency Conversion in R (using xts or zoo):
____________________________________________________________________________________
22 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Adjust the window_size parameter to control the smoothing effect of the moving window.
Larger window sizes result in smoother trends but may obscure short-term fluctuations, while
____________________________________________________________________________________
23 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
smaller window sizes capture more detail but may be susceptible to noise. To calculate other
statistics or aggregates using different window functions such as rolling_sum(),
rolling_median(), rolling_std(), etc., depending on the specific analysis requirements. In R, to
achieve similar functionality using libraries like zoo or xts)
library(xts)
This R code calculates the rolling mean using a moving window of size window_size and
plots the original time series data along with the rolling mean.
Adjust the window_size parameter to control the smoothing effect of the moving window, as
explained earlier.
These visualizations can provide insights into the underlying trends and patterns in the time
series data, helping in feature engineering and model selection for machine learning tasks.
____________________________________________________________________________________
24 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Clustering and Classification is the task of predicting a new observation's category or class
label based on past observations labeled with their corresponding class labels. It is a
supervised learning approach, meaning the algorithm learns from labeled data.
Classification's main aim is to learn a mapping from input features to predefined output
labels. It is used for making predictions on unseen data - for example, spam email detection,
sentiment analysis, disease diagnosis, object recognition, etc.
Reinforcement:
An unsupervised learning technique is used in Clustering to group similar objects or data
points into clusters based on certain features or characteristics. Clustering is utilized in
various fields, such as customer segmentation, image processing, anomaly detection, and
recommendation systems.
Clustering reinforcement are two fundamental techniques in machine learning used for
different types of tasks: Clustering is unsupervised learning, while classification is supervised
learning. Clustering is the grouping of objects so the objects in the same group (called a
cluster) are more similar to each other than those in different groups.
It is an unsupervised learning approach, meaning the algorithm learns the data structure
without any labeled output. The goal of Clustering is to discover inherent groupings in the
data. It helps identify patterns, segment data, and understand the underlying structure—for
example, Customer segmentation, document clustering, image segmentation, anomaly
detection, etc.
____________________________________________________________________________________
25 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
[Link](0)
X = [Link](100, 2)
# Perform K-means clustering
means = KMeans(n_clusters=3)
[Link](X)
# Get cluster centers and labels
centers = means.cluster_centers_
labels = means.labels_
print("Cluster Centers:")
print(centers)
print("Cluster Labels:")
print(labels)
Reinforcement learning is widely used in machine learning, where the agent learns to take
action in an environment to maximize some of the notion of cumulative reward. It learns
through trial and error by interacting with the environment. Reinforcement learning is applied
in various domains such as robotics, game playing, autonomous vehicles, finance, and
healthcare.
____________________________________________________________________________________
26 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
These examples illustrate the implementations of Clustering using K-means in Python and
reinforcement learning using the CartPole environmerom OpenAI. Depending on the specific
requirements, explore more advanced algorithms and techniques in both clustering and
reinforcement learning.
library(stats)
[Link](123)
print(kmeans_result$centers)
print(kmeans_result$cluster)
import numpy as np
np. [Link](123)#
kmeans = KMeans(n_clusters=3)
[Link](data)
print(kmeans.cluster_centers_)
print(kmeans.labels_)
____________________________________________________________________________________
28 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
29 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Assignment: Each data point is assigned to the nearest centroid based on a distance metric
such as Euclidean distance. Each data point or data set is allocated to the cluster whose
centroid is closest to it.
Update Centroids: After assigning all data points to clusters, recalculate the centroids by
taking the mean of all data points allocated to each cluster.
Repeat: Repeat steps 2 and 3 until convergence. Convergence occurs when the centroids no
longer change significantly or after a certain number of iterations.
Final Clustering: Once the algorithm converges, the final clusters are obtained, and each
data point is associated with a cluster.
The K-means clustering is sensitive to the initial selection of centroids. Depending on the
initial centroids and data distribution, it can converge to a local optimum rather than a global
optimum. The algorithm is often run multiple times with different initializations, and the best
Clustering based on some criterion (e.g., minimizing the total within-cluster variance) is
selected. Additionally, variations and improvements to the basic K-means algorithm, such as
K-means++, provide a better initialization strategy to improve convergence and the
Clustering quality. K-means is efficient and scalable, making it suitable for large datasets.
However, it assumes that clusters are spherical and have similar sizes, which may only
sometimes hold in real-world data. In cases where clusters have complex shapes or varying
densities, other clustering algorithms like DBSCAN or hierarchical Clustering may be more
appropriate. An example of K-means clustering using Python with scikit-learn:
import numpy as np
import [Link] as plt
kmeans = KMeans(n_clusters=3)
# Fit the K-means model to the data
[Link](X)
# Get the cluster centers and labels
centers = kmeans.cluster_centers_
labels = kmeans.labels_
# Plot the data points and cluster centers
[Link](X[:, 0], X[:, 1], c=labels, cmap='viridis', alpha=0.5)
____________________________________________________________________________________
30 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
[Link]('Feature 1')
[Link]('Feature 2')
[Link]('K-means Clustering')
[Link]()
In this above example, we generate random data points in a 2D space, then apply K-means
clustering with 3 clusters. We plot the data points colored by their cluster assignments and the
cluster centers (centroid) in red.
kmeans = KMeans(n_clusters=3)
[Link](X)
centers = kmeans.cluster_centers_
labels = kmeans.labels_
[Link](X[:, 1], X[:, 0], c=labels, cmap='viridis', alpha=0.5)
[Link](centers[:, 0], centers[:, 1], c='blue', marker='X', s=200)
[Link]('Feature 1')
[Link]('Feature 2')
[Link]('K-means Clustering')
[Link]()
In the above example with output , we generate a random dataset X with 100 data points and
two features. We initialize the K-means clustering algorithm with 3 clusters using
KMeans(n_clusters=3). We fit the K-means model to the data using the fit() method.
____________________________________________________________________________________
32 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Hierarchical Clustering
Hierarchical Clustering is now a popular unsupervised learning technique for grouping
similar objects into clusters based on their pairwise distances. It creates a hierarchy of
clusters where clusters at the same level are more similar to each other than those at higher
levels.
There are two main types of hierarchy:
Agglomerative Hierarchical Clustering: In this approach, each data point initially forms its
cluster, and then pairs of clusters are iteratively merged based on their similarity until all data
points belong to a single cluster. The merging process continues until a stopping criterion is
met, such as a specified number of clusters or a threshold distance.
Divisive Hierarchical Clustering: This approach works opposite to agglomerative
Clustering. It starts with a single cluster containing all data points and recursively splits
clusters into smaller clusters until each data point is in its cluster. It continues until a stopping
criterion is met, similar to agglomerative Clustering.
Hierarchical Clustering is often visualized using dendrograms, which display the merging (or
splitting) process and help interpret the hierarchy of clusters.
[Link]('Feature of 1')
[Link]('Feature of 2')
[Link]('**Agglomerative Hierarchical Clustering**')
[Link]()
____________________________________________________________________________________
33 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example and the output, to generate random data points in 2D space using
make_blobs, then apply agglomerative hierarchical Clustering with 3 clusters using
Agglomerative Clustering. Finally, to visualize the data points colored by their cluster
assignments.
Recommendation System
Recommendation systems are used in various domains to provide personalized
recommendations to users. They can be implemented using clustering and classification
techniques. Clustering algorithms can group similar users or items based on their features or
behavior. Once clusters are formed, recommendations can be made by suggesting popular
items within a cluster or by recommending items liked by similar users in the cluster.
User Clustering: Group users into clusters based on their preferences, behaviour, or
demographic information. For example, K-means clustering can group users into clusters
based on their ratings or purchase history.
Item Clustering: Group items into clusters based on their features or characteristics. For
example, clustering can be applied to group movies or products into clusters based on their
genres, attributes, or tags.
Recommendation Generation: Once clusters are formed, recommendations can be
generated by suggesting popular items within a cluster or by recommending items liked by
similar users in the cluster.
Prediction and Recommendation: Use the trained classifier to predict the probability of a
user liking a new item. Items with high predicted probabilities can be recommended to the
user. Logistic regression or decision trees can be trained on historical user-item interactions
to predict whether a user will like a new item, and recommendations can be made based on
these predictions.
____________________________________________________________________________________
34 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Apriori Algorithm
The Apriori algorithm is a classic algorithm used in association rule mining, a technique in
data mining that discovers exciting relationships hidden in large datasets. While the Apriori
algorithm is not directly related to clustering or classification, it can be combined with
clustering or classification techniques for specific tasks.
The Apriori algorithm primarily identifies frequent item sets in transactional databases. It
works to iteratively find a frequent item set with an increase in the size of the "apriori"
property to state that any subset of a frequent item set must also be frequent.
Frequent Item Set Generation: The Apriori algorithm starts by identifying all individual
items that occur frequently in the dataset (frequent 1-item sets). It then iteratively generates
larger item sets by combining frequent (k-1)-item sets to form candidate sets, which are
subsequently pruned based on the minimum support threshold.
Association Rule Generation: Once frequent item sets are identified, association rules are
generated by forming rules of the form A → B, where A and B are item sets, and calculating
metrics such as support, confidence, and lift to measure the strength of the association
between A and B.
Apriori with Clustering: Apriori algorithm itself is not directly used for clustering, it can be
employed in conjunction with clustering techniques for specific tasks.
As an example Market Basket Analysis: Apriori can be used to discover frequent item sets
in transactional data, such as customer shopping baskets. These item sets can then identify
patterns and associations among products purchased together. Clustering techniques can be
applied to segment customers based on their purchasing behaviour. Apriori can be used
within each cluster to identify specific item sets or associations relevant to that cluster.
Feature Selection: In classification tasks, Apriori can be used for feature selection by
identifying frequent item sets of features that occur together frequently in the dataset. These
frequent item sets can be utilized as input features for classification models to reduce the
dimensionality of the feature space to improve model performance.
ECLAT Algorithm
The ECLAT algorithm is an Equivalence Class Clustering and Bottom-Up Lattice Traversal
algorithm for frequent item set mining in transactional databases, similar to the Apriori
algorithm. While ECLAT is not inherently a clustering or classification algorithm, it can be
used as a preprocessing step or in conjunction with clustering and classification techniques
for specific tasks. ECLAT is designed to mine frequent itemsets from transactional databases
efficiently. Frequent Item Set Generation: ECLAT recursively finds frequent item sets by
exploring the lattice structure of the item sets. It starts by identifying frequent 1-item sets and
then extends them to larger item sets by recursively combining them with other frequent item
sets.
Equivalence Class Clustering: ECLAT uses an equivalence class to reduce the search
space. It clusters transactions that share everyday items into equivalence classes, and the
____________________________________________________________________________________
35 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
search for frequent item sets is performed within these equivalence classes. While ECLAT is
primarily used for frequent item set mining, it can indirectly contribute to clustering tasks:
Feature Extraction: In clustering tasks, ECLAT can be used to identify frequent item sets of
features occurring together in transactional data. These frequent item sets can then be treated
as new features or dimensions in the dataset, potentially capturing meaningful patterns or
associations among features. The clustering algorithms can be applied to the transformed
dataset to group similar instances based on these extracted features.
Feature Selection: ECLAT can be used for feature selection by identifying frequent item
sets of features occurring together frequently in the dataset. These frequent item sets can be
utilized as input features for classification models.
____________________________________________________________________________________
36 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
import cross_val_score
# UCB-inspired model selection
def ucb_model_selection(estimator, param_grid, X, y, n_iter=50, cv=5):
scores = []
n_params = len(param_grid)
n_iter_per_param = n_iter // n_params
for param in param_grid:
for _ in range(n_iter_per_param):
params = {key: [Link](val) for key, val in param_grid.items()}
clf = estimator.set_params(**params)
cv_scores = cross_val_score(clf, X, y, cv=cv)
[Link]((params, [Link](cv_scores)))
return scores
# Example usage
model_scores = ucb_model_selection(RandomForestClassifier(), param_grid, X, y)
best_params = sorted(model_scores, key=lambda x: x[1], reverse=True)[0][0]
print("Best parameters:", best_params)
____________________________________________________________________________________
37 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example, a UCB-inspired approach is used to select the best hyperparameters for a
Random Forest classifier by sampling hyperparameter combinations from the grid and
evaluating their performance using cross-validation. The approach balances exploration
(trying different hyperparameter combinations) and exploitation (selecting hyperparameter
combinations with high estimated performance).
Thompson Sampling
Dynamic Cluster Selection: Thompson Sampling can be utilized to determine the number of
clusters dynamically or the best clustering algorithm based on uncertainty metrics derived
from the data. As new data points are observed, Thompson Sampling adapts its cluster
assignment strategy to fit the observed patterns best.
for _ in range(n_iter):
# Sample a model from the available options
model = [Link](models)
____________________________________________________________________________________
39 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
A Thompson Sampling-inspired approach selects the best classification model from a set of
Random Forest classifiers. The algorithm iteratively selects models based on their
performance on cross-validated data, adapting its selection strategy over time.
____________________________________________________________________________________
40 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Visualizations are the easiest way to analyze and absorb information. Visuals help to
understand the complex problem quickly. They assist in identifying patterns, relationships,
and outliers in data. It assists in understanding business problems better and quickly. It helps
to build a compelling story based on visuals. Insights gathered from the visuals help create
strategies for businesses. It is also a precursor to many high-level data analyses for
Exploratory Data.
Exploratory Data Analysis (EDA) and Machine Learning (ML). Matplotlib is a 2-D plotting
library that helps in visualizing figures. Matplotlib emulates Matlab-like graphs and
visualizations. Matlab is not accessible, is challenging to scale, and is tedious as a
programming language. So, matplotlib in Python is used as it is a robust, accessible, and easy
library for data visualization. In machine learning, advanced data visualization using
Matplotlib often involves creating visualizations to analyze and understand data, evaluate
model performance, and communicate insights effectively. Matplotlib.
Correlation Matrix Visualization: Visualizing the correlation matrix helps understand the
relationships between features, which is helpful for feature selection and identifying
multicollinearity.
____________________________________________________________________________________
41 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
importances = model.feature_importances_
indices = [Link](importances)[::-1]
[Link]()
____________________________________________________________________________________
42 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
[Link]('Feature Importances')
[Link]([-1, [Link][1]])
[Link]()
Partial Dependence Plots (PDP): PDPs visualize the relationship between a feature and the
target variable while marginalizing the values of other features, providing insights into the
effect of individual features on predictions.
These advanced visualization techniques using Matplotlib can significantly enhance the
understanding of data, model behaviour, and performance in machine learning tasks,
ultimately aiding in model development, evaluation, and interpretation. Matplotlib is a
powerful library in Python that creates static, interactive, and animated visualizations.
Matplotlib offers various features and customization options for advanced data visualization.
Subplots and Grids: Subplots and grids allow creating multiple plots within the exact figure
and comparing different datasets or aspects of the same data.
Here is an example for creating multiple plots and comparing different dataset.
____________________________________________________________________________________
43 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
44 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
3D Plotting: Matplotlib can create 3D plots for visualizing data in three dimensions.
Animations: Matplotlib supports creating animations for visualizing dynamic data over time.
____________________________________________________________________________________
45 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Quantile-quantile (Q-Q) plots are a type of data visualization commonly used to assess
whether a given dataset follows a particular probability distribution or to compare the
distribution of two datasets. In a Q-Q plot, the quantiles of the observed data are plotted
against the quantiles of a theoretical distribution (e.g., normal distribution) or another dataset.
____________________________________________________________________________________
46 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In the above example, we generate random data from a normal distribution using numpy.
Random. Usual ().We then use [Link]() to create the Q-Q plot. We pass the
observed data (data) and specify the distribution we want to compare against (dist= "norm"
for a normal distribution). To define the plot to use (plt) to integrate with Matplotlib. Finally,
we add labels and a title to the plot using Matplotlib's xlabel(), ylabel(), and title() functions.
The resulting plot will display points representing the quantiles of the observed data plotted
against the quantiles of the specified theoretical distribution (in this case, the normal
distribution). If the observed data closely follows the restricted distribution, the points will
fall approximately along a diagonal line. Create Q-Q plots to compare two datasets by
passing the two datasets as arguments [Link](). For the given example: #
Generate another dataset from a normal distribution
fig, ax = [Link]()
[Link]('Quantiles of data')
[Link]('Quantiles')
[Link]()
Statistical Characterization
Statistical characterization refers to the process of describing and summarizing a dataset
using statistical measures and techniques. It involves analyzing the central tendency,
variability, distribution, and relationships within the data to gain insights into its properties
and behavior. Statistical characterization is essential for understanding the underlying
structure of data, identifying patterns, and making informed decisions. Some common
statistical characteristics include:
Central Tendency:
Mean: The average value of the dataset is calculated by summing all values and dividing by
the number of observations.
Median: The middle value of the dataset, sorted in ascending order, represents the median
value. It represents the central value that divides the dataset into two halves.
Mode: Most frequently occurring value(s) in the dataset.
Variability:
Range: Maximum and minimum difference of the values in the dataset, providing a measure
ofdata spread.
Variance: An average of the squared differences between each data point and the mean. It
quantifies the dispersion of data points around the mean value.
Standard Deviation: The variance measures the average deviation of data points from the
mean and is expressed in the same units as the original data distribution: A histogram is a
graphical representation of the frequency distribution of data, showing the frequency of
values within predefined intervals or bins.
Probability Density Function (PDF): PDF describes the continuous random variable taking
on a particular value. It provides insights into the shape and probability distribution of the
data.
Cumulative Distribution Function (CDF): A function that gives a probability that the
random variable takes a value less than or equal to a given value. It represents the cumulative
probabilities of the data.
____________________________________________________________________________________
48 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Relationships:
Correlation Coefficient: The correlation coefficient is the linear relationship between two
variables. It ranges from -1 to 1 to show a positive correlation. Values too low indicate a
strong negative correlation, and values close to 0 show no linear correlation.
Scatter Plot: A scatter plot graph is a graphical representation of the relations of two
variables, with a plotted on the x-axis for one variable and the other on the y-axis. It helps
visualize patterns and trends in the data. Statistical characterization techniques provide a
comprehensive overview of the dataset's properties and facilitate data exploration, hypothesis
testing, and model development in various fields such as science, engineering, finance, and
social sciences.
In the Parallel coordinates plots, a clear pattern emerges. Flowers belonging to setosa species
have large seal widths but low seal length, petal width, and length. Flowers belonging to
versicolor species have low Sepal Widths and medium Sepal Lengths, Petal Width, and
Length. Flowers belonging to Virginia species have low to medium Sepal Widths, medium to
large Sepal Lengths, and large Petal Widths and Lengths.
Order: The features can be ordered so that only a few lines intersect, resulting in an
unreadable chart. To make a Parallel Coordinates plot using Python by highlighting one or
more lines? For example use the Olympics dataset for the year of 2020-2021 to illustrate the
use of a parallel coordinates plot. This dataset has details about the teams that have
participated – country, disciplines, athletes who have participated – country, athletes final
medals tally – country, rank, total medals, and the split across gold, silver, bronze medals.
import pandas as pd
df_teams = pd.read_excel("data/[Link]")
df_athletes = pd.read_excel("data/[Link]")
df_medals = pd.read_excel("data/[Link]")
print(df_teams.info())
print(df_athletes.info())
The bar charts plot each country's athletes, disciplines, ranks, and medals data. For
better readability, use only the top 20 entries, plt. figure(figsize=(20, 5))
____________________________________________________________________________________
49 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
ax = [Link](1,2,1)
ax = [Link](1,2,2)
[Link](figsize=(20, 5))
ax = [Link](1,2,1)
ax = [Link](1,2,2)
multiple plots
Range: start and end values specified as a list or tuple: values where the ticks should be
displayed on this axis tick text: text that should be shown at the ticks label: name of the axis
Values: values that should be plotted on that axis. Then, create a Parcoords, a list of
attributes for the figure.
Correlation Plots
Correlation plots, also known as correlation matrices or correlation heatmaps, are a type of
data visualization used to explore the pairwise correlations between variables in a dataset.
They are beneficial for identifying relationships between multiple variables to understand the
strength and direction of those relationships. And the correlation plots work.
____________________________________________________________________________________
50 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Correlation Calculation:
First, the correlation coefficient between each pair of variables in the dataset is calculated.
The most common correlation coefficient used is Pearson's linear relationship between two
continuous variables with measure. Other correlation coefficients, such as Spearman's rank
correlation coefficient, can be used for ordinal or non-linear relationships. Plotting: The
correlation coefficients are then visualized in a matrix format, with each cell representing the
correlation between a pair of variables.
Typically, the matrix is symmetric along the diagonal, as the correlation between two
variables, A and variable B, is the same as between variable B and variable.
● Colour Mapping: To enhance interpretability, the correlation coefficients are often
color-coded, with a gradient ranging from one color (e.g., blue) to another (e.g., red).
This gradient represents the strength and direction of the correlation, with positive
correlations shown in one color and negative correlations in another. Here, the intensity
of the color corresponds to the magnitude of the correlation coefficient.
Interpretation: By examining the correlation matrix, you can quickly identify highly
correlated variables (either positively or negatively) with each other. Strong positive
correlations (close to +1) indicate that the variables tend to increase or decrease together. In
contrast, strong negative correlations (close to -1) suggest that one variable rises as the other
decreases. A correlation coefficient close to 0 indicates little to no linear relationship between
the variables. Correlation plots are commonly used in various fields, such as statistics,
finance, biology, and machine learning, to gain insights into the relations between variables
and to guide further analysis or modeling efforts. They provide a visual summary of the
correlation structure of the data, making it easier to identify patterns and dependencies.
To create a correlation plot (correlation matrix or heatmap) using Matplotlib, follow these
steps:
● Import the necessary libraries.
● Prepare your data and calculate the correlation matrix.
● Create a heatmap to visualize the correlation matrix.
An example to show correlation plots in matplotlib:
____________________________________________________________________________________
51 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
This example generates a random correlation matrix (data) for demonstration purposes.
What each part of the code does:
[Link](data): Calculates the correlation matrix using NumPy's corrcoef function.
● imshow(): Plots the correlation matrix as a heatmap.
cmap='coolwarm': Sets the colormap to coolwarm to better visualize positive and negative
correlations.
● Color bar (): Adds a color bar to the plot to indicate the correlation values.
[Link]() and [Link](): Sets the labels for the x and y axes with appropriate tick
positions.
Adjust the figure size, colormap, and other parameters according to the preferences.
Additionally, if the column names for the dataset are different, we can replace the tick labels
with the actual variable names for better readability.
____________________________________________________________________________________
52 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Pareto Charts
data <- [Link](Defect_Type = c('A,' 'B,' 'C,' 'D,' 'E'),Frequency = c(50, 30, 20, 15, 10))
data_sorted$Cumulative_Percentage<-cumsum(data_sorted$Frequency)
/sum(data_sorted$Frequency) *100
Using Python and R, generate Pareto charts based on the provided data. In Python, using
Matplotlib for plotting, while in R, utilize the library ggplot2. The key concept is to sort the
data in descending order of frequency and then calculate the cumulative percentage.
Heatmaps
Heatmaps in Python and R are graphical representations of data where values in a matrix are
represented as colors. They are commonly used in machine learning for visualizing various
types of data, including correlation matrices, confusion matrices, and feature importance
matrices, among others. Python, Seaborn is often used for creating heatmaps due to its
simplicity and aesthetics, while in R, ggplot2 provides powerful tools for visualization,
including heatmaps.
____________________________________________________________________________________
54 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
The above example, np. [Link](10, 10) generates a 10x10 array of random numbers or
variables between 0 and 1, representing the data. [Link]() displays the
[Link]='hot' specifies the colormap;
● Color bar () adds a color bar to the plot for reference.
● Title (), plot. Label (), and plot. Label () adds a title and labels to the plot.
Advanced data visualization in ggplot refers to the use of advanced techniques and
functionalities within the ggplot2 package in R to create highly customized and intricate
visualizations. The library ggplot2 is a flexible package for creating static, interactive, and
multi-layered plots based on the grammar of graphics concepts. Some of the advanced data
visualization techniques in ggplot include:
Faceting: Faceting allows you to create small multiples of plots based on one or more
categorical variables.
Layering: ggplot2 allows you to add multiple layers to a plot, allowing for complex
visualizations. You can add layers for points, lines, bars, text, etc., and customize each layer
independently.
Geometric objects: ggplot2 provides a wide range of geometric objects (geoms) such as
points, lines, bars, polygons, and more. You can customize the appearance of these geoms
using aesthetics (aes) mappings.
Themes: Themes in ggplot2 allow you to customize the appearance of the plot elements such
as background, grid lines, text, and overall style. Create the custom themes or use pre-defined
themes provided by ggplot2.
____________________________________________________________________________________
55 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Scale customization: ggplot2 allows you to customize the scale of axes, colors, sizes, etc.
You can change the scale type (e.g., linear, logarithmic), labels, breaks, and limits.
Statistical transformations: ggplot2 provides various statistical transformations (stats) that
can be applied to the data before plotting. It includes summarizing data (e.g., mean, median),
smoothing data (e.g., loess, smoothing splines), and more.
Annotations: You can add annotations such as text, labels, arrows, and shapes to highlight
specific aspects of the plot. Using the functions like geom_text(), geom_label(), and
annotate().
Interactive visualizations: While ggplot2 primarily generates static plots, you can integrate
it with other packages like ggplotly to create interactive plots that can be explored
dynamically.
In Matplotlib, ggrepel-like functionality for legends, where the labels adjust their positions
automatically to avoid overlap, is not directly available. However, there is similar
functionality by changing the legend manually using the bbox_to_anchor parameter of the
plt. legend() function.
Here is an example of how you can create a scatter plot with legends that avoid overlap:
____________________________________________________________________________________
56 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example, Line2D is used to create custom legend elements with markers that match
the colors of the scatter plots,bbox_to_anchor=(1, 1) places the legend outside the plot area in
the upper right corner. By adjusting the bbox_to_anchor values, the legend's position is
controlled to avoid overlapping with data points.
____________________________________________________________________________________
57 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Using the Seaborn library to reconstruct all the charts done using matplotlib
The Seaborn library is a Python data visualization library and provides a high-level interface
for creating attractive and informative statistical graphics using matplotlib. It complements
Matplotlib's functionalities and simplifies the process of creating complex visualizations.
Seaborn offers a variety of built-in themes and color palettes and provides functions for
creating complex statistical plots with minimal code. Seaborn provides similar functions for
various types of plots, and it's often preferred for its aesthetic appeal and ease of use in
creating complex statistical visualizations. Matplotlib package is a powerful tool for low-
level customization and flexibility in plotting the statistical graphics and visualizations in
Python.
1. High-Level interface: The Seaborn library provides the APIs to create statistical visuals.
2. Attractive Defaults: Seaborn comes with attractive default styles and color palettes,
making it easy to create visually appealing plots without much customization.
3. Statistical Plotting: Seaborn offers specialized functions for visualizing statistical
relationships, such as scatter plots, line plots, bar plots, box plots, violin plots, pair plots,
and more. These functions are designed to handle complex data structures like Pandas
DataFrames.
4. Faceted Plotting: Seaborn supports faceted plotting, allowing to easily create grid-based
layouts of plots based on one or more categorical variables.
5. With Pandas: Seaborn seamlessly integrates with Pandas DataFrames, enabling easy
manipulation and visualization of data.
6. Customization: While Seaborn's default styles are attractive, it also provides options for
customizing plots, including color palettes, plot styles, axis labels, titles, and more.
Seaborn is a powerful tool for data visualization in Python, mainly for exploratory data
analysis and for creating publication-quality graphics for presentations, reports, and
publications. It simplifies the process of making seaborn is a popular Python data
visualization library based on Matplotlib.
____________________________________________________________________________________
58 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
59 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
60 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
# Example 3: Histogram
[Link]()
correlation_matrix = [Link]()
[Link]()
In each of the charts using Seaborn functions. Seaborn provides tasks that are specifically
tailored for making these types of visualizations, often with improved aesthetics and default
settings.
____________________________________________________________________________________
61 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Both Seaborn and Matplotlib are powerful data visualization libraries in Python, each with its
own set of pros and cons.
Pros are:
Wide Adoption: Matplotlib is one of the oldest and most widely used plotting libraries in
Python. It's been around for a long time and has a large user base.
Low-level Interface: Matplotlib provides a low-level interface, which means you can create
almost any type of plot from scratch if needed.
Integration: It integrates well with other libraries and tools in the Python ecosystem.
Cons are:
Verbose Syntax: Matplotlib's syntax can be verbose and requires more lines of code to
create complex plots, especially compared to higher-level libraries like Seaborn.
Attractive Defaults: Seaborn has attractive default styles with color palettes and makes it
easy to create visually appealing plots with minimal customization.
Integration with Pandas: Seaborn seamlessly integrates with Pandas DataFrames, allowing
for easy manipulation and visualization of data.
Limited Customization: While Seaborn's default styles are attractive, they can be less
customizable compared to Matplotlib, especially for highly specialized or unconventional
plots.
Less Flexibility: In some cases, the high-level nature of Seaborn's interface may limit
flexibility for users who require highly customized plots.
____________________________________________________________________________________
62 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Bokeh is a powerful Python library for creating interactive and visually appealing data
visualizations for the web. It allows creating interactive plots, dashboards, and applications
directly in Python, Bokeh's key features include:
Interactive Visualization: Bokeh provides tools for creating interactive plots with zooming,
panning, and hovering capabilities, enabling users to explore data interactively.
Flexible and Expressive: Bokeh offers a high-level and flexible API for creating a wide
range of plots, including line plots, scatter plots, bar charts, heat maps, and more. It also
supports complex visualizations like linked plots and interactive dashboards.
Web-Based: Bokeh generates plots as HTML and JavaScript, allowing them to be easily
embedded into web applications or shared as standalone HTML files without the need for a
server backend.
Integration with Jupyter Notebooks: Bokeh can be seamlessly integrated into Jupyter
Notebooks, enabling interactive data exploration and visualization within the notebook
environment.
Plotly is a versatile Python library for creating interactive and visually appealing data
visualizations and a wide range of chart types, including line plots, scatter plots, bar charts,
heat maps, and more. Plotly's key features include:
Interactive Visualization: Plotly generates interactive plots with zooming, panning, and
hovering capabilities, enabling users to explore data interactively.
Web-Based: Plotly generates plots as HTML and JavaScript, making them easily
embeddable into web applications or standalone HTML documents without the need for a
server backend.
High-Quality Graphics: Plotly produces high-quality, publication-ready graphics suitable
for presentations, reports, and publications.
Ease of Use: Plotly offers a simple and intuitive API for creating a wide range of plots with
minimal code.
Integration: Plotly integrates seamlessly with other Python libraries, such as Pandas,
NumPy, and Matplotlib, allowing for easy data manipulation and visualization.
____________________________________________________________________________________
63 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Dimensionality reduction techniques are methods used in data analysis and machine learning
to reduce the number of input variables, and "user" typically refers to an individual
interacting with a system or a platform. It is meant to Various Dimensionality Reduction
Techniques. Dimensionality decrease is a method utilized in AI and measurements to lessen
the number of information factors in a dataset while saving its fundamental elements. It is
beneficial when dealing with high-dimensional data, as it can help improve computational
efficiency, reduce noise, and prevent overfitting. Here are some standard dimensionality
reduction methods:
1. Principal Component Analysis (PCA): PCA is one of the most widely used
dimensionality reduction techniques. It transforms the actual features into a new set of
uncorrelated variables called principal components. These components are ordered by
the amount of variance.
____________________________________________________________________________________
64 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
summary(pca_result)
# Accessing principal components
pcs <- pca_result$x
The prcomp function is then used to perform PCA. The scale. = TRUE argument scales the
variables to have unit variance before [Link] the plot function, visualize the variance
explained and the loadings of each variable on each principal component. PCA captures the
main patterns of the data while reducing it to a lower-dimensional space. The central head
part addresses the course of the most significant fluctuation, and the second head part is
symmetrical to the first and addresses the following most elevated change.
It is important to note that, in practice, PCA is often used as a preprocessing step before other
analyses or modeling tasks, such as clustering or regression, to reduce the data's
dimensionality while preserving its essential characteristics.
Example:
LDA (Linear Discriminant Analysis) is a supervised dimensionality reduction and
classification technique. It finds the linear combinations of features that best separate
multiple classes in a dataset. LDA aims to maximize the distance between the means of
different classes while minimizing the spread (variance) within each class. It is commonly
used for pattern recognition and classification tasks.
Here is a brief explanation along with a simple example in python using the `scikit-learn`
library:
____________________________________________________________________________________
66 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In the example, we use the famous Iris dataset. For visualization purposes, LDA is applied to
reduce the data to two dimensions (`n_components=2`). The resulting plot shows how LDA
transforms the original data into a lower-dimensional space while maximizing the separation
between the three classes of iris flowers. LDA is used for visualization and as a preprocessing
step in classification tasks, where the reduced feature space often leads to improved
classification performance.
____________________________________________________________________________________
67 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In the example, the LinearDiscriminantAnalysis class is used to fit the model on the training
data and make predictions on the test data. The model's accuracy is then calculated using the
accuracy_score function from scikit-learn.
Another Example of R:
____________________________________________________________________________________
68 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In the example, the lda function is used to fit the model to the training data and make
predictions on the test data. The confusion matrix is then calculated, and accuracy is
computed based on its diagonal elements, the Python example; you might need to perform
additional steps such as data preprocessing, parameter tuning, and cross-validation for a more
comprehensive analysis in a real-world scenario.
Markov Chain Monte Carlo (MCMC) methods are a class of algorithms used for sampling
from complex probability distributions, especially when direct sampling is difficult. MCMC
is widely used in Bayesian statistics and other fields. In python, the most commonly used
library for MCMC is PyMC3. PyMC3 is a probabilistic programming library that allows
users to define probabilistic models using a high-level syntax and then perform Bayesian
inference using MCMC methods.
Here is a basic example of using PyMC3 to perform MCMC in Python:
import pymc3 as pm
import 83atpl as np
import [Link] as plt
____________________________________________________________________________________
69 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example, define a simple linear regression model using PyMC3 then specify the slope
and intercept priors and use a normal distribution as the likelihood. The [Link] function
runs the MCMC algorithm to generate samples from the posterior distribution.
____________________________________________________________________________________
70 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example, a simple linear regression model using the Stan modeling language within
the rstan package. The sampling algorithm runs the MCMC function to obtain posterior
distribution samples. The stan_fit object contains the MCMC samples, and you can use
various functions to analyze and visualize the results of the MCMC parameters, perform
model checking, and ensure convergence. PyMC3 provides tools for diagnosing convergence
and assessing the quality of the samples generated by the MCMC algorithm.
____________________________________________________________________________________
71 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
applications in many fields, including speech recognition, bioinformatics, finance, and natural
language processing. In python, the hmmlearn library is commonly used for working with
Hidden Markov Models. Here is a simple example of how to use hmmlearn to create and
train an HMM:
Here is a basic example in Python:
In this example, create a simple HMM using the MultinomialHMM class from hmmlearn.
We generate synthetic data, which represents the observed states over time. The HMM is then
fitted to the data, and the predict method is used to predict the hidden states based on the
observed [Link] hmmlearn library also provides functionalities for generating samples
from an HMM, evaluating likelihoods, and dealing with continuous observations.
To install: pip install hmmlearn
Additionally, explore other Python libraries for hidden Markov models such as pyhsmm or
pomegranate based on your specific needs.
____________________________________________________________________________________
72 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
The Laplace approximation assumes that a Gaussian near its peak can approximate the
posterior distribution well. In R, the laplace() function in the stats package can be used to
perform the Laplace approximation. However, in more complex scenarios, you may need to
implement the approximation manually using numerical optimization techniques.
____________________________________________________________________________________
73 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Replace log_likelihood() with your specific log-likelihood function. The laplace() function
performs the Laplace approximation based on the provided log-likelihood function and an
initial [Link] Bayesian Information Criterion (BIC) is a model selection criterion that
balances the fit of a model to the data with the complexity of the model. When choosing
between different models in statistical modeling and machine learning, it is often used. The
BIC is calculated using the formula:
B I C = −2 log(L) + klog(n)
Where:
● L is the maximized likelihood of the model,
● k is the number of parameters in the model, and
● n is the number of data points.
The BIC can be implemented in Python using libraries like scikit-learn or stats models. Here
is a simplified example:
Example:
from [Link] import GaussianMixture
from [Link] import make_blobs
# Generate synthetic data
X, _ = make_blobs(n_samples=100, centers=3, random_state=42)
# Fit a Gaussian Mixture Model with different numbers of components
for n_components in range(1, 6):
gmm = GaussianMixture(n_components=n_components)
[Link](X)
# Calculate BIC
bic = [Link](X)
print(f"Number of components: {n_components}, BIC: {bic}")
A Gaussian Mixture Model (GMM) is fitted to the synthetic data, and the BIC is calculated
for models with different numbers of components. The idea is to choose the model with the
lowest BIC value, indicating a good balance between model fit and complexity.
In R, you can calculate the BIC using functions from various packages such as stats, MASS,
or specific modeling packages like glm for generalized linear models.
____________________________________________________________________________________
74 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Here is a simplified example of using the BIC with the MASS package using R:
Example
# Load necessary library (if not already installed)
# [Link]("MASS")
library(MASS)
# Fit a model (e.g., linear regression)
model <- lm(y ~ x, data = my_data)
# Calculate BIC
bic <- BIC(model)
# Print the BIC
print(bic)
Replace lm(y ~ x, data = my_data) with the appropriate model fitting function and dataset.
The BIC() function calculates the BIC value for the specified model, which includes the
maximized likelihood and the number of parameters in the model. Lower BIC values indicate
better model fit while penalizing for model complexity.
____________________________________________________________________________________
75 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
● Model Selection
● Model Boosting - Ensemble Method
● Gradient Boosting
● Xgboost
● Adaptive Boosting
● Model Parameters
● Hyperparameter Tuning
Model Evaluation
Model evaluation is the process of evaluating the performance of a prepared model on unseen
data to determine how well it generalizes to new, unseen samples. Model evaluation is
essential for understanding the model's effectiveness and gaining insights into its behavior.
Model evaluation typically involves several key steps and techniques:
1. Holdout Method: The dataset is divided into two subsets- training and testing sets. The
model is prepared on the training set and then evaluated on the separate testing set to
assess its performance on unseen data.
2. Cross-Validation: Instead of a single train-test split, the dataset is divided into multiple
subsets (folds). The model is prepared on k-1 folds and evaluated on the remaining fold;
the process of the test set is repeated k times (every time using a different fold as the test
set). Cross-validation gives a more reliable estimate of the model's performance than the
holdout method, especially with smaller datasets.
3. Performance Metrics: Various metrics are used to quantify the model's performance,
depending on the type of task (classification, regression, clustering, etc.). For
classification tasks, standard metrics include accuracy, precision, recall, F1-score, ROC
AUC (Receiver Operating Characteristic Area under the Curve), etc. For regression
tasks, metrics include Mean Squared Error (MSE), mean absolute error (MAE), R-
squared, etc.
4. Confusion Matrix: For classification tasks, a confusion matrix is often used to visualize
the model's performance in terms of true +ve, true -ve, false +ve, and false -ve. It
provides insights into the model's ability to classify different classes correctly.
5. ROC Curve and Precision-Recall Curve: ROC (Receiver Operating Characteristic)
curves and Precision-Recall curves are graphical representations that are used to assess
binary classification models. They visualize the trade-off between actual positive and
false favorable rates (ROC curves) or precision and recall (Precision-Recall curves) at
different threshold values.
6. Learning Curves: Learning curves plot the model's performance (e.g., training and
validation error) as a function of the training dataset size. They help diagnose issues like
overfitting (high variance) or underfitting (high bias) and provide insights into whether
collecting more data would be beneficial.
In Python, libraries such as scikit-learn (sklearn), TensorFlow, and PyTorch, and in R
libraries such as caret, MLmetrics, and pROC provide built-in functions and utilities for
____________________________________________________________________________________
76 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
model evaluation. These libraries offer a wide range of performance metrics, evaluation
techniques, and visualization tools to assess the quality and efficacy of machine learning
models. Python's rich ecosystem of scientific computing libraries allows custom evaluation
techniques and metrics to be implemented. Additionally, custom evaluation techniques and
metrics can be implemented using R's rich ecosystem of statistical and machine-learning
packages.
Model Selection
Model selection in Python refers to choosing the best-performing model among a set of
candidate models or algorithms for a given task. The model selection goal is to identify the
model that achieves the best balance between model complexity and predictive performance.
Here's an example of model selection using Python and scikit-learn:
[Link](X_train, y_train)
y_pred = [Link](X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"{model.__class__.__name__} Accuracy: {accuracy}")
# Update the best model if the current model performs better
if accuracy > best_accuracy:
best_accuracy = accuracy
best_model = model
# Print the best model
print("\nBest Model:")
print(best_model)
In this example:
1. We load the Iris dataset and divide it into training and testing sets.
2. The list of candidate models includes the Logistic Regression, Decision Tree, and
Random Forest classifiers.
3. To train and evaluate each model on the training and testing data, we print the
accuracy of each model.
4. Finally, we select the model with the highest accuracy as the best model.
Here is an example of model selection using R:
# Load necessary libraries (if not already installed)
# [Link]("caret")
# [Link]("e1071")
library(caret)
library(e1071)
# Load the Iris dataset
data(iris)
####[Link](123) # for reproducibility
trainIndex <- createDataPartition(iris$Species, p = 0.8,
list = FALSE,
times = 1)
data_train <- iris[trainIndex, ]
____________________________________________________________________________________
78 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
4. Utilizing the train function from the caret package, we train each model using the
training data.
5. We evaluate each model on the testing data and compute the accuracy of each model.
____________________________________________________________________________________
79 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
80 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
● Load the iris dataset and divide it into training and testing sets.
● To create an AdaBoost classifier with 50 weak estimators.
● To train the classifier on the training data.
● To make predictions on the test set and calculate the model's accuracy.
In R, the adabag package implements AdaBoost for classification tasks. The gbm
(Generalized Boosted Regression Models) package also offers boosting algorithms for
regression tasks.
Here's a simple example of using AdaBoost for classification in R:
In this example,
● To load the Iris dataset and split it into training and testing sets.
____________________________________________________________________________________
81 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
● To train an AdaBoost classifier using the boosting function from the adabag
package.
● To make predictions on the test set using the trained model.
● To calculate the model's accuracy by comparing the predicted classes to the true
classes in the test set.
Boosting algorithms like AdaBoost are powerful techniques for improving the performance
of weak learners and are widely used in practice for various classification and regression
tasks.
Machine learning, an ensemble method, combines the predictions of multiple individual
models (often called base learners or weak learners) to produce a final prediction. The idea
behind ensemble methods is to leverage the individual models' diversity to improve the
prediction's overall performance and robustness.
There are several types of ensemble methods, including:
1. Voting: Each base learner independently predicts this method; final prediction for the
majority of the votes (for classification of the tasks) or averaging (for regression
tasks) of the individual predictions.
2. Bagging (Bootstrap Aggregating): Bagging involves training multiple base learners
independently on different bootstrap samples (random subsets with replacement) of
the training data. The final prediction is typically obtained by averaging the
predictions of all base learners.
3. Boosting: Boosting algorithms sequentially train a series of base learners, with each
subsequent learner focusing on the errors made by the previous ones. The final
prediction is usually a weighted combination of the projections of all base learners.
4. Stacking: Stacking, also known as stacked generalization, combines the predictions
of multiple base learners using a meta-learner (often a simple linear model). The base
learners' predictions serve as features for training the meta-learner.
x, y = [Link], [Link]
## split the datasets training and testing sets here #
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)#
# Define base classifiers
tree_clf = DecisionTreeClassifier()
knn_clf = KNeighborsClassifier()
log_reg_clf = LogisticRegression()
# Define a voting classifier combining the base classifiers
voting_clf = VotingClassifier(
estimators=[('tree', tree_clf), ('know, knn_clf), ('log_reg', log_reg_clf)],
voting='hard' # Use majority voting
)# Train the voting classifier
voting_clf.fit(X_train, y_train)
# Make predictions on the test set
y_pred = voting_clf.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
In this example,
● To load the Iris dataset and split it into training and testing sets.
● To define three base classifiers: a decision tree classifier, a k-nearest neighbors classifier,
and a logistic regression classifier.
● To create a VotingClassifier ensemble by specifying the base classifiers and the voting
strategy (in this case, majority voting).
● To train the ensemble or same classifier on the training data for making the predictions
on the test set.
● To calculate the accuracy of the ensemble classifier on the test set.
____________________________________________________________________________________
83 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
To load the Iris dataset.
To define three base models: logistic regression (glm), decision tree (rpart), and support
vector machine with radial kernel (svmRadial).
To use the caretStack function from the caretEnsemble package to create an ensemble
model using stacking.
To train the ensemble model on the training data using 5-fold cross-validation.
Finally, print the summary of the ensemble model, which includes information about the
base models and their performance.
Gradient Boosting
Gradient Boosting is a popular ensemble learning technique that builds a robust predictive
model by sequentially adding weak learners (usually decision trees) and fitting them to
the residuals of the previous models. This sequential approach allows gradient Boosting
to continuously increase the model's performance by focusing on the mistakes made by
the last weak learners. In Python, the most widely used implementation of Gradient
Boosting is provided by the GradientBoostingClassifier and
GradientBoostingRegressor classes in the scikit-learn library.
____________________________________________________________________________________
84 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
● To load the Iris dataset and split it into training and testing sets.
● To create a GradientBoostingClassifier with 100 weak learners (decision trees) and
a learning rate of 0.1.
● To train the Gradient Boosting classifier on the training data.
● To make predictions on the test set using the trained classifier.
● To calculate the accuracy of the model on the test set.
Similarly, one can use GradientBoostingRegressor for regression tasks by importing it
from [Link] and applying it to regression datasets.
____________________________________________________________________________________
85 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example:
- To load the datasets for iris.
- To split the training and testing datasets with the `createDataPartition` function from the
`caret` package.
- To train a gradient boosting classifier using the `gbm` function from the `gbm` package.
We specify the number of trees (`[Link]`), the most depth of each tree
(`[Link]`), the shrinkage parameter (`shrinkage`), and the distribution for
classification (`distribution = "multino mial"`). - To predict the test set using the trained
gradient boosting model.
- To convert the predicted probabilities to class labels.
- Finally, calculate the model's accuracy on the test set.
____________________________________________________________________________________
86 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Gradient boosting is a powerful technique for classification and regression tasks, and the
gbm package in R provides a flexible and efficient implementation of this algorithm.
XGBboost
XGBoost, short for eXtreme Gradient Boosting, implements the gradient boosting algorithm.
It is widely used for supervised learning tasks, including classification, regression, and
ranking problems. XGBoost is known for its speed and performance and has won numerous
machine-learning competitions.
Key features of XGBoost include:
1. Regularization: XGBoost includes built-in support for L1 (Lasso) and L2 (Ridge)
regularization to prevent overfitting.
2. Parallelization: XGBoost is highly optimized for parallel computation, enabling
efficient training on large datasets.
3. Tree Pruning: XGBoost uses tree pruning to remove splits that provide little or no
additional information, leading to more efficient and accurate trees.
4. Customizable Objective Functions: XGBoost allows users to define custom loss
functions and evaluation criteria, making it flexible for various tasks.
5. Handling Missing Values: XGBoost can automatically handle the missing values
dataset during the training and prediction data set.
In Python, XGBoost is implemented through the `xgboost` library, which gives an easy-to-
use interface for building and training gradient-boosting models.
To install the library using pip:
pip install xgboost
Here is a simple example of using XGBoost for classification in Python:
library(xgboost)
library(caret)
# Load the Iris dataset
data(iris)
[Link](42) # for reproducibility
train_index <- createDataPartition(iris$Species, p = 0.8, list = FALSE)
train_data <- iris[train_index, ]
test_data <- iris[-train_index, ]
____________________________________________________________________________________
88 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example:
- To load the iris datasets using the `createDataPartition` function from the `caret`
package.
- To convert the data into XGBoost's `DMatrix` format using the `[Link]`
function.
- To define hyperparameters such as the objective function, higher tree depth,
learning rate, and number of rounds.
- To train the XGBoost model using the `xgboost` function.
- To make predictions on the test set using the trained model.
- To calculate the accuracy of the model on the test set.
XGBoost is a powerful and versatile library for gradient boosting. It is widely used in
research and industry for various machine-learning tasks.
____________________________________________________________________________________
89 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Adaptive Boosting
- To train an AdaBoost classifier using the `boosting` function from the `adabag`
package.
- To specify the formula for the model (`Species ~ .`), the data, and set `boos =
TRUE` to indicate that AdaBoost should be used.
- To make predictions on the test set using the trained AdaBoost model.
- To calculate the model's accuracy by comparing the predicted classes to the actual
classes in the test set.
AdaBoost is a robust algorithm for classification tasks and is ultimately used in practice
due to its simplicity and effectiveness, especially when combined with weak learners.
____________________________________________________________________________________
91 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Model Parameters
In the machine learning models, parameters are the configuration settings or variables that the
model learns from the training data. These parameters define the structure and behavior of the
model and are typically adjusted during the training process to optimize the model's
performance.
The Parameters can be classified into two types:
1. Hyperparameters: These parameters are set before the training begins and are not
learned from the data. Examples of hyperparameters include the learning rate,
regularization strength, and the number of layers in a neural network.
Hyperparameters are tuned manually or through automated techniques such as grid or
random search to find the optimal values that yield the best model performance.
2. Model Parameters: These are the parameters that the model learns from the training
data. They represent the relationships and patterns in the data the model captures
during training. For example, the model parameters are the coefficients assigned to
each feature in a linear regression model. In a neural network, the model parameters
are weighted on the neurons in the network.
____________________________________________________________________________________
92 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
● To load the diabetes dataset and split it into training and testing sets.
● To create a linear regression model using the LinearRegression class from scikit-
learn.
● To train the model on the training data using the fit method.
● To obtain the learned model parameters (coefficients) using the coef_ attribute and the
intercept using the intercept_ attribute.
These learned model parameters represent the linear relationship and the features of the
target variable in the training data, as captured by the linear regression model.
Here's an example in R using a linear regression model:
In this example,
- To load the mtcars dataset.
- A linear regression model uses the lm function, where mpg is the response
variable, and cyl, disp, hp, and wt are the predictor variables.
- To extract the learned model parameters (coefficients) using the coef function.
The model_parameters object contains the coefficients of the linear regression model,
which represent the relationships between the predictor variables and response variables.
Model parameters can vary depending on the type of model being used. For example, in a
neural network, model parameters would include the weights and biases of the neurons.
In contrast, model parameters would consist of the splitting thresholds and leaf values in a
decision tree.
____________________________________________________________________________________
93 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Hyperparameter Tuning
Hyperparameters are configuration settings set before the training process begins and are not
learned from the data. Hyperparameters include learning rate, regularization strength, and the
number of layers in a neural network. Tuning these hyperparameters is crucial for achieving
the best performance of the model. Several techniques for hyperparameter tuning exist,
including grid search, random search, and Bayesian optimization. In Python using grid search
for hyperparameter tuning with a support vector machine (SVM) classifier:
____________________________________________________________________________________
95 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
● To define a grid of hyperparameters to search through. In this case, we're tuning the
regularization parameter C, the kernel coefficient gamma, and the kernel type kernel.
● To create a training control object with 5-fold cross-validation.
● To perform a grid search using the train function from the caret package to find the
best hyperparameters from the grid.
● To extract the best hyperparameters found by the grid search.
● To get the best model obtained after tuning.
● To make predictions on the test set using the best model.
● To calculate the accuracy of the best model on the test set.
Grid search is a simple yet effective method for hyperparameter tuning, but it can be
computationally expensive, especially for large hyperparameter grids. Other techniques like
random search or Bayesian optimization may be more efficient in some cases.
____________________________________________________________________________________
96 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
1. Narrow AI refers to AI systems designed and trained for specific tasks or domains. These
systems excel at performing particular tasks but cannot generalize their knowledge
beyond their predefined scope. Examples of narrow AI include virtual assistants (e.g.,
Siri, Alexa), image recognition systems, spam filters, and recommendation systems.
2. General AIrefers to AI systems with human-like intelligence capable of understanding,
learning, and reasoning across diverse tasks and domains. General AI can transfer the
knowledge and skills from one to another domain, adapt to new situations, and exhibit
creativity and consciousness. However, achieving true general AI remains an aspirational
goal and is currently a subject of research and speculation.
Essential techniques and approaches in AI include the following:
Machine learning: A subset of AI that creates algorithms and models that allow the
computers to learn from the data and make predictions and decisions without being explicitly
programmed. Machine learning includes supervised learning, unsupervised learning, and
reinforcement learning.
Deep learning: It is the part of machine learning that uses multilayer artificial neural
networks (deep neural networks) that can learn complex patterns and representations from
large amounts of data. Deep learning has been incredibly successful in tasks such as image
recognition, natural language processing, and speech recognition.
____________________________________________________________________________________
97 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Natural Language Processing (NLP): It is a field of computer science that focuses on the
interactions between computers and humans, enabling computers to understand and generate
human language. NLP techniques are used in machine translation, sentiment analysis,
chatbots, and text summarization applications.
Computer Vision: The field of computer vision allows machines to interpret and
comprehend visual information from the real world. Computer vision techniques are used in
object detection, image classification, facial recognition, and medical image analysis.
Robotics: It is the intersection of AI, engineering, and robotics aimed at designing and
developing intelligent robots capable of performing tasks autonomously or collaboratively
with humans. Robotics applications range from industrial automation and autonomous
vehicles to assistive robots in healthcare and home environments.
AI has the potential to revolutionize the various aspects of society, driving innovation,
efficiency, and progress. However, it also raises ethical, societal, and philosophical questions
regarding privacy, bias, job displacement, autonomy, and the future of humanity. As AI
advances, it is essential to ensure responsible development and deployment practices that
prioritize ethical considerations, transparency, fairness, and accountability.
Neural networks can learn the complex patterns and relationships in data by adjusting their
weights and biases through training. This process typically involves feeding input data
through a network, comparing the predicted output with the actual production, and updating
the network's parameters using optimization algorithms such as gradient descent. In Python,
neural networks are commonly implemented using libraries such as TensorFlow, Keras, and
PyTorch. Here is a simple example of building a neural network for image classification
using Keras:
Here is an Example:
import numpy as np
from [Link] import mnist
from [Link] import Sequential
from [Link] import Dense, Flatten
from [Link] import to_categorical
# Load the MNIST dataset
____________________________________________________________________________________
98 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
● To load the MNIST dataset, consisting of grayscale handwritten digit images (0-9).
● To preprocess the data by scaling pixel values to the range [0, 1].
● To define a neural network architecture using Keras' Sequential API. The network
consists of an input layer (Flatten), two hidden layers (Dense), and an output layer
(Dense) with softmax activation.
● To accumulate the model with the Adam enhancer and categorical cross-entropy loss
function.
● To train the model on the training data for five epochs using a batch size of 32.
● Finally, assess the trained model on the test data and print the test accuracy.
____________________________________________________________________________________
99 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In R, neural networks can be implemented using packages such as ‘keras’, ‘nnet’, or ‘neuralnet’.
Here's a simple example of building a neural network for binary classification using the ‘keras’
package:
____________________________________________________________________________________
100 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
Neural networks are versatile models capable of learning complex patterns in various data
types, making them suitable for multiple applications, including image classification, natural
language processing, and reinforcement learning.
import numpy as np
from [Link] import Sequential
from [Link] import Dense
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import accuracy_score
# Generate synthetic data for binary classification
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
# Split the data 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)
# Scale the features
____________________________________________________________________________________
101 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = [Link](X_test)
# Build the neural network architecture
model = Sequential([
Dense(128, activation='relu', input_shape=(20,)),
Dense(64, activation='relu'),
Dense(1, activation='sigmoid')
])
# Compile the model
[Link](optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model
[Link](X_train_scaled, y_train, epochs=10, batch_size=32, validation_split=0.2)
# Evaluate the model
y_pred = model.predict_classes(X_test_scaled).flatten()
accuracy = accuracy_score(y_test, y_pred)
print("Test Accuracy:", accuracy)
In this example,
● To generate synthetic data for binary classification using the make_classification
function from scikit-learn.
● To split the data into training and testing sets.
● To normalize the features to have a mean of 0 and a unit variance.
● To define a feedforward neural network with three dense layers using the Sequential
API from Keras. The network has two hidden layers with ReLU activation and a put
layer with sigmoid activation for binary classification.
● To accumulate the model with the Adam enhancer and a binary cross-entropy loss
function.
● This model is trained on the training dataset for 10 epochs, utilizing a batch size of 32
for each epoch.
● Then, assess the trained model on the test data and print the test accuracy.
ANNs can be implemented using keras, nnet, or neuralnet packages in R. Here is a simple
example of building a feedforward neural network for binary classification using the keras
package:
____________________________________________________________________________________
102 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
103 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
validation_split = 0.2)
# Evaluate the model
model %>% evaluate(X_test, y_test)
In this example:
● To generate synthetic data for binary classification.
● To split the data into training and testing sets.
● To use the Keras package to define a feedforward neural network with three dense
layers. The network has two hidden layers with ReLU activation and a put layer with
sigmoid activation for binary classification.
● To utilize the Adam optimizer and binary cross-entropy loss function to compile the
model.
● The model undergoes training on the training data for 10 epochs, utilizing a batch size
of 32.
● Finally, assess the trained model on the test data.
Artificial Neural Networks are powerful models capable of learning complex patterns in
various data types, making them suitable for multiple applications, including classification,
regression, image recognition, and natural language processing.
import numpy as np
import [Link] as plt
from [Link] import mnist
from [Link] import Sequential
from [Link] import Conv2D, MaxPooling2D, Flatten, Dense
from [Link] import to_categorical
____________________________________________________________________________________
104 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
105 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
- To load the MNIST dataset, which consists of 28x28 pixel grayscale images of handwritten
digits (0-9).
-To ingest the MNIST dataset, comprising 28x28 pixel grayscale images representing
handwritten digits ranging from 0 to 9.
- To preprocess the data by scaling pixel values to the range [0, 1].
- To define a CNN architecture using Keras's `Sequential API. The architecture of CNN
includes two convolutional layers with ReLU activation followed by max-pooling and fully
connected layers.
- To build the model, we utilize the Adam optimizer and the categorical cross-entropy loss
function.
- This model is trained on the training dataset for 10 epochs, utilizing a batch size of 32 for
each epoch. Finally, we assess the trained model on the test data and print the test accuracy.
We also plot the training and validation accuracy over epochs.
In R, Convolutional Neural Networks (CNNs) can be implemented using the keras package,
which provides an interface to TensorFlow and allows for building and training deep learning
models. Here's an example of building a simple CNN for image classification using the keras
package in R:
____________________________________________________________________________________
106 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
● To load the MNIST dataset, which consists of 28x28 pixel grayscale images of
handwritten digits (0-9).
● To preprocess the data by reshaping the images and scaling pixel values to the range
[0, 1].
● To define a CNN architecture using the keras_model_sequential() function from the
keras package. The architecture of CNN comprises two convolutional layers with
ReLU activation, followed by max-pooling and fully connected layers.
● To compile a model with Adam optimizer and categorical cross-entropy loss function.
● This trains the model on the training data for 5 epochs with a batch size of 32.
● To evaluate the trained model on the test data and print the test accuracy.
____________________________________________________________________________________
107 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
CNN are powerful models that are widely used for image classification in computer vision
applications. The keras package in R provides a convenient interface for building and training
CNNs, leveraging the capabilities of the TensorFlow backend. CNNs have revolutionized
computer vision and are used in image recognition, object detection, and image segmentation.
They are particularly effective in extracting hierarchical features from images, making them
suitable for understanding complex visual patterns.
‘’’python
import numpy as np
import [Link] as plt
from [Link] import Sequential
from [Link] import SimpleRNN, Dense
from sklearn.model_selection import train_test_split
# Generate synthetic time series data
def generate_time_series_data(n_samples, n_steps):
freq1, freq2, offset1, offset2 = [Link](4, n_samples, 1)
time = [Link](0, 1, n_steps)
series = 0.5 * [Link]((time - offset1) * (freq1 * 10 + 10)) # wave 1
series += 0.2 * [Link]((time - offset2) * (freq2 * 20 + 20)) # + wave 2
return series[..., [Link]].astype(np.float32)
# Generate synthetic time series data
n_samples = 10000
n_steps = 50
series = generate_time_series_data(n_samples, n_steps)
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(series[:, :n_steps-1, :], series[:, 1:, :],
test_size=0.2, random_state=42)
____________________________________________________________________________________
108 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
- To generate synthetic time series data with two sine waves of different frequencies.
- To split the data into training and testing sets.
- To define an RNN architecture using Keras's `Sequential API. The RNN consists of two
Simple RNN layers with 20 units each and a dense output layer.
-To use the Adam optimizer and mean squared error (MSE) loss function to compile the
model.
____________________________________________________________________________________
109 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Recurrent Neural Networks (RNNs) can be implemented using the `keras` package, which
provides an interface to TensorFlow and allows for building and training deep learning
models. Here is an example of building a simple RNN for time series prediction using the
`keras` package in R:
```R
# Install and load necessary packages
# [Link]("keras")
library(keras)
library(tidyverse)
# Generate synthetic time series data
generate_time_series_data <- function(n_samples, n_steps) {
freq1 <- runif(n_samples)
freq2 <- runif(n_samples)
offset1 <- runif(n_samples)
offset2 <- runif(n_samples)
time <- seq(0, 1, [Link] = n_steps)
series <- 0.5 * sin((time - offset1) * (freq1 * 10 + 10)) +
0.2 * sin((time - offset2) * (freq2 * 20 + 20))
return([Link](series))
}
# Generate synthetic time series data
n_samples <- 10000
n_steps <- 50
series <- generate_time_series_data(n_samples, n_steps)
____________________________________________________________________________________
111 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
- To generate synthetic time series data with two sine waves of different frequencies.
- To split the data into training and testing sets.
- To define an RNN architecture using the `keras_model_sequential()` function from the
`keras` package. The RNN consists of two `SimpleRNN` layers with 20 units each and a
dense output layer.
- To compile the model with the Adam optimizer and mean squared error (MSE) loss
function.
- To train the model on the training data for 20 epochs.
- Finally, plot the training and validation loss curves and visualize example predictions made
by the model.
RNNs are powerful models for sequential data modeling and prediction tasks. Temporal
dependencies in data can be captured by them, making them suitable for a wide range of
applications.
Basics of Backpropagation
Backpropagation is a fundamental algorithm used for training artificial neural networks,
including deep learning models. Efficiently compute gradient of loss function network
weights, essential for updating during training.
____________________________________________________________________________________
112 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
[1],
[0]])
# Initialize random weights and biases
[Link](42)
weights_input_hidden = [Link](2, 3)
weights_hidden_output = [Link](3, 1)
biases_hidden = [Link](1, 3)
bias_output = [Link](1, 1)
learning_rate = 0.1
# Training loop
for epoch in range(10000):
# Forward pass
hidden_layer_input = [Link](X, weights_input_hidden) + biases_hidden
hidden_layer_output = sigmoid(hidden_layer_input)
output_layer_input = [Link](hidden_layer_output, weights_hidden_output) + bias_output
predicted_output = sigmoid(output_layer_input)
# Compute loss
loss = [Link]((y - predicted_output) ** 2)
# Backward pass (backpropagation)
output_error = (y - predicted_output) * sigmoid_derivative(predicted_output)
hidden_error = [Link](output_error, weights_hidden_output.T) *
sigmoid_derivative(hidden_layer_output)
# Update weights and biases
weights_hidden_output += [Link](hidden_layer_output.T, output_error) * learning_rate
bias_output += [Link](output_error, axis=0, keepdims=True) * learning_rate
weights_input_hidden += [Link](X.T, hidden_error) * learning_rate
biases_hidden += [Link](hidden_error, axis=0, keepdims=True) * learning_rate
# Print loss every 1000 epochs
if epoch % 1000 == 0:
print(f'Epoch: {epoch}, Loss: {loss}')
____________________________________________________________________________________
114 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
print(predicted_output)
In this example,
- To define a simple neural network with one hidden layer and one output layer.
- To initialize random weights and biases.
- To perform the forward pass to compute the predicted output.
- To compute the loss using mean squared error.
- To perform the backward pass (backpropagation) to compute gradients.
- To update weights and biases using the gradients and a learning rate.
- To repeat this process for multiple epochs until convergence.
In this example,
- To define a simple neural network with one hidden layer and one output layer using the
`keras` package.
- To compile the model with stochastic gradient descent (SGD) optimizer and binary cross-
entropy loss function.
- To define input and target data for binary classification.
- To train the model on the input and target data for 1000 epochs with a batch size of 1.
- To visualize the training history and print the summary of the trained model, to have
completed the training process, can utilize the model to forecast outcomes.
```python
import numpy as np
from [Link] import Sequential
from [Link] import Dense
from [Link] import make_classification
from sklearn.model_selection import train_test_split
____________________________________________________________________________________
116 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
```R
# Install and load necessary packages
# [Link]("keras")
library(keras)
library(tidymodels)
# Generate synthetic data for binary classification
[Link](42)
data <- synthetic_classification(n = 1000, noise = 0.1) %>%
[Link]()
# Split the data into training and testing sets
split <- initial_split(data, prop = 0.8, strata = Class)
train_data <- training(split)
test_data <- testing(split)
# Preprocess the data
preprocess <- recipe(Class ~ ., data = train_data) %>%
step_scale(all_predictors()) %>%
step_center(all_predictors()) %>%
prep()
train_data_prep <- bake(preprocess, train_data)
test_data_prep <- bake(preprocess, test_data)
# Define the neural network architecture
model <- keras_model_sequential() %>%
layer_dense(units = 128, activation = 'relu', input_shape = ncol(train_data_prep) - 1) %>%
layer_dense(units = 64, activation = 'relu') %>%
layer_dense(units = 1, activation = 'sigmoid')
# Compile the model
model %>% compile(
loss = 'binary_crossentropy',
optimizer = optimizer_adam(),
metrics = c('accuracy'))
# Train the model
history <- model %>% fit(
x = [Link](select(train_data_prep, -Class)),
y = [Link](train_data_prep$Class) - 1, # Convert to numeric and zero-indexed
____________________________________________________________________________________
118 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
epochs = 10,
batch_size = 32,
validation_split = 0.2)
# Evaluate the model
model %>% evaluate(
x = [Link](select(test_data_prep, -Class)),
y = [Link](test_data_prep$Class) - 1 # Convert to numeric and zero-indexed)
In this example,
- To generate synthetic data for binary classification using the `synthetic_classification`
function from the `tidymodels` package.
- To use the 'initial_split' function from the 'tidymodels' package to divide data into training
and testing sets.
- To preprocess the data by scaling and centering the predictors using the `recipe` and `bake`
functions from the `tidymodels` package.
- To use the `keras_model_sequential` function from the `keras` package to define a neural
network architecture that consists of two hidden layers and an output layer.
- To compile the model with the binary cross-entropy loss function, Adam optimizer, and
accuracy metric.
- This model is trained on the training dataset for 10 epochs, utilizing a batch size of 32
for each epoch.
-To calculate the trained model on the test data using the `evaluate` method from the `keras`
package.
This is a simple example of implementing a neural network for binary classification using
Python with TensorFlow and Keras. The architecture, hyperparameters, and other aspects of
the model to suit your specific problem.
Text mining involves extracting meaningful insights from unstructured text data. Sentiment
analysis involves identifying subjective information from text, such as opinions and
emotions, and determining their polarity as positive, negative, or neutral.
In this example,
- To load a dataset containing Amazon product reviews and their corresponding labels
(positive or negative sentiment).
- To split the dataset into testing and training sets.
- To use the Bag-of-Words (BoW) approach to convert text data into numerical features.
- To train a classifier (Multinomial Naive Bayes) using the training data.
- To make predictions on the testing set and evaluate the classifier's performance using
accuracy and a classification report.
____________________________________________________________________________________
120 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
# [Link]("tidyverse")
# [Link]("textdata")
# [Link]("tm")
# [Link]("wordcloud")
library(tidyverse)
library(textdata)
library(tm)
library(wordcloud)
# Load the dataset
data <- [Link]("amazon_reviews.csv")
# Explore the dataset
head(data)
# Preprocess the text data
corpus <- Corpus(VectorSource(data$Review))
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, removeWords, stopwords("en"))
corpus <- tm_map(corpus, stripWhitespace)
# Convert the corpus to a document term matrix
dtm <- DocumentTermMatrix(corpus)
# Build a word cloud to visualize most frequent words
word_freq <- colSums([Link](dtm))
wordcloud(names(word_freq), word_freq, [Link] = 50, [Link] = FALSE)
# Perform sentiment analysis
sentiment <- textdata_sentiment(data$Review)
print(sentiment)
In this example,
- To load a dataset containing Amazon product reviews and their corresponding text.
- To preprocess the text data, including converting text to lowercase and removing numbers,
punctuation, stopwords, and extra whitespaces.
- To create a document term matrix (DTM) to represent the frequency of words in the corpus.
- To visualize the most frequent words using a word cloud.
____________________________________________________________________________________
121 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
- To perform sentiment analysis using the `textdata_sentiment` function from the `textdata`
package, which provides sentiment scores (positive, negative, neutral) for each review.
A basic approach to sentiment analysis using text mining techniques in python. There are
more advanced methods and techniques available, including deep learning models (e.g.,
recurrent neural networks, transformers) and pretrained language models. Depending on the
specific task and requirements, to explore and experiment with different approaches to
achieve better performance.
Word Cloud
A word cloud is a visual representation of text data where the size of each word indicates its
frequency or importance.
```python
from wordcloud import WordCloud
import [Link] as plt
# Sample text data
text = "Python is an amazing programming language. It is used for data analysis, machine
learning, and web development. Python has a large community and extensive libraries."
# Generate a word cloud
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
# Plot word cloud
[Link](figsize=(10, 5))
[Link](wordcloud, interpolation='bilinear')
[Link]('off')
[Link]()
In this example,
- First import the `WordCloud` class from the `wordcloud` library and `[Link]` for
plotting.
- Define some sample text data.
- Generate the word cloud using the `WordCloud` class, specifying the width, height, and
background color.
- Finally, plot the word cloud using `[Link]()` and configure the plot with
`[Link]('off')` to remove axes and `[Link]()` to display the plot.
In R, create a word cloud using the `wordcloud` package, which provides a simple interface
for generating word clouds. Here is an example of creating a word cloud in R:
```R
# Install and load necessary packages
____________________________________________________________________________________
122 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
# [Link]("wordcloud")
library(wordcloud)
# Sample text data
text <- "Python is an amazing programming language. It is used for data analysis, machine
learning, and web development. Python has a large community and extensive libraries."
# Generate word cloud
wordcloud(words = strsplit(text, " ")[[1]], freq = NULL, scale = c(3, 0.5), [Link] = 1,
[Link] = 100, [Link] = TRUE, [Link] = 0.35, colors = [Link](8,
"Dark2"))
In this example,
- First load the `wordcloud` package.
- Define some sample text data.
- Generate the word cloud using the `wordcloud` function. To provide the words as a vector
(extracted from the text using `strsplit`) and specify various parameters such as scale,
[Link], [Link], [Link], [Link], and colors.
- The `[Link]` function is used to specify colors for the word cloud.
This will generate a word cloud visualization where the size of each word represents its
frequency in the text. The size of a word in a word cloud is proportional to its frequency in
the text.
____________________________________________________________________________________
123 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Reinforcement Learning
Value function, Bellman's equation, Application of neural networks in current industry.
Reinforcement Learning (RL): Interacting with an environment, an agent learns to make
decisions using machine learning. The agent learns through trial and error, receiving feedback
in the form of rewards or penalties, and adjusts its actions to maximize long-term benefits.
Reinforcement Learning implemented in python using the OpenAI Gym environment:
Here is an example for RL:
import numpy as np
import gym
# Create the environment
env = [Link]('Taxi-v3')
# Initialize Q-table with zeros
Q = [Link]([env.observation_space.n, env.action_space.n])
# Set hyperparameters
alpha = 0.1 # learning rate
gamma = 0.6 # discount factor
epsilon = 0.1 # exploration-exploitation trade-off
# Number of episodes
num_episodes = 10000
# Q-learning algorithm
for episode in range(num_episodes):
state = [Link]()
done = False
while not done:
# Choose action using epsilon-greedy policy
if [Link](0, 1) < epsilon:
____________________________________________________________________________________
124 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
In this example,
- Import the necessary libraries, including OpenAI Gym, which provides RL environments.
- Create an instance of the Taxi-v3 environment from OpenAI Gym.
- Initialize a Q-table with zeros. Each row corresponds to a state and each column
corresponds to an action.
____________________________________________________________________________________
125 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
- Define hyperparameters such as learning rate (alpha), discount factor (gamma), and
exploration-exploitation trade-off (epsilon).
The Q-learning algorithm for a fixed number of episodes, during which the agent explores the
environment, updates the Q-table based on received rewards, and gradually learns an optimal
policy.
- To evaluate the trained agent's performance by running it for a fixed number of episodes
and calculating the average reward obtained.
____________________________________________________________________________________
126 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
127 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
}
}
# Print Q-table
print("Q-table:")
print(Q)
# Choose optimal policy
optimal_policy <- apply(Q, 1, function(row) names([Link](row)))
print("Optimal policy:")
print(optimal_policy)
In this example,
- To use the `RLearn` package to create a simple grid world environment.
- Initialize a Q-table with zeros. Each row represents a state, and each column represents an
action.
- Define hyperparameters such as learning rate (alpha), discount factor (gamma), and
exploration-exploitation trade-off (epsilon).
- To run the Q-learning algorithm for a fixed number of episodes, during which the agent
explores the environment, updates the Q-table based on received rewards, and gradually
learns an optimal policy.
- Finally, print the learned Q-table and the optimal policy chosen by the agent.
Value Function
In reinforcement learning, a value function estimates the expected return (total future
rewards) that an agent can receive from a particular state or state-action pair. There are two
types of value functions: state value function (V(s)) and action value function (Q(s, a)).
Here is an example of implementing a state value function in Python using the Gridworld
environment:
import numpy as np
# Define the Gridworld environment
class Gridworld:
def __init__(self, size):
[Link] = size
____________________________________________________________________________________
128 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
129 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
max_value = -[Link]
for action in env.get_actions():
next_state = [Link](state, action)
x, y = next_state
reward = 0 if env.is_terminal_state(next_state) else -1
value = reward + gamma * V[x, y]
max_value = max(max_value, value)
V[i, j] = max_value
delta = max(delta, abs(v - V[i, j]))
if delta < theta:
break
return V
# Create the Gridworld environment
env = Gridworld(size=5)
# Calculate the state value function using value iteration
V = value_iteration(env)
# Print the state value function
print("State Value Function:")
print(V)
In this example,
- Define a simple Gridworld environment where the agent can move in four directions: up,
down, left, and right.
- To implement the value iteration algorithm to calculate the state value function (V(s)) for
each state in the Gridworld.
- The state value function represents the expected return (total future rewards) that an agent
can receive from each state.
- To print the calculated state value function for the Gridworld environment.
____________________________________________________________________________________
130 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
____________________________________________________________________________________
132 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
}
}
return (V)
}
# Create the Gridworld environment
env <- Gridworld(size = 5)
# Calculate the state value function using value iteration
V <- value_iteration(env)
# Print the state value function
print("State Value Function:")
print(V)
In this example,
- To define a simple Gridworld environment where the agent can move in four directions: up,
down, left, and right.
- To implement the value iteration algorithm to calculate the state value function (V(s)) for
each state in the Gridworld.
- The state value function represents the expected return (total future rewards) that an agent
can receive from each state.
- To print the calculated state value function for the Gridworld environment, to implement
and calculate the state value function in Python for a simple reinforcement learning problem.
Bellman's Equation
Bellman's equation is a fundamental concept in dynamic programming and reinforcement
learning. It expresses the relationship between the value of a state or state-action pair and the
value of its successor states or state-action pairs. Bellman's equation has two forms: the
Bellman Expectation Equation and the Bellman Optimality Equation.
The Bellman Expectation Equation for the state value function (V(s)) is given by:
\[ V(s) = \sum_{a} \pi(a|s) \sum_{s'} P(s'|s, a) [R(s,a,s') + \gamma V(s')] \]
Where:
- \( V(s) \) is the value of state \( s \).
- \( \pi(a|s) \) is the policy, representing the probability of taking action \( a \) in state \( s \).
____________________________________________________________________________________
133 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Here is an example of implementing the Bellman Expectation Equation for the state value
function in python:
#python
import numpy as np
# Define transition probabilities
P = [Link]([
[[0.8, 0.2], [0.1, 0.9]], # Transition probabilities for action 0 (left)
[[0.7, 0.3], [0.2, 0.8]] # Transition probabilities for action 1 (right)
])# Define rewards
R = [Link]([
[[1, 0], [-1, 0]], # Rewards for action 0 (left)
[[0, -1], [0, 1]] # Rewards for action 1 (right)])
# Define policy (uniform random policy)
pi = [Link]([[0.5, 0.5], [0.5, 0.5]])
# Define discount factor
gamma = 0.9
# Initialize state value function
V = [Link](2)
# Bellman Expectation Equation
for s in range(2):
V_s = 0
for a in range(2):
for s_prime in range(2):
V_s += pi[s, a] * P[a, s, s_prime] * (R[a, s, s_prime] + gamma * V[s_prime])
V[s] = V_s
____________________________________________________________________________________
134 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
Here is an example,
- To define transition probabilities (\( P \)) and rewards (\( R \)) for a simple Markov Decision
Process (MDP) with two states and two actions.
- To define a uniform random policy (\( \pi \)).
- To define a discount factor (\( \gamma \)).
- To initialize the state value function (\( V \)).
- To iterate over each state and apply the Bellman Expectation Equation to update the value
of each state based on the expected future rewards to implement the Bellman Expectation
Equation for the state value function in python.
In R, Bellman's equation can be implemented for various reinforcement learning tasks, such
as solving Markov decision processes (MDPs) or training agents in environments using
algorithms like Q-learning or value iteration.
Here is a conceptual example of implementing Bellman's equation for Q-learning in R:
In this example,
- To define a Q-learning function `q_learning` that implements the Q-learning algorithm
using Bellman's equation. Inside the function, iterate over episodes, take actions, observe
rewards, and update Q-values based on Bellman's equation.
- To define an example environment (e.g., grid world) with states, actions, a transition
function, a termination condition, and a reward function.
- To set hyperparameters such as the number of episodes, learning rate, discount factor, and
exploration rate (epsilon). Run the Q-learning algorithm on the defined environment to learn
the optimal Q-values.
Bellman's equation can be used in R to implement reinforcement learning algorithms like Q-
learning to solve optimization problems in dynamic environments. Neural networks have
found widespread application across various industries due to their ability to learn complex
patterns and relationships from data.
____________________________________________________________________________________
137 | Machine Learning Methods Using Python and R- II | FG
----------------------------------------------------------- TISS SSE ----------------------------------------------------------
References
1. Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Cambridge: Springer.
Retrieved from [Link]
2. Geron, A. (2019). Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFLow.
United State of America: O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
3. Grolemund, H. W. (2017). R for Data Science. United State of America: O'Reilly,
Sebastopol, cop.
4. Guido, A. C. (2016). Introduction to Machine Learning with Python: A Guide for Data
Scientists. United State of America: Sebastopol, CA: O'Reilly Media, Inc.
5. Ian H. Witten, E. F. (2011). Data Mining: Practical Machine Learning Tools and Techniques.
Burlington, Massachusetts: Morgan Kaufmann. doi:[Link]
19715-5
6. Murphy, K. P. (2012). Machine Learning: A Probabilistic Perspective. Massachusetts
London: The MIT Press Cambridge, England. Retrieved from
[Link]
5nh9osgl8qq0
7. Raschka, S. (2017). Python Machine Learning. Birmingham- Mumbai: Packt Publishing.
____________________________________________________________________________________
138 | Machine Learning Methods Using Python and R- II | FG