Last modified: Aug 27, 2026
AI Code Examples in Python for Beginners
Artificial Intelligence is no longer a mystery. You can start building smart applications today. Python makes this easy with its simple syntax. This guide offers practical AI code examples for you to try.
You will learn by doing. We will cover data handling, model building, and predictions. Each example is short and focused. You can copy, run, and modify them easily. This hands-on approach builds real skills fast.
Let’s start with the basics. We will use popular libraries like NumPy and scikit-learn. These tools are the building blocks of modern AI. If you need a refresher, check out this guide on top Python AI libraries for beginners.
Setting Up Your Python Environment
Before writing code, install the necessary packages. Open your terminal or command prompt. Run the following command to install everything we need.
pip install numpy scikit-learn matplotlib
This command installs numerical tools and machine learning models. It might take a minute. Once finished, you are ready to code. Always ensure your packages are up to date for best results.
Example 1: Simple Linear Regression
Linear regression predicts a continuous value. Imagine predicting house prices based on size. This is a perfect starting point. It teaches the core concept of supervised learning.
We will create fake data to learn from. The model will find the relationship between input and output. This is a foundational skill for many AI applications.
# Import the necessary library
from sklearn.linear_model import LinearRegression
import numpy as np
# Create sample data (house size in sq ft)
X = np.array([[500], [800], [1000], [1200], [1500]])
# Corresponding prices in thousands
y = np.array([150, 210, 260, 310, 380])
# Create and train the model
model = LinearRegression()
model.fit(X, y)
# Make a prediction for a new house size
new_house = np.array([[1100]])
predicted_price = model.predict(new_house)
print(f"Predicted price for 1100 sq ft: ${predicted_price[0]:.0f}k")
The fit method trains the model on our data. The predict method uses the learned pattern to guess new values. This is the heart of machine learning.
Predicted price for 1100 sq ft: $286k
The output shows our model's guess. It learned the trend from the examples. This simple example is the basis for more complex models. You can easily expand this to multiple features.
Example 2: Image Classification with KNN
Image classification is a popular AI task. We will use a simple dataset of handwritten digits. The K-Nearest Neighbors (KNN) algorithm is easy to understand and effective for this.
We will load a built-in dataset from sklearn. This saves us time on data collection. The model will learn to recognize digits from 0 to 9.
# Import necessary modules
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# Load the digits dataset
digits = load_digits()
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
digits.data, digits.target, test_size=0.3, random_state=42
)
# Create and train the KNN classifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
# Evaluate the model's accuracy
accuracy = knn.score(X_test, y_test)
print(f"Model accuracy: {accuracy:.2f}")
We split the data to test on unseen examples. The score method calculates how often the model is correct. This tells us if our model is learning well.
Model accuracy: 0.98
An accuracy of 98% is excellent. The model correctly identifies most digits. This demonstrates the power of simple algorithms. You can use this pattern for other classification problems.
Example 3: Text Sentiment Analysis
Understanding text sentiment is valuable. Businesses use it to analyze customer feedback. We will build a simple sentiment analyzer using a Naive Bayes classifier.
This model will classify text as positive or negative. We will use a small dataset to illustrate the process. This is a great introduction to natural language processing (NLP).
# Import necessary libraries
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
# Sample text data
texts = [
"I love this product",
"This is terrible",
"Great experience",
"Worst service ever",
"Very happy with this",
"Not good at all"
]
# Labels: 1 for positive, 0 for negative
labels = [1, 0, 1, 0, 1, 0]
# Convert text into numerical features
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
# Train the classifier
clf = MultinomialNB()
clf.fit(X, labels)
# Test with new sentences
test_texts = ["I am so happy", "This is bad"]
test_X = vectorizer.transform(test_texts)
predictions = clf.predict(test_X)
for text, pred in zip(test_texts, predictions):
sentiment = "Positive" if pred == 1 else "Negative"
print(f"'{text}' -> {sentiment}")
The CountVectorizer converts words into numbers. The model learns which words indicate positive or negative sentiment. This is a core NLP technique.
'I am so happy' -> Positive
'This is bad' -> Negative
The model correctly identifies the sentiment. This simple approach works surprisingly well. You can scale this up with larger datasets for real-world use.
Example 4: Clustering with K-Means
Clustering finds groups in data without labels. This is unsupervised learning. It's useful for customer segmentation or data exploration. K-Means is a popular clustering algorithm.
We will create random data points and group them. This helps you understand patterns in unlabeled data. It's a powerful tool for discovering hidden structures.
# Import libraries
from sklearn.cluster import KMeans
import numpy as np
# Create sample data points
X = np.array([
[1, 2], [1, 4], [1, 0],
[10, 2], [10, 4], [10, 0]
])
# Create and fit the K-Means model
kmeans = KMeans(n_clusters=2, random_state=0)
kmeans.fit(X)
# Get the cluster labels for each point
labels = kmeans.labels_
print("Cluster labels:", labels)
print("Cluster centers:\n", kmeans.cluster_centers_)
The n_clusters parameter sets how many groups to find. The model automatically assigns each point to a cluster. The cluster_centers_ shows the middle of each group.
Cluster labels: [0 0 0 1 1 1]
Cluster centers:
[[ 1. 2.]
[10. 2.]]
The algorithm found two clear groups. The first three points belong to cluster 0. The last three belong to cluster 1. This is how you can find patterns in data.
Example 5: Neural Network with Keras
Neural networks power modern AI. They are flexible and powerful. We will build a simple one using Keras. This library makes deep learning accessible to everyone.
We will solve a simple classification problem. This example introduces you to the concept of layers and training. It's your first step into deep learning.
# Import Keras modules
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
# Create simple data
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype='float32')
# XOR logic gate output
y = np.array([0, 1, 1, 0], dtype='float32')
# Build the model
model = keras.Sequential([
layers.Dense(16, activation='relu', input_shape=(2,)),
layers.Dense(1, activation='sigmoid')
])
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X, y, epochs=100, verbose=0)
# Test the model
predictions = model.predict(X)
print("Predictions after training:")
for i, pred in enumerate(predictions):
print(f"Input: {X[i]} -> Predicted: {pred[0]:.2f} (Actual: {y[i]})")
The Dense layer creates a fully connected neural network. The compile method configures the learning process. The fit method trains the network on our data.
Predictions after training:
Input: [0. 0.] -> Predicted: 0.02 (Actual: 0.0)
Input: [0. 1.] -> Predicted: 0.98 (Actual: 1.0)
Input: [1. 0.] -> Predicted: 0.98 (Actual: 1.0)
Input: [1. 1.] -> Predicted: 0.03 (Actual: 0.0)
The network learned the XOR pattern. Predictions are close to the actual values. This shows how neural networks can learn complex relationships.
Next Steps in Your AI Journey
You have now seen five core AI examples. These cover regression, classification, NLP, clustering, and deep learning. Each one is a stepping stone to more advanced topics.
Practice by changing the data and parameters. Experimentation is key to mastery. Try adding more features or changing the network structure. The possibilities are endless.
To deepen your understanding, explore a structured path. You can follow a Python AI course for step-by-step guidance. This will help you build a solid foundation.
Also, review the different tools available. Understanding your options is crucial. Read about the top Python AI frameworks to choose the right one for your projects. This knowledge will save you time later.
Common Mistakes to Avoid
Beginners often make similar errors. One is using too little data. Models need enough examples to learn effectively. Another mistake is forgetting to split data into training and testing sets.
Always check your input data types. Mismatched types cause many errors. Also, don't ignore the importance of data cleaning. Quality data leads to quality models.
Remember to scale your features when needed. Many algorithms perform better with normalized data. These small details make a big difference in performance.
Conclusion
You have successfully learned AI code examples in Python. You now know how to build models for prediction, classification, and clustering. This is a solid start to your AI journey.
Keep practicing with these examples. Modify them and see what happens. The best way to learn is by doing. Your skills will grow with every line of code you write.
Remember, AI is a powerful tool. Use it responsibly and creatively. The projects you can build are limited only by your imagination. Start building something amazing today.