lOMoARcPSD|45622269
UNIT – I
Introduction:
Machine Learning provides a set of tools that uses computer to transform data into
actionable knowledge.
Machine learning (ML) is a branch of artificial intelligence (AI) and computer science
that focuses on the using data and algorithms to enable AI to imitate the way that humans learn,
gradually improving its accuracy.
A computer program which learns from experience is called a machine learning program
or simply a learning program. Such a program is sometimes also referred to as a learner.
Machine learning is a branch of artificial intelligence that enables algorithms to uncover
hidden patterns within datasets, allowing them to make predictions on new, similar data without
explicit programming for each task.
Need for machine learning
Machine learning is important because it allows computers to learn from data and
improve their performance on specific tasks without being explicitly programmed. This ability
to learn from data and adapt to new situations makes machine learning particularly useful for
tasks that involve large amounts of data, complex decision-making, and dynamic
environments.
Here are some specific areas where machine learning is being used:
Predictive modeling: Machine learning can be used to build predictive models that can
help businesses make better decisions. For example, machine learning can be used to predict
which customers are most likely to buy a particular product, or which patients are most
likely to develop a certain disease.
Natural language processing: Machine learning is used to build systems that can
understand and interpret human language. This is important for applications such as voice
recognition, chatbots, and language translation.
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Computer vision: Machine learning is used to build systems that can recognize and
interpret images and videos. This is important for applications such as self-driving cars,
surveillance systems, and medical imaging.
Fraud detection: Machine learning can be used to detect fraudulent behavior in financial
transactions, online advertising, and other areas.
Recommendation systems: Machine learning can be used to build recommendation
systems that suggest products, services, or content to users based on their past behavior and
preferences.
Components of Learning
Basic components of learning process The learning process, whether by a human or a
machine, can be divided into four components, namely, data storage, abstraction, generalization
and evaluation. Figure 1.1 illustrates the various components and the steps involved in the
learning process.
Data input:
It utilizes observation, memory storage, and recall to provide a factual basis for further
reasoning.
Facilities for storing and retrieving huge amounts of data are an important component of
the learning process. Humans and computers alike utilize data storage as a foundation for
advanced reasoning.
In a human being, the data is stored in the brain and data is retrieved using electro
chemical signals.
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Computers use hard disk drives, flash memory, random access memory and similar
devices to store data and use cables and other technology to retrieve data .
Abstraction:
It involves the translation of data into broader representations.
Abstraction is the process of extracting knowledge about stored data. This involves
creating general concepts about the data as a whole. The creation of knowledge involves
application of known models and creation of new models.
The process of fitting a model to a dataset is known as training. When the model has
been trained, the data is transformed into an abstract form that summarizes the original
information.
Generalization:
It uses abstracted data to form a basis for action.
The term generalization describes the process of turning the knowledge about stored data
into a form that can be utilized for future action. These actions are to be carried out on
tasks that are similar, but not identical, to those what have been seen before. In
generalization, the goal is to discover those properties of the data that will be most
relevant to future tasks.
Evaluation:
It is the process of giving feedback to the user to measure the utility of the learned
knowledge. This feedback is then utilised to effect improvements in the whole learning
process
Machine learning: Key Concepts
1. Data: The foundation of machine learning. It can be structured (e.g., tables or databases)
or unstructured (e.g., images, text, or video). The data serves as input for training a
machine learning model.
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
2. Algorithms: Machine learning algorithms are used to find patterns in the data and make
predictions. Common types include decision trees, support vector machines, neural
networks, and more.
3. Model: A model is the mathematical representation of a machine learning algorithm that
has been trained on data. It is used to make predictions or classifications.
4. Training: This is the process where a machine learning model learns from data. During
training, the model adjusts its parameters to minimize the error or make more accurate
predictions.
5. Features: Features are individual measurable properties or characteristics of the data. For
example, in a dataset of houses, features might include square footage, number of
bedrooms, and price.
6. Labels: These are the outcomes or categories we want the machine learning model to
predict. For instance, in a dataset for predicting house prices, the price itself is the label.
7. Prediction: Once the model is trained, it can be used to predict labels for new, unseen
data. This could mean classifying an image, predicting a stock price, or determining
whether a tumor is malignant.
Steps to apply machine learning
1. Collect and Prepare the Data
Data Collection: Gather relevant data from available sources such as databases, web
scraping, APIs, or public datasets.
Data Types: Your data could include numerical, categorical, or text features. Make sure
to collect data that is representative of the problem you're solving.
Example: In customer churn prediction, data may include customer demographics,
purchase history, and interaction data.
2. Explore and Preprocess the Data
Data Exploration (EDA): Use exploratory data analysis to understand the structure,
patterns, and relationships in the data. You can visualize it using tools like histograms,
scatter plots, and correlation matrices.
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Cleaning:
o Handle missing values: Drop, impute, or flag missing data.
o Remove or correct outliers that may distort the model.
o Convert categorical variables into numerical representations using techniques
like one-hot encoding or label encoding.
Feature Engineering:
o Create new features from existing ones if needed (e.g., calculating customer
lifetime value).
o Normalize or scale the data, especially for algorithms sensitive to scale (like SVM
or K-means).
b. Split the Data
Training and Testing Data: Split your dataset into two parts: training data and testing
data (e.g., 80% training, 20% testing). This helps prevent overfitting, allowing you to
evaluate the model’s performance on unseen data.
Validation Set (optional): For more complex models, you might need an additional
validation set or use cross-validation.
3. Select a Machine Learning Model
Choose a machine learning algorithm based on the nature of your problem:
o Supervised Learning: Algorithms like linear regression, decision trees, random
forests, or neural networks.
o Unsupervised Learning: Algorithms like K-means clustering or principal
component analysis (PCA).
o Reinforcement Learning: For problems requiring sequential decision-making,
such as robotics or game AI.
Example: For predicting customer churn, you might start with a logistic regression or
decision tree model.
4. Train the Model
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Training: Feed the training data into the selected model to learn the relationships
between the input features and the target variable (label).
Hyperparameter Tuning: Optimize the hyperparameters of the model using techniques
like grid search or random search to improve performance.
5. Evaluate the Model
Performance Metrics: Use metrics to evaluate how well the model performs on the test
data.
o For regression problems, use metrics like Mean Squared Error (MSE) or R-
squared.
o For classification problems, use metrics like accuracy, precision, recall, F1-
score, or the Area Under the ROC Curve (AUC).
Confusion Matrix: In classification, a confusion matrix helps analyze where the model
is making correct or incorrect predictions.
Example: If you're predicting churn, you might look at the precision and recall of the
model to understand how well it's identifying customers likely to churn.
6. Improving model performance / Optimize the Model
Improve Accuracy: If your model’s performance is not satisfactory, consider the
following:
o Try different algorithms (e.g., random forest instead of decision trees).
o Use more sophisticated techniques such as ensemble methods (e.g., boosting or
bagging).
o Feature selection or dimensionality reduction techniques like Principal
Component Analysis (PCA).
Cross-validation: Use k-fold cross-validation to better evaluate the model’s performance
and reduce overfitting.
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Types of Machine Learning
1. Supervised Learning: In supervised learning, the model is trained on labeled data,
meaning both the inputs and corresponding outputs are provided. The goal is to learn a
mapping from inputs to outputs.
Example: Predicting house prices based on historical data.
A training set of examples with the correct responses (targets) is provided and,
based on this training set, the algorithm generalises to respond correctly to all possible
inputs. This is also called learning from exemplars. Supervised learning is the machine
learning task of learning a function that maps an input to an output based on example
input-output pairs.
In supervised learning, each example in the training set is a pair consisting of an
input object (typically a vector) and an output value. A supervised learning algorithm
analyzes the training data and produces a function, which can be used for mapping new
examples. In the optimal case, the function will correctly determine the class labels for
unseen instances. Both classification and regression 13 problems are supervised learning
problems. A wide range of supervised learning algorithms are available, each with its
strengths and weaknesses. There is no single learning algorithm that works best on all
supervised learning problems.
Remarks:
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
A “supervised learning” is so called because the process of an algorithm learning
from the training dataset can be thought of as a teacher supervising the learning process.
We know the correct answers (that is, the correct outputs), the algorithm iteratively
makes predictions on the training data and is corrected by the teacher. Learning stops
when the algorithm achieves an acceptable level of performance.
Example Consider the following data regarding patients entering a clinic. The data
consists of the gender and age of the patients and each patient is labeled as “healthy” or “sick”.
2. Unsupervised Learning: In unsupervised learning, the model is trained on data that
doesn't have labeled outcomes. The goal is to find patterns or groupings within the data.
Example: Clustering customers based on their purchasing behavior.
Correct responses are not provided, but instead the algorithm tries to identify
similarities between the inputs so that inputs that have something in common are
categorised together. The statistical approach to unsupervised learning is known as
density estimation.
Unsupervised learning is a type of machine learning algorithm used to draw
inferences from datasets consisting of input data without labeled responses. In
unsupervised learning algorithms, a classification or categorization is not included in the
observations. There are no output values and so there is no estimation of functions. Since
the examples given to the learner are unlabeled, the accuracy of the structure that is
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
output by the algorithm cannot be evaluated. The most common unsupervised learning
method is cluster analysis, which is used for exploratory data analysis to find hidden
patterns 14 or grouping in data.
Example
Consider the following data regarding patients entering a clinic. The data consists
of the gender and age of the patients.
Based on this data, can we infer anything regarding the patients entering the clinic?
3. Reinforcement Learning: In reinforcement learning, the model learns by interacting
with an environment. It receives rewards or penalties based on its actions, and the goal is
to maximize the cumulative reward over time.
Example: Training a robot to navigate a maze.
This is somewhere between supervised and unsupervised learning. The algorithm
gets told when the answer is wrong, but does not get told how to correct it. It has to
explore and try out different possibilities until it works out how to get the answer right.
Reinforcement learning is sometime called learning with a critic because of this monitor
that scores the answer, but does not suggest improvements.
Reinforcement learning is the problem of getting an agent to act in the world so
as to maximize its rewards. A learner (the program) is not told what actions to take as in
most forms of machine learning, but instead must discover which actions yield the most
reward by trying them. In the most interesting and challenging cases, actions may affect
not only the immediate reward but also the next situations and, through that, all
subsequent rewards.
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Example
Consider teaching a dog a new trick: we cannot tell it what to do, but we can
reward/punish it if it does the right/wrong thing. It has to find out what it did that made it
get the reward/punishment. We can use a similar method to train computers to do many
tasks, such as playing backgammon or chess, scheduling jobs, and controlling robot
limbs. Reinforcement learning is different from supervised learning. Supervised learning
is learning from examples provided by a knowledgeable expert
Common Algorithms in Machine Learning
The process of choosing a machine learning algorithm involves matching the characteristics
of the data to be learned to the biases of the available approaches. Since the choice of a machine
learning algorithm is largely dependent upon the type of data you are analyzing and the proposed
task at hand, it is often helpful to be thinking about this process while you are gathering,
exploring, and cleaning your data
1. Linear Regression: Used for predicting a continuous variable, like house prices, based
on the relationship between input variables and the output.
2. Decision Trees: A tree-like model of decisions, used for both classification and
regression tasks.
3. Neural Networks: Models inspired by the structure of the human brain, particularly
effective in tasks like image recognition and natural language processing.
4. K-Means Clustering: An unsupervised algorithm that groups data into clusters based on
similarity.
5. Support Vector Machines (SVM): Used for classification tasks, finding a hyperplane
that best separates the data into categories.
Applications of Machine Learning
10
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Healthcare: ML models are used for diagnosing diseases, predicting patient outcomes,
and personalizing treatment plans.
Finance: In fraud detection, stock price forecasting, and credit scoring, machine learning
helps improve decision-making and reduce risks.
Autonomous Vehicles: Machine learning powers self-driving cars, enabling them to
recognize objects and navigate roads safely.
Natural Language Processing (NLP): Used in chatbots, language translation, and
sentiment analysis.
Recommendation Systems: Platforms like Netflix and Amazon use ML to suggest
movies, products, or music to users.
Transportation: Machine learning is used in the transportation industry to optimize
routes, reduce fuel consumption, and improve the overall efficiency of transportation
systems. It also plays a role in autonomous vehicles, where ML algorithms are used to
make decisions about navigation and safety.
Government organization: The government makes use of ML to manage public safety
and utilities. Take the example of China with its massive face recognition. The
government uses Artificial intelligence to prevent jaywalking.
Managing and Understanding Data: R Programming
Introduction:
R is a powerful and widely used programming language and environment primarily
designed for statistical computing and data analysis. It is popular among statisticians, data
analysts, researchers, and machine learning practitioners because of its ease of use and extensive
capabilities for data manipulation, visualization, and analysis.
11
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Key Features of R
1. Statistical Analysis: R offers a vast collection of libraries and tools for statistical tests,
hypothesis testing, time series analysis, linear and nonlinear modeling, etc.
2. Data Manipulation: R is well-suited for handling, cleaning, and manipulating large
datasets. Packages like dplyr and [Link] make it efficient to work with data.
3. Data Visualization: R provides advanced visualization capabilities with libraries like
ggplot2 and lattice, enabling users to create highly customizable and complex graphs
and plots.
4. Extensibility: With a large community of contributors, R has thousands of packages
(available on CRAN) for various domains, including genetics, finance, social sciences,
machine learning, and more.
5. Open Source: R is free to use and is open-source, which means its development is
community-driven, and it is constantly evolving.
6. Cross-platform: R runs on various operating systems, including Windows, macOS, and
Linux.
Why Use R?
1. Data Science and Machine Learning: R is widely used in data science because of its
extensive support for data manipulation, statistical modeling, and visualization. It is also
equipped with machine learning libraries like caret, randomForest, and xgboost.
2. Statistical Research: For academics and researchers, R is a go-to tool due to its robust
statistical analysis and reproducibility features.
3. Reproducibility: Tools like R Markdown allow for creating reports that combine code,
output, and narrative text in a single document, which ensures reproducibility in research
and reporting.
R data structures
The R data structures used most frequently in machine learning are vectors, factors, lists, arrays,
and data frames.
12
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
1. Vectors
Definition: The fundamental R data structure is the vector, which stores an ordered set of
values called elements. A vector can contain any number of elements. However, all the
elements must be of the same type; for instance, a vector cannot contain both numbers
and text.
Types:
o Integer vectors: A sequence numbers without decimals
o Numeric vector: A sequence of numbers with decimals.
o Character vector: A sequence of text strings.
o Logical vector: A sequence of boolean values (TRUE, FALSE).
o Special Values:
NULL- Indicate the absence of any value
NA - Indicates a missing value
Example:
# Numeric vector
num_vector <- c(1, 2, 3, 4, 5)
# Character vector
char_vector <- c("apple", "banana", "cherry")
# Logical vector
log_vector <- c(TRUE, FALSE, TRUE)
Accessing Elements:
You can access vector elements by using an index.
Example:
> num_vector[2] # Access the second element (returns 2)
[1] 2
13
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
A range of values can be obtained using the colon operator.
> num_vector[2:3]
[1] 23
Items can be excluded by specifying a negative item number.
> num_vector[-3]
[1] 1 2 4 5
2. Factors
A factor is a data structure used for categorical data, where the values are restricted to a
set of predefined categories or levels. It is often used in statistical modeling.
# Creating a factor
gender <- factor(c("Male", "Female", "Female", "Male"))
# Viewing the factor and its levels
print(gender)
levels(gender) # View the unique categories (Male, Female)
Ordered Factors: Factors can also be ordered, which is useful for ordinal data (e.g., low,
medium, high).
levels <- factor(c("Low", "Medium", "High"), ordered = TRUE)
3. Lists
A list is used for storing an ordered set of values.
A list is a versatile data structure that can store elements of different data types (numeric,
character, logical, etc.). Each element of a list can be a scalar, vector, matrix, or even
another list.
A Lists are often used to store various types of input and output data and sets of
configuration parameters for machine learning models
A list is created using the list() function
Example:
my_list <- list(name = "John", age = 30, scores = c(85, 90, 88), passed = TRUE)
14
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
# Accessing elements of a list
my_list$name # Access the 'name' element (returns "John")
my_list$scores[2] # Access the second score in the 'scores' vector (returns 90)
4. Data Frame
A data frame is one of the most commonly used data structures in R. It is like a matrix
but allows columns to contain different types of data (numeric, character, logical). A data frame
is similar to a table or spreadsheet.
A data frame created using the [Link]() function
Example:
> data <- [Link]( Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 35), Passed = c(TRUE, FALSE,
TRUE) )
>data
Name Age Passed
1 Alice 25 TRUE
2 Bob 30 FALSE
3 Charlie 35 TRUE
5. Matrixes and arrays
A matrix is a data structure that represents a two-dimensional table, with rows and
columns of data. R matrixes can contain any single type of data, although they are most often
used for mathematical operations and therefore typically store only numeric data.
To create a matrix, simply supply a vector of data to the matrix() function, along with a
parameter specifying the number of rows (nrow) or number of columns (ncol).
> m <- matrix(c('a', 'b', 'c', 'd'), nrow = 2)
>m
[,1] [,2]
[1,] "a" "c"
[2,] "b" "d"
Managing data with R
15
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
1. Saving and loading R data structures
The save() function writes R data structures to the location specified by the file
parameter. R data files have the file extension .RData.
Ex:
> save(x, y, z, file = "[Link]")
The load() command will recreate any data structures already saved that were to an
.RData file
> load("[Link]")
2. Importing and saving data from CSV files
A tabular (as in "table") data file is structured in matrix form, in such a way that
each line of text reflects one example, and each example has the same number of
features.
The feature values on each line are separated by a predefined symbol known as a
delimiter.
Perhaps the most common tabular text file format is the Comma-Separated Values
(CSV) file, which as the name suggests, uses the comma as a delimiter. The CSV
files can be imported to and exported from many common applications.
To load CSV file into R, the [Link]() is used
> pt_data <- [Link]("pt_data.csv", stringsAsFactors = FALSE)
stringsAsFactors = FALSE parameter to prevent R from converting all text variables to
factors.
3. Exploring the structure of data.
The str() function provides a method for displaying the structure of a data frame
# Creating a list
gfg <- list(2, 4, 5, 6, 1)
str(gfg)
$: num 2
16
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
$ : num 4
$ : num 5
$ : num 6
$ : num 1
4. Exploring numeric variables
The summary() function displays several common summary statistics.
Statistics is the science of analyzing, reviewing and conclude data.
Some basic statistical numbers include:
Mean, median and mode
Minimum and maximum value
Percentiles
Variance and Standard Devation
Covariance and Correlation
Probability distributions
Measuring the central tendency – mean and median
Measures of central tendency are a class of statistics used to identify a value that falls in
the middle of a set of data.
Mean
The average is also known as the mean, n, a measurement defined as the sum of all values
divided by the number of values.
> mean(c(36000, 44000, 56000))
[1] 45333.33
Median
The median is the middle value of a sorted dataset. If there is an odd number of values,
the median is the middle value. If there is an even number, it is the average of the two middle
values.
# Example vector
>data <- c(10, 20, 30, 40, 50)
# Calculate median
>median_value <- median(data)
>median_value
17
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
[1] 30
Measuring spread – quartiles and the five-number summary
The five-number summary is a set of five statistics that roughly depict the spread of a
dataset. All five of the statistics are included in the output of the summary() function. Written in
order, they are:
1. Minimum (Min.)
2. First quartile, or Q1 (1st Qu.)
3. Median, or Q2 (Median)
4. Third quartile, or Q3 (3rd Qu.)
5. Maximum (Max.)
In R, the range() function returns both the minimum and maximum value.
The difference between Q1 and Q3 is known as the interquartile range (IQR), and can
be calculated with the IQR() function.
The quantile() function provides a robust tool for identifying quantiles for a set of values.
By default, the quantile() function returns the five-number summary.
Example:
> data <- c(10, 20, 30, 40, 50)
> summary(data)
Min. 1st Qu. Median Mean 3rd Qu. Max.
10 20 30 30 40 50
Visualizing numeric variables – boxplots
A boxplot is a standardized way of displaying the distribution of data based on a five-
number summary: minimum, first quartile (Q1), median (Q2), third quartile (Q3), and
maximum. Boxplots are useful for detecting outliers and understanding the spread of numeric
variables.
Example:
# Sample data
>data <- c(12, 15, 14, 19, 22, 25, 21, 23, 19, 14, 18)
# Create a boxplot
18
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
boxplot(data, main = "Boxplot of Data", ylab = "Values", col = "lightblue")
Visualizing numeric variables – histograms
A histogram is another way to graphically depict the spread of a numeric variable. It is
similar to a boxplot in that it divides the variable's values into a predefined number of portions,
or bins that act as containers for values.
A boxplot requires that each of four portions of data must contain the same number of
values, and widens or narrows the bins as needed. In contrast, a histogram uses any number of
bins of identical width, but allows the bins to contain different numbers of values.
Example:
>data <- c(12, 15, 14, 19, 22, 25, 21, 23, 19, 14, 18)
# Create a basic histogram
> hist(data, main = "Histogram of Data", xlab = "Values", col = "lightblue", border = "black")
19
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Measuring spread – variance and standard deviation
Variance and Standard Deviation are two fundamental measures of spread or dispersion
in a dataset. They describe how much the data points deviate from the mean, helping to
understand the variability of the dataset.
1. Variance
Variance measures the average of the squared differences from the mean. It provides a sense of
how spread out the values in the dataset are.
Where:
n is the number of data points.
xi are the individual data points.
X is the mean of the data points.
20
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
Variance in R:
You can calculate variance in R using the var() function.
# Sample data
>data <- c(10, 12, 23, 23, 16, 23, 21, 16)
# Calculate variance
>variance_value <- var(data)
>variance_value
[1] 24.98214
2. Standard Deviation
The standard deviation is the square root of the variance and is expressed in the same units as
the data. It gives a more interpretable measure of how spread out the values are.
Formula:
Standard Deviation in R:
You can calculate the standard deviation in R using the sd() function.
# Sample data
>data <- c(10, 12, 23, 23, 16, 23, 21, 16)
# Calculate standard deviation
>sd_value <- sd(data)
> sd_value
[1] 4.998214
Measuring the central tendency – the mode
21
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
The mode is a measure of central tendency that represents the most frequently occurring
value(s) in a dataset. Unlike the mean or median, which provide the "average" or "middle"
value, the mode identifies the most common value. A dataset can have one mode (unimodal),
more than one mode (multimodal), or no mode if all values occur with the same frequency.
Example:
# Function to calculate mode
>get_mode <- function(x) {
uniq_vals <- unique(x)
uniq_vals[[Link](tabulate(match(x, uniq_vals)))]
}
# Example vector
>data <- c(10, 20, 20, 30, 40, 40, 40, 50)
# Calculate mode
>mode_value <- get_mode(data)
>mode_value
[1] 40
Visualizing relationships – scatterplot
A scatter plot is a graphical representation used to display the relationship between two
continuous variables. Each point on the plot represents an observation from the dataset, with its
position determined by the values of the two variables. Scatter plots are useful for identifying
correlations, patterns, and potential outliers in the data.
Example:
# Sample data
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 6, 8, 10)
22
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
# Create a basic scatter plot
plot(x, y, main = "Basic Scatter Plot", xlab = "X-axis", ylab = "Y-axis", pch = 16, col =
"blue")
Examining relationships – two-way cross-tabulations
Two-way cross-tabulations (or contingency tables) are used to examine the relationship
between two categorical variables. They display the frequency distribution of the variables and
help in understanding how the levels of one variable relate to the levels of another. Cross-
tabulations are useful for identifying patterns, associations, and potential interactions between
variables.
In R, you can create two-way cross-tabulations using the table() function. This function
generates a contingency table showing the counts of occurrences for each combination of levels
in the two categorical variables.
Example:
# Sample data
>gender <- factor(c("Male", "Female", "Female", "Male", "Female", "Male"))
>smoker <- factor(c("Yes", "No", "No", "Yes", "Yes", "No"))
23
Downloaded by Amsa Mariya Fatima (secretof66@[Link])
lOMoARcPSD|45622269
# Create a two-way cross-tabulation
>cross_tab <- table(gender, smoker)
>cross_tab
smoker
gender No Yes
Female 1 2
Male 2 1
24
Downloaded by Amsa Mariya Fatima (secretof66@[Link])