DEV Community

Cover image for Gemika’s Enchanted Guide to Iris Dataset with Magic and Machine Learning 🌟🧙‍♂️ (Part #7)
gerry leo nugroho
gerry leo nugroho

Posted on

Gemika’s Enchanted Guide to Iris Dataset with Magic and Machine Learning 🌟🧙‍♂️ (Part #7)

Welcome back, my dazzling young spellcasters! I’m Professor Gerry Leo Nugroho, your guide through the wondrous corridors of data magic at Hogwarts, and a dear friend of Albus Dumbledore. Last time, we wielded the Elder Wand to split our Iris Dataset into training and testing realms—like dividing champions for the Triwizard Tournament! 🌸

Now, my little Gryffindor charmer, Gemika Haziq Nugroho, and I are skipping off to Professor Flitwick’s Charms Class. It’s time to wave our wands and cast a spell that finds friends among flowers—ready your incantations! 📚✨


Chapter 7: Charms Class - Casting the K-Nearest Neighbors Spell 🪄✨

Picture this: we’re perched on stools in the airy Charms classroom, sunlight streaming through stained-glass windows, and Professor Flitwick squeaks, “Today, Nugroho, we’ll charm these Irises with K-Nearest Neighbors—or KNN for short!” 🌺

This spell is like a magical compass—it looks at an Iris flower’s traits (petal length, sepal width) and asks, “Who’s your closest neighbor?” Then, it guesses the flower’s type—Setosa, Versicolor, or Virginica—based on its five nearest pals! It’s as if the flowers are holding hands in a circle, singing, “You’re one of us!” Flitwick’s wand twirls—this charm’s pure delight! 🎶🪄


7.1 The Code & Algorithm: Waving the KNN Wand

Let’s open our spellbook (or Jupyter Lab) and cast the KNeighborsClassifier spell from sklearn. It’s a charm so simple, even Neville could master it—yet powerful enough to stun a troll! Here’s the magic, with a grin for my curious Gemika:

# Summoning our charm tools
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

# Loading and splitting our Iris scroll
iris = load_iris()
iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
X = iris_df.drop('species', axis=1)  # Flower traits
y = iris_df['species']               # Flower names
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Spell: Casting KNN—like a friendly wave!
knn = KNeighborsClassifier(n_neighbors=5)  # 5 neighbors, our magic number
knn.fit(X_train, y_train)                 # Teaching the spell with training data

# Testing the charm’s power
y_pred = knn.predict(X_test)              # Guessing the test flowers!
print("First few guesses:", y_pred[:5])
print("Real answers:", y_test[:5].values)
Enter fullscreen mode Exit fullscreen mode

7.2 What’s Twirling in the Spell?

  • KNeighborsClassifier(n_neighbors=5): Sets up our charm—five neighbors vote on each flower’s type, like a mini Hogwarts jury!
  • .fit(X_train, y_train): Teaches the spell using our training realm—like practicing Wingardium Leviosa on feathers!
  • .predict(X_test): Casts the charm on test flowers—guessing their species faster than a Snitch flies!

Run this, and you might see:

First few guesses: ['versicolor' 'setosa' 'virginica' 'versicolor' 'versicolor']
Real answers: ['versicolor' 'setosa' 'virginica' 'versicolor' 'versicolor']
Enter fullscreen mode Exit fullscreen mode

Look at that—our charm’s spot on! Flitwick would give us an “Outstanding” for sure! 🌟🎉


7.3 Hogwarts Application: Finding Your Closest Pals

Imagine Professor Flitwick chirping, “Let’s find your Hogwarts friends with KNN!” We’d measure traits—wand length, spell speed, chocolate frog card collection—and the spell would point to your nearest neighbors. Are you closest to Harry’s bravery, Hermione’s smarts, or Ron’s loyalty? Just like guessing Iris species, KNN would match you with your crew—perfect for plotting pranks or studying for OWLs! 🧙‍♂️👭✨


7.4 Gemika’s Quiz Time! 🧑‍🚀

My little Gemika, waving his stick like a tiny Flitwick, pipes up, “Abi, how does this spell guess the Iris flower’s house?” I beam—he’s got charm in spades! Pick your answer, young enchanters:

  • A) It asks the Sorting Hat to whisper the answer.
  • B) It checks the five closest flowers and takes a vote—like a friend poll!
  • C) It waves a wand and hopes for the best.

Scribble your guess or shout it louder than a Cheering Charm—Gemika’s giggling for your reply! 🗣️📝✨ (Hint: Think neighbors, not luck!)


7.5 Next Chapter: The Tree of Wisdom

Hold your Hippogriffs, because next we’re planting a Decision Tree—a magical map of choices! We’ll guide our Irises through a forest of decisions, like sorting students into Houses. It’ll be so grand, even Luna Lovegood might wander in! Get ready for more magic and a twist of wonder! 🌳🪄✨


Top comments (0)