Python 10day Notes
Python 10day Notes
Intermediat
Day 6 ■■ OOP — Classes & Objects e
Data
Day 7 ■ NumPy Mastery Science
Data
Day 8 ■ Pandas for Data Analysis Science
Data
Day 9 ■ Data Visualization Science
Machine
Day 10 ■ Scikit-Learn & ML Basics Learning
Machine
Day 11 ■ Advanced ML & Tuning Learning
Deep
Day 12 ■ Deep Learning with PyTorch Learning
Python is a dynamically typed, interpreted language. Variables need no type declaration — Python infers the type
at runtime. These building blocks are the foundation of every DS/ML script you will ever write.
score = 0.9427
print(f'Accuracy: {score:.2%}') # Accuracy: 94.27%
print(f'Pi ~ {3.14159:.2f}') # Pi ~ 3.14
Practice Problems
Easy 1. Write a program that asks the user for their name and age, then prints: 'Hello Alice! In 10 years you will
be 35.'
Easy 2. Given a float 0.8763, format and print it as a percentage with 1 decimal place.
Mediu 3. Write a temperature converter: ask the user for Celsius, convert to Fahrenheit (F = C * 9/5 + 32) and
m
Kelvin (K = C + 273.15), print all three.
Mediu 4. Given the string ' Python is AMAZING ', produce: 'python is amazing' (stripped and lowercased) and
m
count how many words it contains.
Hard 5. Write a simple BMI calculator. Input: weight (kg) and height (m). Output: BMI value rounded to 2
decimal places and the category (Underweight <18.5, Normal 18.5-25, Overweight 25-30, Obese >30).
Control flow statements direct the order in which code executes. Mastering loops is critical for data iteration, model
training, and batch processing.
■ Conditionals
if/elif/else evaluates boolean expressions. Python uses indentation (4 spaces) to define code blocks — there are
no curly braces.
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
print(f'Grade: {grade}') # Grade: B
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
upper = [[Link]() for w in labels]
for i in range(10):
if i == 3: continue # skip 3
if i == 7: break # stop at 7
print(i, end=' ') # 0 1 2 4 5 6
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Print all numbers from 1 to 50 that are divisible by 3 or 5 using a for loop.
Easy 2. Use a while loop to keep asking the user for a password until they type 'python123'. Print 'Access
granted' when correct.
Mediu 3. Write a program to find all prime numbers between 1 and 100 using nested loops.
m
Mediu 4. Given a list of exam scores [78,92,55,88,73,95,60,41,85,67], use list comprehension to create: (a)
m
scores above 70, (b) letter grades for each score.
Hard 5. Implement FizzBuzz for 1-100: print 'Fizz' for multiples of 3, 'Buzz' for multiples of 5, 'FizzBuzz' for
both, and the number otherwise. Then count how many of each category appeared.
Python's built-in data structures — list, tuple, dict, set — are the workhorses of data science. Understanding their
properties, time complexities, and use-cases is essential.
data = [3, 1, 4, 1, 5, 9, 2, 6]
data[0] # 3 (first)
data[-1] # 6 (last)
data[1:4] # [1, 4, 1]
data[::2] # every 2nd: [3, 4, 5, 2]
data[::-1] # reversed: [6, 2, 9, 5, 1, 4, 1, 3]
■ Dictionaries
Dicts store key-value pairs. Keys must be hashable (str, int, tuple). Lookup: O(1). Used everywhere for
hyperparameters, configs, and word frequency counts.
# Dict comprehension
squared = {x: x**2 for x in range(5)}
# Tuple unpacking
point = (3.0, 7.5)
x, y = point
# Sets
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b) # {3, 4} intersection
print(a | b) # {1,2,3,4,5,6} union
print(a - b) # {1, 2} difference
print(3 in a) # True O(1) lookup
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Given the list [5,2,8,1,9,3,7,4,6], sort it ascending and descending without modifying the original. Print
all three.
Easy 2. Create a dictionary of 5 countries and their capitals. Then print only the countries whose capital
contains the letter 'a'.
Mediu 3. Given a sentence string, count the frequency of each word using a dictionary (without Counter). Then
m
find the top 3 most frequent words.
Mediu 4. You have two lists: students = ['Alice','Bob','Charlie','Diana'] and scores = [88,72,95,81]. Create a dict
m
mapping student to score, then find the student with the highest score.
Hard 5. Implement a simple inventory system using a dict. Support: add_item(name, qty), remove_item(name,
qty), check_stock(name), and list_low_stock(threshold). Test with at least 5 items.
Functions are reusable blocks of code that promote modularity and readability. Python's flexible argument system
(*args, **kwargs) is heavily used in ML libraries like PyTorch and scikit-learn.
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Write a function celsius_to_all(c) that returns a dict with keys 'fahrenheit' and 'kelvin' containing the
converted values.
Easy 2. Write a function is_palindrome(s) that returns True if the string reads the same forwards and
backwards (case-insensitive).
Mediu 3. Write a function flatten(nested_list) that takes a list of lists (any depth) and returns a flat list. E.g.
m
flatten([1,[2,[3,4]],5]) -> [1,2,3,4,5].
Mediu 4. Write a function moving_average(data, window) that returns the list of moving averages. Handle edge
m
cases where len(data) < window.
Hard 5. Implement a decorator @timer that measures and prints the execution time of any function. Test it on
a function that computes the sum of squares from 1 to 1,000,000.
Production data science requires robust file handling and error management. Data pipelines that crash silently or
lose results are useless — proper I/O and exception handling keeps systems reliable.
# Write
with open('[Link]', 'w') as f:
for r in [0.91, 0.93, 0.95]:
[Link](f'{r}\n')
# Read CSV
with open('[Link]') as f:
reader = [Link](f)
rows = list(reader)
# JSON round-trip
config = {'lr': 0.001, 'epochs': 50}
with open('[Link]', 'w') as f:
[Link](config, f, indent=2)
with open('[Link]') as f:
loaded = [Link](f)
try:
model = load_model('[Link]')
preds = [Link](X_test)
except FileNotFoundError:
print('Model missing — train first!')
except ValueError as e:
print(f'Shape error: {e}')
except Exception as e:
print(f'Unexpected: {e}')
raise # re-raise for debugging
finally:
print('Pipeline step done.')
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Write a program that reads a text file and prints: total lines, total words, and total characters.
Easy 2. Create a JSON config file for a neural network (layers, lr, epochs, optimizer). Write a function
load_config(path) that loads and returns it, with a default if file not found.
Mediu 3. Write a CSV logger class that appends a row (timestamp, metric_name, value) to a CSV file on each
m
call to log(name, value). Include a read_all() method that returns all logged rows.
Mediu 4. Write a safe_divide(a, b) function that raises a custom exception DivisionByZeroError with a helpful
m
message when b is 0.
Hard 5. Build a simple data pipeline: read a CSV of numbers, clean it (skip non-numeric rows, log errors),
compute statistics (mean, std, min, max), and write results to a JSON report file.
Object-Oriented Programming organises code into reusable classes. All PyTorch models ([Link]), scikit-learn
estimators, and pandas DataFrames are classes. Understanding OOP lets you extend and build ML components
from scratch.
class NeuralNetwork:
framework = 'PyTorch' # class attribute
def _compute_loss(self):
return 1.0 / (len([Link]) + 1)
def __repr__(self):
return f'NN(layers={[Link]})'
class CNN(NeuralNetwork):
def __init__(self, layers, filters, lr=0.001):
super().__init__(layers, lr)
[Link] = filters
class Dataset:
def __init__(self, X, y):
self.X = X
self.y = y
@property
def n_features(self): return [Link][1]
ds = Dataset(X, y)
print(len(ds)) # 1000
print(ds.n_features) # 20
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Create a BankAccount class with attributes owner and balance. Add methods deposit(amount),
withdraw(amount) (raise error if insufficient funds), and __str__.
Easy 2. Create a Rectangle class with width and height. Add methods area(), perimeter(), and is_square().
Override __eq__ to compare two rectangles by area.
Mediu 3. Create a Stack class using a list internally. Implement push(item), pop(), peek(), is_empty(), and
m
__len__. Raise StackEmptyError on pop/peek when empty.
Mediu 4. Build a Student class and a Classroom class. Classroom has a list of Students and methods:
m
add_student(), remove_student(), class_average(), and top_n(n) returning top n students by grade.
Hard 5. Implement a SimpleLinearRegression class with fit(X, y), predict(X), and score(X, y) methods using
only pure Python (no numpy). Store coefficients as attributes.
NumPy is the computational backbone of Python data science. It provides n-dimensional arrays with C-speed
operations. Pandas, scikit-learn, PyTorch, and TensorFlow all use NumPy arrays internally.
import numpy as np
a = [Link]([1, 2, 3, 4, 5])
b = [Link]((3, 4)) # 3x4 zeros
c = [Link]((2, 2))
d = [Link](3) # identity matrix
e = [Link](100, 10) # standard normal
f = [Link](0, 10, 0.5) # 0 to 9.5, step 0.5
g = [Link](0, 1, 50) # 50 evenly spaced
X = [Link](1000, 20)
X[0] # first row
X[:, 5] # column 5 all rows
X[10:20, :5] # rows 10-19, cols 0-4
# Boolean masking
scores = [Link]([0.9, 0.4, 0.8, 0.2, 0.7])
mask = scores > 0.5
high = scores[mask] # [0.9, 0.8, 0.7]
idx = [Link](mask)[0] # [0, 2, 4]
X = [Link](1000, 10)
mean = [Link](axis=0) # shape (10,)
std = [Link](axis=0) # shape (10,)
X_norm = (X - mean) / std # broadcasts!
# Linear algebra
A = [Link](3, 3)
b = [Link]([1.0, 2.0, 3.0])
x = [Link](A, b) # Ax = b
evals, evecs = [Link](A)
U, S, Vt = [Link](A) # SVD
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Create a 5x5 matrix where the diagonal is 1,2,3,4,5 and all other elements are 0. Print it. Then
compute row sums and column sums.
Easy 2. Given an array of 100 random numbers from N(0,1), count how many are > 1.96, compute mean/std,
and replace all values < -2 with exactly -2.
Mediu 3. Implement Z-score normalisation from scratch using NumPy: write normalize(X) that standardises
m
each column to mean=0, std=1. Verify on a 100x5 random matrix.
Mediu 4. Implement matrix multiplication manually using [Link]. Then implement softmax(x) =
m
exp(x)/sum(exp(x)) and verify it sums to 1.0 for any input vector.
Hard 5. Implement linear regression using only NumPy: solve the normal equation W = (X^T X)^{-1} X^T y.
Test on synthetic data y = 3x + 2 + noise and report the learned coefficients.
Pandas is the primary tool for data manipulation in Python. It provides the DataFrame — a 2D table with labelled
axes. 80% of a data scientist's time is spent cleaning and exploring data with Pandas.
import pandas as pd
df = pd.read_csv('[Link]')
[Link]() # first 5 rows
[Link]() # dtypes + null counts
[Link]() # stats summary
[Link] # (891, 12)
[Link]() # all column names
[Link]().sum() # nulls per column
df['Age'].value_counts().head(10)
# Selection
df['Age'] # Series
df[['Age', 'Survived']] # DataFrame
[Link][df['Age'] > 30, ['Name']] # conditional
[Link][10:20, 0:4] # positional
# Cleaning
df['Age'].fillna(df['Age'].median(), inplace=True)
[Link](subset=['Embarked'], inplace=True)
df.drop_duplicates(inplace=True)
df['Age'] = df['Age'].astype(int)
# GroupBy
survival = ([Link]('Pclass')['Survived']
.agg(['mean','count']).round(2))
# Feature Engineering
df['FamilySize'] = df['SibSp'] + df['Parch'] + 1
df['IsAlone'] = (df['FamilySize'] == 1).astype(int)
df['AgeBin'] = [Link](df['Age'],
bins=[0,18,35,60,100],
labels=['youth','adult','mid','senior'])
df['Title'] = df['Name'].[Link](r', ([A-Za-z]+)\.')
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Load the Titanic CSV. Find: (a) survival rate by gender, (b) average age by passenger class, (c)
percentage of missing values in each column.
Easy 2. Create a DataFrame of 5 employees with columns: name, department, salary, years. Filter to
employees with salary > 60000 or years > 5.
Mediu 3. Given a DataFrame with sales data (date, product, quantity, price), compute: daily revenue, top 5
m
products by total revenue, and month-over-month growth rate.
Mediu 4. Clean a messy dataset: handle missing values intelligently (median for numeric, mode for categorical),
m
remove duplicate rows, fix inconsistent string casing, and report what was changed.
Hard 5. Perform a full EDA on the Titanic dataset: survival rates by all categorical variables, age distribution by
survival, correlation matrix, and create at least 3 new meaningful features.
Visualization is how you communicate insights from data. Without EDA plots, you are modelling blind. Matplotlib
provides full control; Seaborn provides statistical beauty with minimal code.
# Training curve
axes[0].plot(train_loss, label='Train', color='#2563EB', lw=2)
axes[0].plot(val_loss, label='Val', color='#DC2626', ls='--')
axes[0].set(title='Loss Curve', xlabel='Epoch', ylabel='Loss')
axes[0].legend()
axes[0].grid(alpha=0.3)
# Histogram
axes[1].hist(data, bins=30, color='#16A34A', edgecolor='white')
plt.tight_layout()
[Link]('[Link]', dpi=150, bbox_inches='tight')
# Correlation heatmap
[Link](figsize=(10, 8))
[Link]([Link](), annot=True, fmt='.2f',
cmap='coolwarm', center=0, square=True)
# Distribution by class
[Link](data=df, x='Age', hue='Survived', kde=True)
# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
[Link](cm, annot=True, fmt='d', cmap='Blues',
xticklabels=['No','Yes'],
yticklabels=['No','Yes'])
[Link]('Predicted'); [Link]('Actual')
# Feature importance
feat_df = [Link]({'feature': names,
'importance': importances})
feat_df.sort_values('importance').[Link](x='feature')
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Plot the sine and cosine functions from 0 to 4*pi on the same figure with different colors and a legend.
Add gridlines and a title.
Easy 2. Create a 2x2 subplot grid showing: histogram, box plot, scatter plot, and bar chart — all from the same
dataset of your choice.
Mediu 3. Load the Titanic dataset. Create a figure with 4 subplots: (a) survival count bar chart, (b) age
m
distribution by survival (overlapping histograms), (c) fare distribution by class (box), (d) correlation
heatmap.
Mediu 4. Plot training and validation loss curves for a hypothetical model over 50 epochs (simulate with random
m
data trending down). Mark the point of best validation loss with a vertical dashed line.
Hard 5. Create a complete EDA dashboard for any dataset: at least 6 different plot types, consistent color
scheme, proper labels on everything, saved as a high-res PNG. Write a caption for each plot.
Scikit-learn is the most widely used ML library in Python. Its consistent fit/transform/predict API means you can
swap any algorithm with one line of code. Mastering this API is essential for every ML practitioner.
scaler = StandardScaler()
X_tr_s = scaler.fit_transform(X_tr) # fit + transform
X_te_s = [Link](X_te) # transform only!
model = RandomForestClassifier(n_estimators=100)
[Link](X_tr_s, y_tr)
print(classification_report(y_te, [Link](X_te_s)))
pipe = Pipeline([
('scaler', StandardScaler()),
('clf', RandomForestClassifier(100))
])
[Link](X_tr, y_tr)
print([Link](X_te, y_te))
models = {
'LR': LogisticRegression(max_iter=1000),
'DT': DecisionTreeClassifier(max_depth=5),
'RF': RandomForestClassifier(100)
}
for name, m in [Link]():
[Link](X_tr_s, y_tr)
auc = roc_auc_score(y_te,
m.predict_proba(X_te_s)[:,1])
print(f'{name}: AUC={auc:.3f}')
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Load the sklearn iris dataset. Train a LogisticRegression. Print accuracy, classification report, and
confusion matrix. Visualise the confusion matrix.
Easy 2. Compare DecisionTree depths 1, 3, 5, 10, None on the breast cancer dataset. Plot train vs test
accuracy for each depth.
Mediu 3. Build a full sklearn Pipeline for the Titanic dataset: impute missing values, encode categoricals, scale
m
numerics, then train RandomForest. Evaluate with 5-fold cross-validation.
Mediu 4. Demonstrate data leakage: show that fitting the scaler on ALL data before splitting gives artificially
m
better results vs the correct approach. Use a real dataset.
Hard 5. Implement a model comparison framework that trains 5 different sklearn algorithms, evaluates each
with 5-fold CV, plots a boxplot of CV scores, and prints a summary table with mean +/- std.
Getting from 'good model' to 'best model' requires systematic hyperparameter tuning and proper evaluation.
XGBoost is the industry standard for tabular data. Model explainability is increasingly required in production.
param_grid = {
'n_estimators': [100, 200, 300],
'max_depth': [3, 5, 7, None],
'min_samples_split': [2, 5, 10]
}
gs = GridSearchCV(RandomForestClassifier(42),
param_grid, cv=5,
scoring='roc_auc', n_jobs=-1)
[Link](X_tr, y_tr)
print(gs.best_params_)
print(f'Best AUC: {gs.best_score_:.4f}')
model = [Link](
n_estimators=500, learning_rate=0.05,
max_depth=5, subsample=0.8,
colsample_bytree=0.8,
early_stopping_rounds=20,
eval_metric='auc',
random_state=42, use_label_encoder=False)
[Link](X_tr, y_tr,
eval_set=[(X_te, y_te)], verbose=50)
print(f'Best iter: {model.best_iteration}')
import shap
explainer = [Link](model)
shap_vals = explainer.shap_values(X_te)
# Global importance
shap.summary_plot(shap_vals, X_te,
feature_names=feature_names)
# Single prediction
shap.force_plot(explainer.expected_value,
shap_vals[0], X_te[0],
feature_names=feature_names)
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 2. Plot a learning curve (training size vs. train/val score) for a RandomForest. Identify whether the model
is high-bias or high-variance.
Mediu 3. Train an XGBoost model on the Titanic dataset with early stopping. Plot the training/validation AUC
m
curves by number of trees. Report the optimal number of trees.
Mediu 4. Compare Logistic Regression, Random Forest, and XGBoost using the same 5-fold CV splits. Create
m
a bar chart of mean AUC with error bars showing std.
Hard 5. Build a full AutoML-lite: for a given dataset, automatically try 5 algorithms, tune each with
RandomizedSearchCV, ensemble the top 3 with a VotingClassifier, and report a comprehensive
evaluation.
PyTorch is the dominant deep learning framework in research and increasingly in production. Every modern LLM
(GPT, BERT, LLaMA) is built with PyTorch. Understanding tensors and autograd is the foundation.
import torch
# Autograd
w = [Link](784, 10, requires_grad=True)
loss = (x @ w).pow(2).mean()
[Link]() # compute gradients
print([Link]) # (784, 10)
# NumPy interop
arr = [Link]().detach().numpy()
import [Link] as nn
class MLP([Link]):
def __init__(self, in_dim, hid, out_dim, p=0.3):
super().__init__()
[Link] = [Link](
[Link](in_dim, hid),
nn.BatchNorm1d(hid),
[Link](),
[Link](p),
[Link](hid, out_dim))
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Create a 3-layer MLP in PyTorch for binary classification (input=10, hidden=64, output=1 with
sigmoid). Print the model architecture and total number of trainable parameters.
Easy 2. Implement the ReLU, Sigmoid, and Tanh activation functions manually using PyTorch tensors. Plot all
three on the range [-5, 5].
Mediu 3. Train a PyTorch MLP on the sklearn digits dataset (64 features, 10 classes). Track train/val loss each
m
epoch. Plot the curves. Achieve at least 95% test accuracy.
Mediu 4. Implement a training loop with early stopping: stop training if validation loss does not improve for 10
m
consecutive epochs. Save the best model checkpoint.
Hard 5. Build a CNN for MNIST classification: 2 conv layers + 2 FC layers. Train for 10 epochs, achieve > 99%
test accuracy, and visualise 10 misclassified examples.
Natural Language Processing has been revolutionised by Transformer models. HuggingFace provides pre-trained
models for hundreds of NLP tasks. You can fine-tune state-of-the-art LLMs with a few lines of Python.
import re
from sklearn.feature_extraction.text import TfidfVectorizer
def clean(text):
text = [Link]()
text = [Link](r'<.*?>', '', text) # strip HTML
text = [Link](r'[^a-z0-9\s]', '', text)
return [Link](r'\s+', ' ', text).strip()
vectorizer = TfidfVectorizer(max_features=10000,
ngram_range=(1, 2))
X = vectorizer.fit_transform(texts)
print([Link]) # (n_docs, 10000)
# Sentiment Analysis
clf = pipeline('sentiment-analysis')
print(clf('I love deep learning!'))
# [{'label': 'POSITIVE', 'score': 0.9998}]
# Summarisation
summ = pipeline('summarization')
summ(long_text, max_length=60)
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
model = AutoModelForSequenceClassification.from_pretrained(
'bert-base-uncased', num_labels=2)
args = TrainingArguments(
output_dir='./out', num_train_epochs=3,
per_device_train_batch_size=16,
evaluation_strategy='epoch')
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Use HuggingFace pipeline to analyse sentiment of 10 movie reviews. Plot a bar chart showing count
of POSITIVE vs NEGATIVE predictions.
Easy 2. Use zero-shot classification to categorise 20 news headlines into 5 categories without any training.
Print each headline with its predicted category and confidence score.
Mediu 3. Build a text classification pipeline: clean text -> TF-IDF features -> Logistic Regression. Train on the
m
20 newsgroups dataset. Report accuracy and plot a confusion matrix.
Mediu 4. Use HuggingFace to: (a) summarise a long article, (b) answer 3 questions about it using QA pipeline,
m
(c) extract named entities. Use any real article.
Hard 5. Fine-tune a small BERT model (distilbert-base-uncased) on the IMDb sentiment dataset for 2 epochs.
Report train/val loss curves and final accuracy. Compare to TF-IDF + LR baseline.
MLOps bridges the gap between a working notebook and a production system. Without proper experiment
tracking, model versioning, and deployment skills, your models stay in Jupyter forever.
# Recommended structure
my_project/
data/raw/ # NEVER modify raw data
data/processed/
notebooks/ # EDA only
src/
[Link] # data loading
[Link] # feature engineering
[Link] # model definition
[Link] # training script
models/ # saved artifacts
[Link]
[Link]
import mlflow
import [Link]
mlflow.set_experiment('titanic-v1')
with mlflow.start_run(run_name='rf_tuned'):
mlflow.log_params({'n_est': 200, 'depth': 5})
[Link](X_tr, y_tr)
auc = roc_auc_score(y_te,
model.predict_proba(X_te)[:,1])
mlflow.log_metric('auc', auc)
[Link].log_model(model, 'model')
# [Link]
import streamlit as st
import joblib, numpy as np
[Link]('ML Predictor')
model = [Link]('[Link]')
if [Link]('Predict'):
X = [Link]([[age, income]])
pred = [Link](X)[0]
prob = model.predict_proba(X)[0][1]
[Link](f'Result: {pred} ({prob:.1%})')
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Easy 1. Set up an MLflow experiment for any classification task. Log at least 3 different parameter sets, their
metrics, and the best model. Open the MLflow UI and take a screenshot.
Easy 2. Write a Python logging setup (using the logging module) that logs INFO/WARNING/ERROR
messages both to console and to a rotating file. Test it in a simple ML pipeline.
Mediu 3. Build a Streamlit app that: (a) accepts CSV file upload, (b) shows basic stats and plots, (c) lets user
m
choose a model (LR, RF, XGBoost), (d) shows predictions and evaluation metrics.
Mediu 4. Refactor a Jupyter notebook into a proper src/ package structure with separate data loading, feature
m
engineering, training, and evaluation modules. Add a main [Link] script.
Hard 5. Create a full ML pipeline with: MLflow tracking, model registry, a REST API (using FastAPI or Flask)
that serves predictions, and a Streamlit frontend. Deploy locally and test end-to-end.
Congratulations on completing 14 days of intensive Python for DS/AI! Today we consolidate everything into a
complete production-grade pipeline and chart your path forward.
log = [Link](__name__)
[Link](level=[Link])
df = pd.read_csv('data/raw/[Link]')
[Link](f'Loaded {len(df)} rows')
X, y = [Link]('target',axis=1).values, df['target'].values
X_tr,X_te,y_tr,y_te = train_test_split(
X,y,test_size=0.2,stratify=y,random_state=42)
pipe = Pipeline([('sc',StandardScaler()),
('clf',GradientBoostingClassifier())])
gs = GridSearchCV(pipe,
{'clf__n_estimators':[100,200],'clf__lr':[0.05,0.1]},
cv=5, scoring='roc_auc', n_jobs=-1)
[Link](X_tr, y_tr)
[Link](f'Best AUC: {gs.best_score_:.4f}')
[Link](gs.best_estimator_, 'models/[Link]')
# Track 2: ML Engineer
# XGBoost deep dive -> Feature Stores -> Docker -> AWS
DS/ML Relevance: These skills are used directly in production data pipelines, model training scripts, and ML
engineering roles.
Practice Problems
Mediu 2. Build a complete end-to-end project on the House Prices dataset: EDA + feature engineering +
m
stacked model + submission. Write a README explaining every decision.
Mediu 3. Build and deploy a Streamlit ML app on any dataset. Push to GitHub and deploy on Streamlit
m
Community Cloud. Share the public URL.
Hard 4. Create a portfolio project combining everything: scrape or download a real dataset, perform full EDA,
engineer features, train and tune multiple models, track experiments with MLflow, serve predictions with
FastAPI, and build a Streamlit frontend.
Hard 5. CAPSTONE: Pick any Kaggle competition, build your best model, write a 500-word technical blog post
explaining your approach, and publish it on Medium or a personal site.