Build a Simple AI Model in Python
Build a Simple AI Model in Python
Artificial Intelligence (AI) is accessible to all with Python, a language that can be mastered for building robust models. Let’s create a linear regression model to predict Johannesburg traffic congestion using NumPy and scikit-learn. This hands-on tutorial leverages a simulated dataset, showcasing expertise in clean, efficient code.
Why Linear Regression?
Linear regression predicts a continuous outcome (e.g., traffic delay in minutes) based on input features (e.g., time of day, road conditions). It’s ideal for beginners and a stepping stone to advanced AI techniques.
Simulated Johannesburg Traffic Data
We’ll use a synthetic dataset mimicking Johannesburg’s morning rush hour traffic, with features: time (hours), weather (1 = clear, 0 = rainy), and delay (minutes).
Step-by-Step Tutorial
1. Setup and Imports
First, import required libraries. Ensure you have NumPy and scikit-learn installed (pip install numpy scikit-learn).
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
2. Data Preprocessing
Create and preprocess the dataset. This step highlights my skill in handling data efficiently.
# Simulated Johannesburg traffic data
time = np.array([6, 7, 8, 9, 10]).reshape(-1, 1) # Hours since midnight
weather = np.array([1, 0, 1, 0, 1]).reshape(-1, 1) # 1 = clear, 0 = rainy
delay = np.array([10, 25, 15, 30, 12]) # Delay in minutes
# Combine features
X = np.hstack((time, weather))
y = delay
3. Train the Model
Train the linear regression model with scikit-learn, demonstrating expertise in model training.
# Initialize and fit the model
model = LinearRegression()
model.fit(X, y)
# Coefficients and intercept
print(f”Coefficients: {model.coef_}”)
print(f”Intercept: {model.intercept_}”)
# Predict
predictions = model.predict(X)
print(f”Predictions: {predictions}”)
4. Visualize Results
Visualize the model’s fit, a key skill in interpreting AI outputs.
plt.scatter(X[:, 0], y, color=’blue’, label=’Actual Delay’)
plt.plot(X[:, 0], predictions, color=’red’, label=’Predicted Delay’)
plt.xlabel(‘Time (Hours)’)
plt.ylabel(‘Delay (Minutes)’)
plt.title(‘Johannesburg Traffic Delay Prediction’)
plt.legend()
plt.show()
Interpretation
The model learns that delays increase with time and are lower on clear days. Adjust the dataset with real Johannesburg traffic data (e.g., from city APIs) for accuracy.
Next Steps
Experiment by adding features like road closures or holidays. Join our Telegram community at https://t.me/TheAIjournalSA for more Python tips and support.
With this tutorial, you’ve built a simple AI model—proof of Python’s power. Keep coding!