Skip to main content

Practical Code Examples

โฑ 13 min read ยท Chapter 5 ยท Foundations

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.

End-to-end classification in ~10 lines.
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

Example 2 โ€” Recognize handwritten digitsโ€‹

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

Image classification with a support-vector machine.
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

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.

From text to prediction.
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']

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.

State-of-the-art sentiment in 3 lines.
from transformers import pipeline

classifier = pipeline("sentiment-analysis")
result = classifier("AIbyExamples makes this so clear!")
print(result)
# [{'label': 'POSITIVE', 'score': 0.9998}]

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.

A typical chat completion request.
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)
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.