Build Your First Machine Learning Model with Python
Difficulty: Beginner – Intermediate
This tutorial shows you how to build your first supervised machine learning model using scikit-learn, one of the most popular Python libraries for ML. No advanced math required!
🔧 What You'll Learn
- What supervised learning is
- How to load and explore datasets
- How to train a model in Python
- How to test and evaluate it
🧰 Prerequisites
Ensure you have the following installed:
- Python 3.x
- scikit-learn
- pandas
- matplotlib (optional for visualization)
You can install them via pip:
pip install scikit-learn pandas matplotlib
📦 Step 1: Import Libraries
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
🌸 Step 2: Load the Dataset
We’ll use the built-in Iris
dataset:
iris = load_iris()
X = iris.data # Features
y = iris.target # Labels
🔀 Step 3: Split the Data
Split into 80% training and 20% testing:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
🤖 Step 4: Train the Model
We’ll use the K-Nearest Neighbors algorithm:
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
📊 Step 5: Make Predictions
y_pred = model.predict(X_test)
📈 Step 6: Evaluate the Model
Check the accuracy:
accuracy = accuracy_score(y_test, y_pred)
print("Model Accuracy:", accuracy)
🎉 Done!
You’ve just built and evaluated your first ML model. You can now try other algorithms like Decision Trees, SVM, or even deep learning with TensorFlow.
📘 Challenge for Students
- Try changing
n_neighbors
to 5 or 7 - Visualize the dataset with matplotlib
- Try a different dataset (e.g.,
load_digits()
)
Subscribe to DarchumsTech for more tutorials and AI content tailored to students and young developers.
Comments
Post a Comment