Lessons › Projects
Your first ML model: an iris flower classifier
A model that looks at four measurements of a flower and names its species, then tells you how sure it is.
No setup needed. Run every step in your browser on Gradient Lab, or download it.
Open the notebookLevel: Beginner · Time: 20 min · You’ll practise: train/test split, k-nearest neighbors, accuracy, probabilities
Steps
1. Load the data
Load scikit-learn’s built-in iris dataset: 150 flowers, each described by 4 numbers (the features), plus its species (the label).
iris = load_iris()
X, y = iris.data, iris.target
print("Features:", iris.feature_names)
print("Species :", ", ".join(iris.target_names))
print("Data shape:", X.shape)2. Hold back 20% as a test set the model never sees while learning
Lock 20% of the flowers away as a test set. stratify=y keeps the same mix of species in both parts.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
print(f"Training on {len(X_train)} flowers, testing on {len(X_test)}")3. Train a k-nearest-neighbors model
Create a k-nearest-neighbors model and call fit. That’s the whole training step: k-NN just remembers the examples.
model = KNeighborsClassifier(n_neighbors=5) model.fit(X_train, y_train)
4. Check it on the unseen test flowers
Predict the test flowers and compare with the real answers. This is your honest score on data the model never saw.
predictions = model.predict(X_test)
print(f"Test accuracy: {accuracy_score(y_test, predictions):.0%}")5. Predict a brand-new flower
Give it a flower it has never seen and ask for a prediction and the probability of each species.
new_flower = [[5.8, 2.7, 5.1, 1.9]] # sepal length, sepal width, petal length, petal width (cm)
guess = model.predict(new_flower)[0]
chances = model.predict_proba(new_flower)[0]
print("New flower looks like:", iris.target_names[guess])
for name, p in zip(iris.target_names, chances):
print(f" {name:<11} {p:.0%}")6. How does k change accuracy?
Experiment: try different values of k. Very small k is jumpy; very large k blurs the groups together.
for k in [1, 3, 5, 15, 45]:
acc = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train).score(X_test, y_test)
print(f"k = {k:>2}: accuracy {acc:.0%}")Expected output
$ python iris_classifier.py Features: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'] Species : setosa, versicolor, virginica Data shape: (150, 4) Training on 120 flowers, testing on 30 Test accuracy: 100% New flower looks like: virginica setosa 0% versicolor 0% virginica 100% k = 1: accuracy 97% k = 3: accuracy 100% k = 5: accuracy 100% k = 15: accuracy 97% k = 45: accuracy 90%
Stretch goals
- Swap k-NN for
LogisticRegressionorDecisionTreeClassifierand compare accuracy. - Use only two features and plot the flowers with matplotlib, colored by species.
- Change
random_statein the split a few times. How much does the accuracy move?