R Data Analysis Example: Learn classification and visualization with the Iris Iris dataset

When you start analyzing data, one of the first datasets you're likely to encounter is the iris Iris datasetThis dataset is a classic R data analysis example that is often used to learn the basics of data analysis. It addresses the problem of classifying which variety each sample belongs to, based on several characteristics of iris flowers (length and width of petals and sepals).

(R 데이터분석 예제 - 붓꽃 Iris 데이터셋
( R Data Analysis Example - Iris dataset )

In this post, you'll learn how to explore and visualize data using the Iris dataset as an R data analysis example, and create a simple classification model. Read on to learn important information about classification and visualization!

Iris dataset overview

Iris datasetcontains information about the morphology of irises and is useful for solving the problem of predicting iris varieties from the data. The dataset consists of 150 samples, each with four characteristics (sepal length, sepal width, petal length, and petal width). The Data analysis exampleswe'll see how to classify three iris varieties (Setosa, Versicolor, and Virginica) based on these characteristics.

Loading and exploring data

Let's start by using R to load our Iris data, and do a little exploring. R has a iris The dataset is built-in, so no installation is required.

Loading data from R

Import the # Iris Dataset
data(iris)

Check the # data structure
str(iris)
summary(iris)
head(iris)
R 데이터분석 예제 - iris 데이터 탐색1

iris The dataset is organized into five columns, each containing the following variables

  • Sepal.Length: calyx length
  • Sepal.Width: calyx-width
  • Petal.Length: petal length
  • Petal.Width: petal-width
  • Species: varieties of irises (Setosa, Versicolor, Virginica)

Data structure descriptions

Through the above code iris You can see the structure of your data and explore summary statistics. For each attribute, you can see basic statistics like mean, median, minimum, and maximum to help you understand the overall distribution of your data.

R data analysis example data visualization

Once you've explored your data, it's important to visualize it to visually understand the relationship between each attribute. R's ggplot2 package makes it simple to perform visualizations. In this Data analysis examplesshows the length and width of the petals and sepals as a scatter plot.

Drawing scatter plots in R

Install and load # ggplot2
# install.packages("ggplot2") #ggplot2 If the package is not installed, install it.
library(ggplot2)

# Visualize the length and width of petals and sepals
ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point(size = 3) +
  labs(title = "Distribution of varieties by petal length and width", x = "Petal Length", y = "Petal Width")

When you run this code, you'll see a scatter plot that visualizes the distribution of iris varieties based on petal length and width. We've colored the varieties differently, so you can see at a glance how the data is visually distributed.

In this visualization, you can see that Setosa is clearly separated from the other two varieties, while Versicolor and Virginica have some overlap.

Build a K-Nearest Neighbor (K-NN) classification model

Now you can create a simple Classification modelsThis time, we'll use the K-Nearest Neighbor (K-NN) algorithm to predict the variety of irises. K-NN is a simple and intuitive algorithm that, given a new data point, classifies it by referring to the data of its K closest neighbors.

Building K-NN models in R

Install and load the # prerequisite packages
install.packages("class")
library(class)

Split the # dataset into training and test sets
set.seed(123)
index <- sample(1:nrow(iris), 0.7 * nrow(iris))
train_data <- iris[index, ]
test_data <- iris[-index, ]

Train and predict the # K-NN model
train_labels <- train_data$Species
test_labels <- test_data$Species
knn_pred <- knn(train = train_data[, -5], test = test_data[, -5], cl = train_labels, k = 3)

Check the # prediction results
table(knn_pred, test_labels)

# execution result data #
            test_labels
knn_pred setosa versicolor virginica
  setosa 14 0 0
  versicolor 0 17 0
  virginica 0 1 13

The above code would be called K-NN algorithmto predict the iris varieties in the Iris dataset. After splitting the training and test data, it predicts the varieties on the test data and compares the results to the actual values.

Evaluate prediction results

One way to evaluate prediction results is to use the Confusion matrixThe confusion matrix allows you to see at a glance how accurately the model predicted and how many samples were misclassified. In the code above table() function to compare predicted and actual values can output a confusion matrix, but it's hard to analyze its meaning right away.

So when evaluating performance on a K-NN classification model, we typically use the Precision, Recall, F1 Score and more to specifically analyze the performance of your model.

caret package or e1071 package makes it easy to calculate precision, recall, and F1 scores. Here, we'll use the caret package to get it, and we'll explain how to use it.

1. install and load the caret package

First, create a caret Let's install and load the package.

Installing # on-demand packages
# install.packages("caret")

library(caret)

2. Generate confusion matrices and evaluate performance

table() function to evaluate performance using a confusion matrix of your own creation, caret package's confusionMatrix() Functions allow you to automatically calculate precision, recall, F1 score, and more.

Generate a # confusion matrix and evaluate its performance
confusion_matrix <- confusionMatrix(knn_pred, test_labels)

Print the # results
print(confusion_matrix)

When you run this code, you'll see that for each class, the Precision, Reproducibility, F1 Scoreas well as Accuracyto the end of the document.

3. Interpret the results

confusionMatrix() function returns a result containing various performance metrics. We'll describe the main metrics here:

  • PrecisionThe percentage of data that actually belongs to a particular class out of the values predicted for that class.
  • RecallThe percentage of data that actually belongs to that class that you predicted correctly.
  • F1 ScoreThe harmonic mean of precision and recall, which allows for a balanced evaluation of both values.
  • Accuracy: The percentage of the total data that was correctly predicted.

4. example results

confusionMatrix() function will output something like this.

Confusion Matrix and Statistics

            Reference
Prediction setosa versicolor virginica
  setosa 14 0 0
  versicolor 0 17 0
  virginica 0 1 13

Overall Statistics

               Accuracy : 0.9778
                 95% ci : (0.8887, 0.9994)
    No Information Rate : 0.3556
    P-Value [Acc > NIR] : < 2e-16

                  Kappa : 0.9662

Mcnemar's Test P-Value : NA

Statistics by Class:

                     Class: setosa Class: versicolor Class: virginica
Sensitivity 1.0000 0.9444 1.0000
Specificity 1.0000 1.0000 0.9722
Pos Pred Value 1.0000 1.0000 0.9286
Neg Pred Value 1.0000 0.9667 1.0000
Prevalence 0.2889 0.3556 0.3556
Detection Rate 0.2889 0.3333 0.3556
Detection Prevalence 0.2889 0.3333 0.3833
Balanced Accuracy 1.0000 0.9722 0.9861
Interpretation of each key metric:
  • SensitivityRecall. Indicates how well the predicted value matches the actual value.
  • Specificity: A metric for how well it predicted non-specific classes of data.
  • Pos Pred ValuePrecision, which is the percentage of predictions that are correct.
  • Neg Pred Valueis the percentage of predictions that were correct.
  • Accuracy: The percentage of the total forecast that was correct.

In this way, you can more specifically evaluate and analyze the performance of your model.

Common mistakes in data analysis and how to fix them

This time Data analysis exampleshere are some tips to avoid common beginner mistakes.

  1. Neglecting to preprocess data: Before you analyze your data, you must deal with missing values, outliers, etc. While Iris data is free of missing values, other datasets must take care of preprocessing.
  2. Select the appropriate K value: In a K-NN model, the k It is important to choose a value that is appropriate. A K value that is too small can result in overfitting, while a K value that is too large can miss important patterns.
  3. Not paying attention to data partitioning: When dividing training and test data, be sure to sample the data randomly, otherwise the model may be biased toward certain data.

FAQs

Q1: Where can I download the Iris dataset?
A: Iris datasets are built into R by default and do not require a separate download. data(iris) command to load them.

Q2: How do I set the K value in a K-NN model?
A: The K value is typically set to an odd number, and we recommend using cross-validation to find the optimal K value. Depending on the size and distribution of your dataset, your K value may vary.

Q3: Can I try other classification algorithms?
A: Absolutely! In addition to K-NN, you'll get hands-on experience with a variety of other classification algorithms, including logistic regression, decision trees, random forests, and more.

Organize

In this post, we'll use the Data analysis examplesto do some basic exploratory data analysis and visualization with the Iris dataset, and then build a classification model using the K-Nearest Neighbor (K-NN) algorithm. While the Iris dataset is small and simple, it is a very useful resource for learning and analyzing classification problems. We hope that this example has helped you understand the basic concepts of data analysis and has given you a springboard to more complex problems.

You can build on this example to create a Other datasetsfor the challenge!

Similar Posts