Prediction of Flower Species (Iris)

Natali

2025-08-04

Introduction

This Shiny application predicts the species of a flower based on the famous iris dataset using a k-Nearest Neighbors (kNN) classification model. The input features are:

Sepal Length and Width

Petal Length and Width

# Your actual R code starts here
library(shiny)


# UI Definition
ui <- fluidPage(
  titlePanel("Prediction of Flower Species (Iris)"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("sepalLength", "Sepal Length:", min = 4, max = 8, value = 5.8),
      sliderInput("sepalWidth", "Sepal Width:", min = 2, max = 4.5, value = 3),
      sliderInput("petalLength", "Petal Length:", min = 1, max = 7, value = 4),
      sliderInput("petalWidth", "Petal Width:", min = 0.1, max = 2.5, value = 1.2),
      actionButton("predict", "Predict Species")
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Result", textOutput("prediction")),
        tabPanel("Help",
                 h3("How to Use This App"),
                 p("1. Adjust the floral feature values using the sliders."),
                 p("2. Click on 'Predict Species'."),
                 p("3. View the prediction in the 'Result' tab."),
                 p("The model uses kNN trained on the iris dataset.")
        )
      )
    )
  )
)

# Server Logic
server <- function(input, output) {
  model <- reactive({
    data <- iris[, 1:4]
    labels <- iris[, 5]
    list(data = data, labels = labels)
  })

  prediction <- eventReactive(input$predict, {
    inputValues <- data.frame(
      Sepal.Length = input$sepalLength,
      Sepal.Width = input$sepalWidth,
      Petal.Length = input$petalLength,
      Petal.Width = input$petalWidth
    )
    pred <- knn(train = model()$data, test = inputValues, cl = model()$labels, k = 3)
    paste("The predicted species is:", pred)
  })

  output$prediction <- renderText({ prediction() })
}

# Launch App
shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents
## Iris Dataset Summary
library(datasets)
summary(iris)
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## 

Conclusion

This interactive app demonstrates how simple machine learning can be used for classification problems in R. By combining Shiny’s UI features with kNN, it provides an educational and intuitive tool for exploring pattern recognition in floral data.