Download machine learning short notes and more Schemes and Mind Maps Machine Learning in PDF only on Docsity!
MACHINE LEARNING
Detailed Study Guide with Python & Scikit-learn Practical
Concepts • Simple Hinglish intuition • Code • Evaluation • Projects
Learning purpose:
This guide is designed for learning Machine Learning as part of a longer AI/ML → Deep Learning → GenAI/LLM learning
path, not for BCA exam preparation only.
How to study each topic
1. Understand the concept and why it is used.
2. Read the simple explanation and real-world example.
3. Run the code in Jupyter Notebook or VS Code.
4. Change a value, inspect the output, and explain what changed.
5. Evaluate the model instead of trusting a single prediction.
Code examples use common Python libraries. Install them if needed: pip install pandas numpy matplotlib seaborn
scikit-learn
Learning Map
This guide expands the core topics in the earlier notes and adds practical implementation patterns. It covers supervised
learning, unsupervised learning, model evaluation and sound ML workflow. Reinforcement Learning and deep learning are
introduced conceptually only; they are separate study blocks.
Stage What you should learn Practical outcome
1. Foundations ML definition, types, workflow, X/y, splits Understand the end-to-end process
2. Data preparation Missing values, encoding, scaling, leakage Prepare reliable model inputs
3. Supervised ML Regression, classification, model families Train prediction models
4. Unsupervised ML Clustering, K-Means, silhouette, PCA Find structure without target labels
5. Evaluation Metrics, cross-validation, tuning Compare models fairly
6. Mini-project Customer churn / sales / segmentation Create a reproducible ML notebook
Recommended order: do not jump directly into algorithms. First understand what problem you are solving, what the
target is, and what a fair evaluation looks like.
1. What is Machine Learning?
Theory
Machine Learning (ML) is a part of Artificial Intelligence in which a computer system learns patterns from examples or data
and uses those patterns to make predictions, classifications or decisions. Instead of writing a separate rule for every possible
case, we train a model on representative examples.
Simple Hinglish
Normal programming mein hum rules likhte hain. ML mein hum examples/data dete hain, algorithm patterns learn karta hai,
aur trained model naye data par prediction karta hai.
Example
A retailer has past customer records. The model may learn patterns associated with customers who stop buying. It can then
estimate churn risk for current customers. This is a prediction, not a guarantee or proof that a particular customer will leave.
Important vocabulary
Term Meaning
Data / dataset Examples or records used for analysis and learning.
Feature (X) An input column the model uses, such as age, income or order count.
Target / label (y) The answer the model is learning to predict, such as churn or price.
Algorithm The learning procedure, such as Linear Regression or Decision Tree.
Model The fitted result that can produce predictions.
Training The process of fitting the model to training examples.
Inference Using a trained model to make predictions on new inputs.
Generalization How well the model works on data not used to fit it.
Interview answer
Machine Learning is a subset of AI that learns patterns from data to make predictions or decisions. It is useful when
manually writing all rules is difficult, such as fraud detection, recommendations and forecasting.
Data leakage
Leakage occurs when the model gets access to information it would not truly have at prediction time, or when test-set
information influences training. For example, using a 'cancellation_date' column to predict cancellation before the
cancellation happens can leak the answer.
Rule: split first. Fit imputation, scaling, encoding and feature-selection steps using training data only. Scikit-learn
pipelines help enforce this.
4. X, y and Train/Test/Validation
In scikit-learn, X usually means feature columns and y means the target. For a churn task, X may contain tenure, monthly
charges and contract type; y contains whether the customer churned.
Example: split features from the target
X = df.drop(columns=["Churn"]) y = df["Churn"]
Training set: used to fit model parameters. Validation set / cross-validation: used to compare models and tune
hyperparameters. Test set: held back for a final, less biased evaluation.
Subset Purpose Use it for tuning?
Training Fit model parameters Yes, it is used during fitting
Validation / CV Choose model or settings Yes
Test Final estimate of generalization No; keep it untouched until final evaluation
Basic split code
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20, random_state= )
test_size=0.20 means 20% is reserved for testing. random_state=42 makes the random split reproducible; 42 has no special
ML meaning. For classification, consider stratify=y to preserve class proportions. For time series, use a chronological split
instead of random shuffling.
Check the split
print(X_train.shape, X_test.shape) print(y_train.shape, y_test.shape)
The number of rows in X_train must match y_train, and the number of rows in X_test must match y_test.
5. Data Preprocessing and Pipelines
Real-world data is often incomplete, inconsistent or stored as text. Preprocessing converts it into a form that the chosen
algorithm can use.
Common operations
- Missing values: investigate why they are missing; impute or remove only with a reason.
- Categorical encoding: convert categories such as Contract Type into numeric columns.
- Scaling: make feature ranges comparable for algorithms sensitive to distances or coefficient size.
- Outlier handling: inspect extreme values; they can be errors or genuine high-value cases.
- Feature engineering: create useful inputs from existing columns, using only information available at prediction time.
Why use a pipeline?
A Pipeline bundles preprocessing and the model so that the same transformations are learned from training data and then
applied to validation, test and future data. This reduces leakage and inconsistent processing.
import pandas as pd
from sklearn.model_selection import train_test_split from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression
df is your cleaned dataset; target column is "Churn"
X = df.drop(columns=["Churn"]) y = df["Churn"]
num_cols = X.select_dtypes(include="number").columns cat_cols = X.select_dtypes(exclude="number").columns
num_pipe = Pipeline([ ("imputer", SimpleImputer(strategy="median")), ("scaler", StandardScaler()) ]) cat_pipe = Pipeline([ ("imputer", SimpleImputer(strategy="most_frequent")), ("encoder", OneHotEncoder(handle_unknown="ignore")) ])
prep = ColumnTransformer([ ("num", num_pipe, num_cols), ("cat", cat_pipe, cat_cols) ])
model = Pipeline([ ("prep", prep), ("classifier", LogisticRegression(max_iter=1000)) ])
This is a reusable pattern, not a dataset-specific finished project. Confirm that your target labels and column types are
correct before running it.
6. Regression: Linear, Ridge, Lasso and Elastic Net
What regression solves
Regression predicts a numerical target. Examples: sales amount, delivery duration, energy consumption and property price.
Simple Linear Regression intuition
It fits a straight-line relationship between one input x and target y: y = mx + c. Here m is the slope and c is the intercept. The
model estimates the line from training data; it does not prove that x causes y.
Hinglish: model aisi line choose karta hai jo training points ke predictions aur actual values ke beech ke errors ko overall kam
kare.
Practical: Linear Regression
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score import numpy as np
Replace "Sales" and feature names with your real columns
X = df[["AdvertisingSpend", "Discount"]] y = df["Sales"]
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state= )
model = LinearRegression() model.fit(X_train, y_train) # learn from training data pred = model.predict(X_test) # predict unseen test rows
print("MAE:", mean_absolute_error(y_test, pred)) print("RMSE:", np.sqrt(mean_squared_error(y_test, pred))) print("R2:", r2_score(y_test, pred))
Column names above are examples. Replace them with columns in your dataset. MAE/RMSE are in the target's units; R²
compares the model with a mean-prediction baseline and may be negative on test data.
Use text variables such as train_messages/test_messages here; this snippet is a text-classification pattern. MultinomialNB
commonly uses non-negative count-like features.
K-Nearest Neighbours (KNN)
KNN predicts from the nearest training examples under a distance measure. For classification it votes among neighbours; for
regression it often averages their target values. It is called a lazy learner because much of the work happens when
predictions are requested.
from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score
knn = make_pipeline( StandardScaler(), KNeighborsClassifier(n_neighbors=5) ) knn.fit(X_train, y_train) pred = knn.predict(X_test) print("Accuracy:", accuracy_score(y_test, pred))
- A very small k can react strongly to noise.
- A very large k can smooth away meaningful local patterns.
- Scaling usually matters because distance is affected by units.
- KNN can become slow when prediction requires searching many training rows. 9. Support Vector Machines: SVC and SVR
Support Vector Machines find a boundary or function that balances fit with a margin-based objective. SVC is used for
classification; SVR is used for regression. Kernel functions allow certain non-linear patterns to be modelled.
Practical SVC
from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC from sklearn.metrics import classification_report
svc = make_pipeline( StandardScaler(), SVC(kernel="rbf", C=1.0) ) svc.fit(X_train, y_train) pred = svc.predict(X_test) print(classification_report(y_test, pred))
C controls the trade-off between margin size and training errors. The RBF kernel can model non-linear boundaries. SVMs
often need feature scaling, and tuning C/gamma/kernel can materially affect performance.
SVR
from sklearn.svm import SVR from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler
svr = make_pipeline(StandardScaler(), SVR(kernel="rbf", C=10)) svr.fit(X_train, y_train) # y_train must be numerical pred_values = svr.predict(X_test)
10. Decision Trees and Pruning
A Decision Tree makes a prediction by asking a sequence of feature-based questions. Each split divides records into groups;
a leaf gives the final class or numerical prediction.
Term Meaning
Root First split in the tree
Internal node A later question/split
Branch Outcome of a split
Term Meaning
Leaf Final prediction
Gini / entropy Common classification split criteria
Squared error A common regression split criterion
Practical classification tree
from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import classification_report
tree = DecisionTreeClassifier( max_depth=5, min_samples_leaf=10, random_state= ) tree.fit(X_train, y_train) pred = tree.predict(X_test) print(classification_report(y_test, pred))
max_depth and min_samples_leaf limit complexity. Pre-pruning sets limits while the tree is being built. Post-pruning grows a
larger tree and then removes branches that do not help enough.
Regression tree
from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_absolute_error
tree_reg = DecisionTreeRegressor(max_depth=5, random_state=42) tree_reg.fit(X_train, y_train) # numerical y pred = tree_reg.predict(X_test) print("MAE:", mean_absolute_error(y_test, pred))
Trees can model non-linear patterns and are relatively easy to explain, but deep trees may overfit and can be unstable
when the data changes.
11. Random Forest, Bagging and Boosting
Ensemble learning combines multiple models. It often improves stability or predictive performance, but does not guarantee a
better result on every dataset.
Random Forest
Random Forest trains many decision trees with randomness in row sampling and feature selection. Classification combines
tree votes; regression usually averages tree outputs. This often reduces the variance of a single decision tree.
from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report
rf = RandomForestClassifier( n_estimators=200, max_depth=None, min_samples_leaf=2, random_state=42, n_jobs=- ) rf.fit(X_train, y_train) pred = rf.predict(X_test) print(classification_report(y_test, pred))
Bagging vs Boosting
Bagging Boosting
Models often train independently on resampled data. Models are built stage-by-stage; later stages focus on earlier
errors or residuals.
Often reduces variance. Can reduce bias and improve fit, but requires careful tuning.
Example: Random Forest. Examples: AdaBoost, Gradient Boosting, XGBoost.
Random Forest hyperparameters include n_estimators (number of trees), max_depth and min_samples_leaf. More trees can
stabilize predictions but increase compute time. Feature importance is a useful clue, not proof of causation.
from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA
X_num is a numeric feature matrix with missing values handled
X_scaled = StandardScaler().fit_transform(X_num)
pca = PCA(n_components=2) X_2d = pca.fit_transform(X_scaled)
print("Explained variance ratio:", pca.explained_variance_ratio_) print("Total for two components:", pca.explained_variance_ratio_.sum())
For a real evaluation workflow, fit the scaler and PCA on training data only, then transform validation/test data using
those fitted objects. Do not fit PCA on the full dataset before the split if the goal is an unbiased test evaluation.
14. Overfitting, Underfitting, Bias, Variance and Regularization
Concept Meaning Common clue
Underfitting Model is too simple to learn the useful pattern. Poor performance on training and test data.
Overfitting Model learns training noise/details too closely. Excellent training score but weaker test score.
Bias Error associated with restrictive assumptions. Often linked with underfitting.
Variance Sensitivity to the particular training sample. Often linked with complex models.
Ways to reduce overfitting
- Use representative data and fix data-quality problems.
- Limit tree depth or increase minimum leaf size.
- Use regularization for models that support it.
- Select features based on training data and domain reasoning.
- Use cross-validation to compare settings.
- Check for leakage and avoid tuning repeatedly on the final test set.
Goal: good generalization on new examples, not a perfect score on training data.
15. Model Evaluation: Regression Metrics
The metric must match the problem. For regression, compare predicted numerical values with actual values.
Metric Meaning Interpretation
MAE Average absolute error. Lower is better; same units as target.
MSE Average squared error. Lower is better; large errors receive stronger
penalty.
RMSE Square root of MSE. Lower is better; same units as target.
R² Fit relative to a mean-prediction baseline. Often higher is better; can be negative on test data.
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score import numpy as np
mae = mean_absolute_error(y_test, pred) rmse = np.sqrt(mean_squared_error(y_test, pred)) r2 = r2_score(y_test, pred)
print("MAE:", mae) print("RMSE:", rmse) print("R2:", r2)
Adjusted R² accounts for the number of predictors in a linear-model context; it may be useful when comparing models with
different numbers of features. Do not use it as a universal score for every ML algorithm.
Residual check
residuals = y_test - pred print(residuals.describe())
Residuals are actual minus predicted values. Look for systematic patterns or very large errors; a single summary score can
hide problems in particular segments.
16. Model Evaluation: Classification Metrics
A confusion matrix compares actual and predicted classes. For binary classification, TP = true positive, TN = true negative,
FP = false positive, FN = false negative.
Metric Formula Question answered
Accuracy (TP + TN) / total What fraction of all predictions was correct?
Precision TP / (TP + FP) Among predicted positives, how many were truly positive?
Recall TP / (TP + FN) Among actual positives, how many did we find?
F1-score 2 × Precision × Recall / (Precision +
Recall)
How do precision and recall balance?
Example: in fraud detection, false negatives mean fraud was missed; false positives mean legitimate transactions were
flagged. High recall helps catch more fraud; high precision reduces false alarms. The right trade-off depends on business
costs.
from sklearn.metrics import confusion_matrix, classification_report
print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred, zero_division=0))
For imbalanced classes, inspect precision, recall, F1, class counts and possibly PR-AUC/ROC-AUC where appropriate.
A high accuracy score alone can be misleading.
17. Cross-Validation and Hyperparameter Tuning
Cross-validation estimates how results vary across multiple train/validation splits. In k-fold CV, the training data is divided
into k folds; each fold is used for validation once while the others are used for fitting.
Parameters are learned from data during fit. Hyperparameters are choices that control the learning process, such as tree
depth, number of neighbours or regularization strength.
from sklearn.model_selection import GridSearchCV from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import StratifiedKFold
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) search = GridSearchCV( DecisionTreeClassifier(random_state=42), param_grid={ "max_depth": [3, 5, 8, None], "min_samples_leaf": [1, 5, 10] }, scoring="f1_weighted", cv=cv, n_jobs=- ) search.fit(X_train, y_train)
print("Best settings:", search.best_params_) print("Best CV score:", search.best_score_) best_model = search.best_estimator_ test_predictions = best_model.predict(X_test)
The test set must remain separate during the search. Choose scoring that matches the task and class balance. For
time-series data, use time-aware validation instead of randomly mixing past and future.
Grid search vs random search
Grid search Random search
Checks every specified combination. Samples combinations from a search space.
Can be expensive when many settings exist. Often explores broad spaces more efficiently.
Starter template
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion_matrix
1. Load your dataset
df = pd.read_csv("customer_churn.csv")
2. Inspect before modelling
print(df.shape) print(df.head()) print(df.isna().sum()) print(df["Churn"].value_counts(dropna=False))
3. Separate inputs and target
X = df.drop(columns=["Churn"]) y = df["Churn"]
4. Split before fitting preprocessing
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y )
5. Select numeric/categorical columns
num_cols = X_train.select_dtypes(include="number").columns cat_cols = X_train.select_dtypes(exclude="number").columns
numeric = Pipeline([ ("imputer", SimpleImputer(strategy="median")), ("scale", StandardScaler()) ]) categorical = Pipeline([ ("imputer", SimpleImputer(strategy="most_frequent")), ("onehot", OneHotEncoder(handle_unknown="ignore")) ]) preprocess = ColumnTransformer([ ("num", numeric, num_cols), ("cat", categorical, cat_cols) ])
6. Fit model
model = Pipeline([ ("preprocess", preprocess), ("classifier", LogisticRegression(max_iter=1000)) ]) model.fit(X_train, y_train)
7. Evaluate once on test data
pred = model.predict(X_test) print(confusion_matrix(y_test, pred)) print(classification_report(y_test, pred, zero_division=0))
Before running, make sure your target is actually named Churn and that the target values are suitable labels. If the
dataset has customer IDs, dates or columns recorded after churn, assess whether they should be excluded. Do not
blindly remove columns without understanding them.
20. Mini-Project: Customer Segmentation with K-Means
Goal: find customer groups from behaviour features such as order frequency and total spending, then describe the groups
using their actual profiles.
import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score
df = pd.read_csv("customers.csv") features = df[["Total_Orders", "Total_Spent"]].copy() features = features.dropna()
scaler = StandardScaler() scaled = scaler.fit_transform(features)
scores = {}
for k in range(2, 8): km = KMeans(n_clusters=k, random_state=42, n_init=10) labels = km.fit_predict(scaled) scores[k] = silhouette_score(scaled, labels)
print(scores)
chosen_k = max(scores, key=scores.get) # inspect scores, don't blindly trust this km = KMeans(n_clusters=chosen_k, random_state=42, n_init=10) labels = km.fit_predict(scaled)
result = features.copy() result["Cluster"] = labels print(result.groupby("Cluster").agg( customers=("Cluster", "size"), avg_orders=("Total_Orders", "mean"), avg_spend=("Total_Spent", "mean") ))
The highest silhouette score is one clue, not an automatic business decision. Inspect group sizes, stability and whether the
segments can support a useful action. Cluster numbers such as 0, 1 and 2 have no inherent rank or meaning.
21. Common Errors and Debugging Checklist
- ValueError: could not convert string to float: a categorical/text column may need encoding or a text-specific
representation.
- Input contains NaN: choose a missing-value strategy or an algorithm that supports missing values, then validate the
choice.
- Feature names mismatch: use the same columns and order for training and prediction; a Pipeline helps.
- Perfectly high score: check target leakage, duplicates across train/test, and whether the split matches real use.
- Low recall: inspect class imbalance, threshold, feature quality and false negatives.
- K-Means clusters look odd: check scaling, outliers, feature relevance, K choice and whether the data supports cluster
structure.
- Model works in notebook but not later: save the full preprocessing + model pipeline and preserve feature definitions.
A simple habit
For every experiment, record: business question, dataset version, features, split method, model settings, metric, result and
next change. This makes learning systematic rather than trial-and-error.
22. Interview Questions and Self-Check
Short interview answers
What is the difference between AI and ML? AI is the broader field of building systems that perform intelligent tasks; ML is
one approach in AI that learns patterns from data.
Why split data? To estimate how well a model generalizes to records it did not fit on.
Why use a Pipeline? To apply preprocessing consistently and help prevent leakage by fitting transformations within the
training process.
Why is accuracy sometimes misleading? With imbalanced classes, predicting the majority class can produce high
accuracy while missing the class we care about.
What is overfitting? When a model fits training details/noise too closely and performs worse on unseen data.
What is the difference between a parameter and a hyperparameter? A parameter is learned during fitting; a
hyperparameter controls how learning is carried out.
What does a silhouette score tell us? It estimates how similar a record is to its own cluster compared with other clusters; it
is one diagnostic, not proof of useful segments.
Self-check questions
1. A model predicts monthly revenue. Is this regression or classification, and why?