AIbyExamples
Chapter 5

Practical Code Examples

Copy-paste-ready Python examples for classification, image recognition, text sentiment, and calling a modern language model.

13 min read

Theory sticks when you run it. This chapter is a collection of small, self-contained programs. Each one solves a real AI task in just a few lines. Install the libraries you need with pip install scikit-learn torch transformers.

Run these in order

Every example is independent. Copy one into a file or notebook cell and run it. Tweak the inputs to build intuition.

Example 1 — Classify flowers (Iris)

The classic "hello world" of ML: predict the species of an iris flower from its measurements.

python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2)

clf = RandomForestClassifier().fit(X_tr, y_tr)
print("accuracy:", round(clf.score(X_te, y_te), 3))  # ~0.97
End-to-end classification in ~10 lines.

Example 2 — Recognize handwritten digits

A slightly harder image task: recognize digits (0–9) from 8x8 pixel images.

python
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

digits = load_digits()
X_tr, X_te, y_tr, y_te = train_test_split(
    digits.data, digits.target, test_size=0.25
)

model = SVC(gamma=0.001).fit(X_tr, y_tr)
print("accuracy:", round(model.score(X_te, y_te), 3))  # ~0.99
Image classification with a support-vector machine.

Example 3 — Text sentiment analysis

Turn raw text into a positive / negative signal. We vectorize words with a bag-of-words model and train a simple classifier.

python
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

texts = ["I love this", "awful and boring",
         "best ever", "terrible waste of time"]
labels = ["pos", "neg", "pos", "neg"]

vec = CountVectorizer()
X = vec.fit_transform(texts)
clf = MultinomialNB().fit(X, labels)

test = vec.transform(["I really love the best parts"])
print(clf.predict(test))  # -> ['pos']
From text to prediction.

Example 4 — Use a pretrained model

You rarely need to train from scratch. The Hugging Face transformers library lets you use powerful pretrained models with a single pipeline call.

python
from transformers import pipeline

classifier = pipeline("sentiment-analysis")
result = classifier("AIbyExamples makes this so clear!")
print(result)
# [{'label': 'POSITIVE', 'score': 0.9998}]
State-of-the-art sentiment in 3 lines.

Example 5 — Call a large language model

Modern apps often call a hosted LLM through an API. The pattern is always the same: send messages, receive a completion.

python
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from the environment

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a helpful tutor."},
        {"role": "user", "content": "Explain overfitting in one sentence."},
    ],
)
print(response.choices[0].message.content)
A typical chat completion request.

Keep API keys secret

Never hard-code API keys in your source or commit them to git. Load them from environment variables and store them in a .env file that is git-ignored.

Where to go next

  • Re-implement Example 1 with a neural network in PyTorch.
  • Swap datasets — try the Wine or Breast Cancer datasets from scikit-learn.
  • Explore the Hugging Face Hub for models on translation, summarization and vision.
  • Build a tiny web app that wraps one of these models behind a form.

You made it!

You now understand the core ideas of AI and can run real examples. The best next step is to pick one snippet and extend it into a small project of your own.