Python for Machine Learning
Python is one of the most widely used languages for Machine Learning. This tutorial focuses on the Python concepts you actually need to begin working with ML data and models.
How Python Fits Into Machine Learning
You do not need to master all of Python before starting Machine Learning. Think of Python as the tool you use to store data, prepare it, train a model, and ask the model for a prediction.
Collect Data
Study hours + marks
Use Python
Store and prepare the data
Train a Model
Let an ML library learn the pattern
Make a Prediction
Predict marks for a new student
Python is the tool that connects your data, ML libraries, and predictions.
A Tiny First ML Example: Study Hours → Marks
Suppose we have four students. We know how long they studied and the marks they received:
| Study Hours | Marks |
|---|---|
| 1 | 40 |
| 2 | 50 |
| 3 | 60 |
| 4 | 70 |
With only a few lines of Python, we can give these examples to a simple ML model and ask it to predict the marks for a student who studies for 5 hours.
from sklearn.linear_model import LinearRegression
# X = input feature: study hours
X = [[1], [2], [3], [4]]
# y = known answers: marks
y = [40, 50, 60, 70]
model = LinearRegression()
model.fit(X, y)
predicted_marks = model.predict([[5]])
print(predicted_marks[0])80.0
Step 1
X stores the information we give the model: study hours. Each inner list represents one student row.
Step 2
y stores the correct answers we already know: marks.
Step 3
model.fit(X, y) lets the model learn the simple pattern in those examples.
Step 4
model.predict([[5]]) asks: what marks would you expect for 5 study hours?
Keep this example simple
Why Python for Machine Learning?
Readable Syntax
Python is designed to be readable, so beginners can spend more attention on the data and ML idea instead of complicated language syntax.
Large ML Library Ecosystem
Libraries such as NumPy, Pandas, Scikit-learn and PyTorch provide ready-made tools for many common ML tasks.
Cross-Platform
Python works across Windows, macOS and Linux. You still need to manage packages and environments correctly when moving code between systems.
Large Community
Python has extensive documentation, tutorials and open-source examples, so help is available for many common beginner and ML problems.
Setting Up Python for Machine Learning
You have several good ways to start. If you are completely new, choose the option that creates the least setup work for you.
| Option | Setup | Good for |
|---|---|---|
| Google Colab | Nothing to install | Best if you want to start immediately |
| Anaconda | One beginner-friendly package | Useful for a local data-science setup |
| Python + virtual environment | Lightweight setup | Useful when you want more control |
If you choose a local Anaconda setup, verify that Python and Conda are available, then install any libraries you still need:
# Verify your local installation
python --version
conda --version
# Install key libraries if needed
pip install numpy pandas scikit-learn matplotlib seabornBeginner tip: notebooks are convenient
Core Python Concepts for ML
You do not need every Python feature before learning ML. Start with these five building blocks:
| Python concept | Simple ML use |
|---|---|
| Variables | Store values such as age, salary or learning rate. |
| Lists | Keep several values such as marks or predictions together. |
| Dictionaries | Store named settings such as model hyperparameters. |
| Functions | Reuse a calculation instead of writing it repeatedly. |
| Files | Load datasets and save predictions or results. |
1. Variables & Data Types
# Basic types
age = 25 # int
gpa = 3.8 # float
name = "Alice" # string
passed = True # bool
# Check type
print(type(gpa)) # <class 'float'>
print(isinstance(age, int)) # True<class 'float'> True
2. Lists & List Comprehensions
Lists hold sequences of values. List comprehensions are a compact Python shorthand that is often useful when preparing data.
scores = [88, 72, 95, 61, 84]
# Slice: first 3 elements
print(scores[:3]) # [88, 72, 95]
# List comprehension: scale scores to 0-1
normalised = [s / 100 for s in scores]
print(normalised) # [0.88, 0.72, 0.95, 0.61, 0.84]
# Filter: only scores above 80
high = [s for s in scores if s > 80]
print(high) # [88, 95, 84][88, 72, 95] [0.88, 0.72, 0.95, 0.61, 0.84] [88, 95, 84]
3. Dictionaries
Dictionaries map keys to values — essential for storing model hyperparameters and results.
params = {"learning_rate": 0.01, "max_depth": 5, "n_estimators": 100}
# Access
print(params["learning_rate"]) # 0.01
# Add / Update
params["max_features"] = "sqrt"
print(params)
# Loop over hyperparameters
for key, value in params.items():
print(f"{key}: {value}")0.01
{'learning_rate': 0.01, 'max_depth': 5, 'n_estimators': 100, 'max_features': 'sqrt'}
learning_rate: 0.01
max_depth: 5
n_estimators: 100
max_features: sqrt4. Functions
def mean_squared_error(actual, predicted):
"""Calculate MSE between two lists."""
n = len(actual)
squared_errors = [(a - p) ** 2 for a, p in zip(actual, predicted)]
return sum(squared_errors) / n
actual = [10, 20, 30, 40]
predicted = [12, 18, 33, 37]
mse = mean_squared_error(actual, predicted)
print(f"MSE: {mse}") # MSE: 6.5MSE: 6.5
What did this function calculate?
Do not worry if you have not learned MSE yet. The purpose here is to see how a Python function turns repeated calculation steps into reusable code.
| Actual | Predicted | Error² |
|---|---|---|
| 10 | 12 | (10 − 12)² = 4 |
| 20 | 18 | (20 − 18)² = 4 |
| 30 | 33 | (30 − 33)² = 9 |
| 40 | 37 | (40 − 37)² = 9 |
Step 1: Add the squared errors: 4 + 4 + 9 + 9 = 26.
Step 2: There are 4 predictions, so divide by 4.
Step 3: MSE = 26 ÷ 4 = 6.5.
5. File Handling (Loading Datasets)
import csv
# Read a CSV file without Pandas
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["score"])
# Write results to a CSV
with open("results.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "prediction"])
writer.writerow(["Alice", 0.92])Complete Python ML Workflow Example
The next example is more realistic than our tiny first example. Read the six numbered comments first; they tell you the whole story before you worry about every line of code.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
# ── 1. Load Data ────────────────────────────────
df = pd.read_csv("students.csv")
print(df.head())
# ── 2. Define Features (X) and Label (y) ───────
X = df[["study_hours", "sleep_hours", "attendance_pct"]]
y = df["passed"] # 1 = passed, 0 = failed
# ── 3. Split into Train / Test ──────────────────
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(f"Train samples: {len(X_train)}, Test samples: {len(X_test)}")
# ── 4. Feature Scaling ─────────────────────────
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train) # fit on train only!
X_test = scaler.transform(X_test)
# ── 5. Train Model ─────────────────────────────
model = LogisticRegression()
model.fit(X_train, y_train)
# ── 6. Predict & Evaluate ──────────────────────
predictions = model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, predictions):.2%}")
print(classification_report(y_test, predictions))Train samples: 800, Test samples: 200
Accuracy: 87.50%
precision recall f1-score
0 0.85 0.88 0.87
1 0.90 0.87 0.88The ML Python Library Stack
| Library | Purpose | Key Objects | Import |
|---|---|---|---|
| NumPy | Fast numerical arrays & linear algebra | ndarray | import numpy as np |
| Pandas | Tabular data loading, cleaning & analysis | DataFrame, Series | import pandas as pd |
| Matplotlib | Static plots & charts | Figure, Axes | import matplotlib.pyplot as plt |
| Seaborn | Statistical visualisations (built on Matplotlib) | heatmap, pairplot | import seaborn as sns |
| Scikit-learn | Classic ML algorithms & evaluation | estimator API | from sklearn import ... |
| PyTorch | Deep Learning & neural networks | Tensor, nn.Module | import torch |
| XGBoost | Efficient gradient-boosted decision trees | XGBClassifier | import xgboost as xgb |
Common Beginner Questions
Do I need advanced Python before learning Machine Learning?
No. Be comfortable with variables, lists, dictionaries, loops, functions and basic file/data handling. You can learn more Python as your ML tasks become more advanced.
Is Python the only language used for Machine Learning?
No. ML can be built with several languages. Python is especially popular for learning, experimentation and data science because of its readable syntax and strong library ecosystem.
What should I learn after basic Python?
Learn NumPy for numerical arrays, Pandas for tables and data preparation, and Scikit-learn for classic ML workflows.
Next Steps