Skip to content

Your First AI Project in Python: From Zero to Working Model

Install scikit-learn, train three classifiers on the 150-flower Iris dataset, and find out why a perfect first score means less than it looks. Every snippet was run on scikit-learn 1.9.1.

The Shortest Path From Python to a Trained Model

You have Python installed, an hour free, and a roadmap that wants you to finish linear algebra first. This guide to Python for AI skips that step. A few dozen lines of scikit-learn are enough to train a classifier on real measurements. The harder skill is knowing how far to trust the score it prints. For more on this topic, see AI coding assistants.

The data is the Iris set: 150 flowers, 50 each of setosa, versicolor and virginica, with four measurements per flower in centimeters (sepal length, sepal width, petal length, petal width). Edgar Anderson collected the measurements and Ronald Fisher used them in a 1936 paper. scikit-learn’s copy follows that paper: the load_iris documentation says two wrong data points were fixed in version 0.20, so it matches the copy in R but not the one in the UCI repository, which differs from Fisher’s article.

You will train three algorithms, watch all three score 100% on the first run, and then find out why that number is weaker than it looks. You leave with a fairer way to score any model, not only flower classifiers.

Setting Up

Create an isolated environment so the packages cannot collide with anything else on your machine:

python -m venv ml_env

Activate it with source ml_env/bin/activate on macOS and Linux, ml_env\Scripts\activate.bat in Windows cmd.exe, or ml_env\Scripts\Activate.ps1 in PowerShell, as listed in the Python venv documentation. Then install the packages (NumPy comes along as a dependency):

pip install scikit-learn pandas

As of October 2026 the current release is scikit-learn 1.9.1. PyPI lists it as released on September 10, 2026, and it requires Python 3.11 or newer. Confirm what you installed with python -c "import sklearn; sklearn.show_versions()". All the snippets below, joined in order into one file called first_model.py, ran on Python 3.14.2 with scikit-learn 1.9.1, pandas 3.0.6 and NumPy 2.5.4, with every warning turned into an error. Nothing raised one.

Loading and Inspecting the Data

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report

iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target

print("Dataset shape:", df.shape)
print("\nSamples per species:")
print(df['species'].value_counts().sort_index())
print("\nFeature statistics (cm):")
print(df[iris.feature_names].describe().round(2).T[['mean', 'std', 'min', 'max']])

The shape is (150, 5): four measurement columns plus the species code, with exactly 50 rows each for codes 0, 1 and 2 (setosa, versicolor, virginica, in the order of iris.target_names). Equal class sizes are a luxury that real data rarely offers.

Look at the ranges. Petal length runs from 1.0 to 6.9 cm, petal width from 0.1 to 2.5 cm, sepal width only from 2.0 to 4.4 cm. Differences like these are the usual reason for scaling features, so the next step does it. Whether scaling actually helps on this dataset is a separate question, answered further down.

Split, Scale, Train

Every supervised project repeats one rhythm: split the data into training and test sets, preprocess the features, train a model, evaluate it on rows it has never seen.

# Separate features from labels
X = iris.data
y = iris.target

# 80% training, 20% testing
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
print("Test flowers per species:", np.bincount(y_test))

# Learn the mean and spread from the training rows only
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

models = {
    'K-Nearest Neighbors': KNeighborsClassifier(n_neighbors=5),
    'Logistic Regression': LogisticRegression(max_iter=200),
    'Decision Tree': DecisionTreeClassifier(random_state=42),
}

for name, model in models.items():
    model.fit(X_train, y_train)
    preds = model.predict(X_test)
    print(f"{name}: {accuracy_score(y_test, preds):.2%}")

Two details carry the weight. random_state=42 fixes the shuffle, so everyone running this code gets the same 120 training rows and 30 test rows. And the scaler learns its mean and spread with fit_transform on the training rows only, then applies them to the test rows with transform. scikit-learn’s common pitfalls guide states the rule as “never call fit on the test data”. If test rows help set the mean, information leaks from the test set into the model and the score comes out optimistic.

Run it and every model prints 100.00%. The test split holds 10 setosa, 9 versicolor and 11 virginica flowers, and all 30 predictions are right for all three models.

Three perfect scores call for suspicion before celebration. With 30 test flowers, one mistake costs 3.3 percentage points, so the score can only move in steps of 3.3. Whether you see 100% or 93.3% depends on which 30 flowers the seed happened to pick.

Why the 100% Is Fragile, and a Fairer Score

Try this yourself: run the same split, scale and score routine for 100 different seeds and look at the distribution instead of a single number.

