Build Your First Machine Learning Model in Python (20-Minute Tutorial)
What You’ll Need
- Python 3.8+ installed
- Virtual environment (venv, Conda, etc.)
- Familiarity with Python basics
- Libraries:
scikit-learn,pandas,numpy,matplotlib
Step 1 — Load Your Dataset
We’ll use the built-in Iris dataset:
from sklearn.datasets import load_iris
import pandas as pd
iris = load_iris()
X = pd.DataFrame(iris.data, columns=iris.feature_names)
y = pd.Series(iris.target, name='species')
print(X.head())
print(y.value_counts())
Step 2 — Split into Train & Test
Keep an 80/20 split to evaluate on unseen data:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
Step 3 — Train a Simple Classifier
Using Logistic Regression:
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
Step 4 — Evaluate Model Performance
Check accuracy and visualize a confusion matrix:
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import matplotlib.pyplot as plt
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred, target_names=iris.target_names))
cm = confusion_matrix(y_test, y_pred)
plt.imshow(cm, cmap='Blues', interpolation='nearest')
plt.title("Confusion Matrix")
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.colorbar()
plt.show()
Tip: Aim for 80–90 % accuracy on Iris as your first milestone.
Step 5 — Make a New Prediction
Use your model on a custom example:
sample = [[5.1, 3.5, 1.4, 0.2]]
pred_class = iris.target_names[model.predict(sample)[0]]
print("Predicted species:", pred_class)
Step 6 — Deploy as a Minimal API (Bonus)
Serve predictions with Flask:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
data = request.json['features']
pred = model.predict([data])[0]
return jsonify({"species": iris.target_names[pred]})
Next: containerize with Docker or deploy on AWS Lambda.
Guided, Mentor-Led Sessions
Hands-on workflows, live Q&A, & code reviews every week.
6-Week Job-Ready Roadmap
- Regression & classification
- Deep learning with TensorFlow
- API deployment with Flask & Streamlit
- Interview prep challenges
Common Gotchas & Tips
- Scale features with
StandardScaler(). - Prevent overfitting by monitoring train/test gap.
- Use
GridSearchCVfor hyperparameter tuning.
What You’ve Achieved
- Loaded & explored data
- Trained & evaluated a model
- Visualized performance
- Served predictions via API
Level-Up with the Full Course
Master advanced ML techniques, live projects, & career coaching.