Guilds AI / Blog

,

4 AI Code Examples in Python You Can Run Locally

Laptop displaying illustrative Python code in a dark editor alongside an AI chip symbol.

These AI code examples show how to build four small machine learning programs in Python: predicting a number, categorizing support messages, grouping observations and recognizing handwritten digits. Each script was tested locally using scikit-learn, and none requires a paid AI API. The examples explain what the models learn and what their outputs do and do not demonstrate.

For guided practice with coding agents while developing your programming skills, see our Claude Code learning path.

For a complete beginner project with six unit tests, see our Python chatbot code guide.

Set up Python for the examples

These four exercises use scikit-learn, an open-source machine learning library. They cover supervised regression, supervised classification, unsupervised clustering and image classification. Each example runs independently on a CPU without a paid model API or downloaded training corpus. Create a virtual environment and install the library.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install scikit-learn

On Windows PowerShell, activate the environment with .venv\Scripts\Activate.ps1. Save each script in a separate Python file and execute it with python followed by its filename. The examples were executed with scikit-learn 1.8.0; use a compatible Python version and record your dependencies if you want reproducible results.

1. Predict a number with linear regression

Regression estimates a numerical target. Suppose a fictional printing service charges a fixed fee plus an amount per page. Four artificial observations are enough to demonstrate how a linear model learns the relationship.

from sklearn.linear_model import LinearRegression

pages = [[1], [2], [3], [4]]
costs = [12, 19, 26, 33]

model = LinearRegression().fit(pages, costs)
print(model.predict([[5]])[0])

Tested output: 40.0. The model learns an increase of seven units per page and a fixed component of five units. Each input is a list of features, even when the example uses just one feature. This synthetic dataset follows a perfect straight line. Real costs may include discounts, minimum charges and other variables; this example does not establish prediction accuracy on actual pricing data.

2. Classify a support message

Text classification assigns a label to a message. This example learns to distinguish billing questions from account-access requests. TF-IDF converts words into numerical features based on their occurrence and relative importance. A naive Bayes classifier learns associations between those features and the labels. The pipeline keeps the text transformation and classifier together.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

texts = [
    "invoice payment due",
    "refund payment request",
    "invoice billing question",
    "cannot login password",
    "reset password login",
    "account login problem",
]
labels = ["billing"] * 3 + ["access"] * 3

model = make_pipeline(
    TfidfVectorizer(), MultinomialNB()
).fit(texts, labels)

print(model.predict([
    "reset my password", "invoice payment"
]).tolist())

Tested output: [‘access’, ‘billing’]. These six training messages are deliberately simple, and the two new phrases demonstrate prediction rather than reliable evaluation. A request such as ‘I cannot access my invoice’ may contain signals from both classes. For a real support system, add representative labeled examples, reserve a test set and allow uncertain requests to be reviewed by a person.

3. Find groups with k-means clustering

Clustering finds groups without training labels. This exercise uses two artificial numerical features and six observations. The two groups are visibly separated, which makes the learned centers easy to inspect.

from sklearn.cluster import KMeans

points = [
    [1, 2], [2, 1], [1, 1],
    [9, 8], [8, 9], [9, 9]
]
model = KMeans(
    n_clusters=2, n_init=10, random_state=42
).fit(points)

print(sorted(model.cluster_centers_.tolist()))

The tested centers, rounded to two decimal places, are [1.33, 1.33] and [8.67, 8.67]. K-means assigns observations to their nearest cluster center and iteratively adjusts the centers. Cluster identifiers are arbitrary: cluster zero is not necessarily the lower-valued group. Real clustering projects require sensible feature scaling and validation of whether the chosen groups are useful. The algorithm does not discover the business meaning of a cluster by itself.

4. Recognize handwritten digits

The built-in digits dataset contains small grayscale images represented by 64 numerical pixel values per image, with labels from zero to nine. A nearest-neighbor classifier predicts a label by comparing a new image with similar labeled examples. Unlike the preceding demonstrations, this exercise reserves a separate test set.

from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)

model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

print(f"Accuracy: {accuracy_score(y_test, predictions):.2%}")
print(f"Test examples: {len(y_test)}")

Tested output: accuracy 98.61%, with 360 test examples. That is 355 correct classifications in this particular split. It does not establish accuracy on photographs, unfamiliar handwriting styles or larger images. A real image application needs tests representing its actual input conditions. Inspect incorrect predictions and compare performance with a baseline before deploying a model.

How to use AI in coding these projects

A coding assistant can explain a model, generate test cases or help interpret an error message. Ask it to solve a specific problem and verify its proposed code independently. For example, request a test for an empty input or an explanation of why a text classifier fails on unfamiliar words. Do not let generated code install packages, access credentials or modify unrelated files without review.

Building software that uses machine learning and using generative AI to assist with programming are different activities. Our AI agents for coding guide covers coding assistance in more detail.

Move from scripts to a working application

Start with an appropriate metric: mean absolute error for a numerical prediction, classification metrics for labeled examples, or a suitable cluster-quality measure for unsupervised learning. Avoid evaluating a supervised model solely on the examples it learned from. Use held-out data and maintain a repeatable test process; our AI evals guide explains task-specific evaluation.

Once a model is useful, connect it to an interface, validate inputs and monitor results. Follow our tutorial on creating a machine learning app for a complete example with Streamlit. The four scripts above are educational examples, not production-ready services.

If your goal is to generate ordinary Python code rather than build a machine learning model, compare the tools in our AI Python code generator guide.

Frequently asked questions

Can I run AI code without a GPU? Yes. These examples use small datasets and traditional machine learning algorithms that run on a CPU.

Do AI code examples require an API key? These four examples do not. Hosted language-model applications generally require authorized service access.

Which Python library should beginners start with? Scikit-learn is a useful starting point for traditional machine learning. Choose a deep learning framework when the task requires neural network development.

Is high test accuracy enough to deploy a model? No. Check representative input conditions, error costs, data leakage, security and ongoing performance before deployment.