scores = {name: [] for name in models}
for seed in range(100):
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=seed)
    sc = StandardScaler().fit(X_tr)
    for name, model in models.items():
        model.fit(sc.transform(X_tr), y_tr)
        scores[name].append(model.score(sc.transform(X_te), y_te))

for name, s in scores.items():
    s = np.array(s)
    print(f"{name}: mean {s.mean():.1%}, worst {s.min():.1%}, "
          f"perfect in {(s == 1).sum()} of {len(s)} splits")

On scikit-learn 1.9.1 this prints:

K-Nearest Neighbors: mean 94.8%, worst 83.3%, perfect in 17 of 100 splits
Logistic Regression: mean 95.3%, worst 86.7%, perfect in 20 of 100 splits
Decision Tree: mean 94.5%, worst 83.3%, perfect in 14 of 100 splits

Seed 42 was a lucky draw. A typical split scores about 95%, an unlucky one lands between 83% and 87%, and a perfect score appears in only 14 to 20 of the 100 splits, depending on the model.

Cross-validation removes the luck by testing on every row. Five-fold means five rounds: train on four fifths of the data, test on the remaining fifth, rotate. Repeating that with ten different shuffles gives 50 test scores per model instead of one. Wrapping the scaler and the model in a pipeline matters here, because the pipeline refits the scaler on each round’s training part only. scikit-learn’s getting started guide says a pipeline used for cross-validation “will largely keep you from this common pitfall”, meaning test-fold information leaking into preprocessing.

from sklearn.dummy import DummyClassifier
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline

cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=0)

for name, model in models.items():
    pipe = make_pipeline(StandardScaler(), model)
    s = cross_val_score(pipe, X, y, cv=cv)
    print(f"{name}: {s.mean():.1%} +/- {s.std():.1%} over {len(s)} test folds")

baseline = cross_val_score(DummyClassifier(strategy="most_frequent"), X, y, cv=cv)
print(f"Always guessing one species: {baseline.mean():.1%}")
AlgorithmHow It DecidesDoes Scaling Matter?Mean AccuracyStd Across Folds
K-Nearest NeighborsVotes among the 5 closest training flowersYes, distances mix all features95.9%3.4 points
Logistic RegressionLearns a weighted score per speciesUsually, its regularization assumes similar ranges95.5%3.6 points
Decision TreeChain of if/then thresholds on single featuresNo94.4%3.9 points

The spread between best and worst model is 1.5 points, while each model’s own score swings by about 3.5 points from fold to fold. On Iris, the ranking is noise. The last line of the script gives the floor: a DummyClassifier, which the documentation describes as “a simple baseline to compare against other more complex classifiers”, ignores the measurements and scores 33.3% on three equal classes.

A rule for any model comparison: report a score together with three companions: the baseline a dummy model reaches (33.3% here), the number of test rows (30, so one row is 3.3 points) and the spread across folds (about 3.5 points). If two models differ by less than that spread, you have not found a winner.

Reading the Classification Report

Accuracy is one number for all species. The classification report splits it per species. This version stratifies the split, so each species contributes exactly 10 flowers to the test set (the unstratified seed-42 split held 10, 9 and 11), and it uses a pipeline for the scaling:

X_tr, X_te, y_tr, y_te = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
pipe.fit(X_tr, y_tr)
print(classification_report(y_te, pipe.predict(X_te), target_names=iris.target_names))
              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        10
  versicolor       0.90      0.90      0.90        10
   virginica       0.90      0.90      0.90        10

    accuracy                           0.93        30
   macro avg       0.93      0.93      0.93        30
weighted avg       0.93      0.93      0.93        30

Same seed, one added argument, and the score falls from 100% to 93.3% (28 of 30). The same drop happens for all three models. The report shows where the two mistakes sit: one versicolor was called virginica and one virginica was called versicolor. Versicolor precision is 9 correct out of 10 predictions of versicolor, 0.90. Versicolor recall is 9 found out of 10 real versicolor flowers, 0.90. The F1-score is the harmonic mean of the two, 2 x 0.90 x 0.90 / (0.90 + 0.90) = 0.90. Setosa is never confused with anything here, and it almost never is elsewhere: summing sklearn.metrics.confusion_matrix over the 100 random splits from the previous section, logistic regression made 140 mistakes in 3,000 predictions, and 139 of those swapped versicolor and virginica.

Per-class numbers also expose what accuracy hides. Take 1,000 emails of which 50 are spam, and a filter that answers “not spam” every time. It is right 950 times, so its accuracy is 95%, and it catches 0 of the 50 spam messages, so its spam recall is 0. scikit-learn’s classification_report prints 0.00 for the spam row and warns that “Precision is ill-defined and being set to 0.0 in labels with no predicted samples”. A DummyClassifier(strategy="most_frequent") reproduces this exactly, which makes it a quick sanity check whenever your classes are lopsided.

When Scaling Matters: The Wine Dataset

On Iris, scaling barely changes anything. With the same repeated cross-validation on the raw centimeter values, K-nearest neighbors scores 96.7% against 95.9% scaled, logistic regression 96.5% against 95.5%, and the decision tree 94.5% against 94.4%. All four Iris features are centimeters between 0.1 and 7.9, so no feature drowns out the others. The wine dataset that ships with scikit-learn (178 wines, 13 chemical measurements, 3 classes) is different: proline runs from 278 to 1680 while hue runs from 0.48 to 1.71.

from sklearn.datasets import load_wine

Xw, yw = load_wine(return_X_y=True)
for use_scaler in (False, True):
    knn = KNeighborsClassifier(n_neighbors=5)
    model = make_pipeline(StandardScaler(), knn) if use_scaler else knn
    s = cross_val_score(model, Xw, yw, cv=cv)
    print(f"KNN, scaled={use_scaler}: {s.mean():.1%}")

The output is 70.6% unscaled and 96.2% scaled, a gap of about 26 points from one preprocessing step. K-nearest neighbors measures distance across all features, so a feature with a range of 1,400 swamps one with a range of 1.2. Logistic regression survives better (94.9% raw, 98.0% scaled), but on the raw data its solver hit the 200-iteration limit and warned in each of the 50 fits (swap LogisticRegression(max_iter=200) into the loop to see it). The decision tree scores 91.0% either way, because a tree only compares one feature against a threshold at a time. scikit-learn’s preprocessing guide gives the general reason: a feature whose variance is orders of magnitude larger than the others “might dominate the objective function”, and its decision tree guide lists “requires little data preparation” as an advantage of trees.

Where to Go After Your First Model

Each next project should add one difficulty you have not met yet.

Columns that are not all numbers. scikit-learn’s mixed-types example trains on the Titanic passenger data from OpenML. It scales the numeric columns (age, fare), one-hot encodes the categorical ones (embarked, sex, passenger class) and fills in missing values, all inside one ColumnTransformer pipeline, and reports a test score of 0.798. Kaggle also hosts a Titanic – Machine Learning from Disaster competition if you want an outside score to compare with.

Predicting a number. Switch to regression with California housing: 20,640 rows, 8 features, and a target of median house value in units of 100,000. It does not ship inside the package. fetch_california_housing downloads it on first use and caches it under ~/scikit_learn_data by default.

Text. scikit-learn’s text feature extraction example chains a TfidfVectorizer and a ComplementNB classifier on two newsgroup categories. Its tuned model reaches 0.816 accuracy under cross-validation but 0.709 on the held-out test set, the kind of gap the first half of this guide taught you to look for.

Saving the model. joblib can write a trained model to disk, but the model persistence guide warns that loading a pickle-based file from an untrusted source can run malicious code, and that there is no supported way to load a model trained with a different scikit-learn version. Pin the version in a requirements file next to the saved model, retrain when you upgrade, and only then put a FastAPI or Flask endpoint in front of it.

Before you close this tab, run the 100-seed loop yourself, then add stratify=y and run it again. From now on, report any accuracy as a mean with a spread, next to a baseline.

Test Set Size
30
one mistake = 3.3 points
Worst Of 100 Splits
83%
same code, different seed
Cross-Validated Mean
94 to 96%
50 test folds per model

Frequently Asked Questions

Do I need to understand the math behind these algorithms before I start?

Not to run them. You do need to be comfortable with fractions and averages, because precision, recall and the spread across folds are all simple ratios, worked through above. The math starts to pay off when you tune a model: the number of neighbors in K-nearest neighbors, the regularization strength in logistic regression, or the depth limit that keeps a tree from becoming, in the words of the scikit-learn tree guide, “over-complex” and unable to “generalize the data well”.

Why don’t my numbers match the ones above?

Check four things: the random_state values (seed 42 for the single split, seeds 0 to 99 for the loop, 0 for the repeated cross-validation), whether you passed stratify=y, whether you scaled before splitting, and the scikit-learn version (the numbers here come from 1.9.1). Different versions can give slightly different results, so compare the size of the spread rather than the last decimal.

Is Iris too easy to be a good first project?

scikit-learn’s own documentation calls it “a classic and very easy multi-class classification dataset”. That is why it suits learning the workflow, and why it is a poor way to compare algorithms: three different methods finished within 1.5 points of each other, inside the noise. For comparison practice, move to data where preprocessing choices change the result, such as the wine dataset above, where skipping the scaler cost K-nearest neighbors about 26 points.

Leave a comment