⚡ TechVani: AI, Technology, Apps, Coding & Digital World
TechVaniAI • Technology • Apps • Coding • Digital World
HomeAI & TechAppsCodingFree AI ToolsStudent TechSecurityAboutContactPrivacy
TECHVANI // LEARN. BUILD. TEST.

Learn the tech. Build the idea.

Clear study notes, tested lab files and practical guides for coding, AI and digital safety.

Explore Latest →
šŸ¤– AI & TechAI news, tools & guides šŸ“± Apps & ToolsUseful apps & websites šŸ’» CodingProgramming & web development šŸŽ“ Student TechStudy & career technology šŸ” Cyber SecuritySafety & awareness

Latest Posts

Circuit Notebook theme

Exam Notes

šŸ“š BTech CSE Exam Notes

Find Semester 1-8 subjects in one place. Choose a semester and open the notes you need. This is a general study guide, not an official syllabus.

Open Exam Notes →🧪 Open Lab Files →

Exam Numericals & Study Series

Practice CPU scheduling and explore OS and DBMS topics in separate, easy-to-follow parts. New topics will appear in the hub as they are published.

Open Numericals Hub →

Start here and stay in touch

New to TechVani? Start with our free AI tools guide for students. It covers which tools to try and what to check before relying on an answer.

For step-by-step videos, visit SiteSudhar on YouTube.

Join TechVani on WhatsApp

Get new AI tools and coding guides in your WhatsApp Updates tab.

Browse Topics

Popular Posts

TechVani

Fundamentals of Machine Learning | Semester 5 Core Notes

Semester 5 - Page 4: Fundamentals of Machine Learning. 27 numbered topics, highlighted rules, worked arithmetic, answered exam questions, pipeline diagrams, comparison tables and four complete Python demos. General common-core guide, not an official syllabus or a validated prediction service.

Run each Python block separately: Python 3, standard library only. These offline toy examples use no personal dataset, packages or network. They demonstrate arithmetic and algorithms, not useful real-world accuracy. Zero-denominator metrics in the demo deliberately return 0; other libraries may warn or use a different configured convention.

Topic map

  1. Learning problems and generalization
  2. Features, labels and prediction time
  3. Baselines and task framing
  4. Train, validation and test splits
  5. Leakage and preprocessing boundaries
  6. Missing values, encoding and scaling
  7. Linear regression and least squares
  8. Loss and gradient descent
  9. Logistic regression and thresholds
  10. K-nearest neighbors and distance
  11. Naive Bayes and conditional independence
  12. Decision trees and split criteria
  13. Support vector machines and kernels
  14. Ensembles, bagging and boosting
  15. Neural networks and backpropagation
  16. Overfitting, underfitting and regularization
  17. Cross-validation and hyperparameters
  18. Confusion matrix and classification metrics
  19. ROC, precision-recall and calibration
  20. Regression metrics and uncertainty
  21. K-means and cluster interpretation
  22. Other clustering and dimensionality reduction
  23. Feature engineering and selection
  24. Reinforcement learning basics
  25. Deployment, drift and reproducibility
  26. Privacy, fairness and decision costs
  27. Exam and experiment checklist

1. Learning problems and generalization

Machine learning fits patterns from examples to use on new data. Supervised learning uses target labels; unsupervised learning searches for structure. Prediction does not establish causation.

Worked example: Predict a later quiz outcome using information available earlier, then evaluate on genuinely held-out students/time periods.
Exam question: Does high training accuracy establish useful generalization?
Answer: No. It may reflect memorization, leakage or an unrepresentative sample.

2. Features, labels and prediction time

Features are inputs available when predicting; labels are the target outcome. Define unit, time, source and permission for each input.

Worked example: An earlier practice score may be allowed; the later final quiz score leaks the outcome into a pass prediction.
Exam question: Can a highly predictive feature still be invalid?
Answer: Yes. It may be unavailable at prediction time or inappropriate to use.

3. Baselines and task framing

Choose a measurable task and a simple baseline before adding complexity. Regression predicts numeric targets; classification predicts categories; clustering has no supplied target classes.

Worked example: Compare a classifier to training-majority prediction under the same split/metric, not only a different team's headline score.
Exam question: Does beating a weak baseline prove the system is ready?
Answer: No. Data quality, uncertainty, costs and deployment conditions still matter.

4. Train, validation and test splits

Training fits parameters; validation guides model/threshold choices; test estimates held-out performance after choices. Keep the test set out of tuning.

Worked example: Split by student for new-student use, and chronologically for future-period use when random mixing would be unrealistic.
Exam question: Why avoid repeated threshold changes on the test set?
Answer: They adapt the model to that test set and bias the reported score.

5. Leakage and preprocessing boundaries

Fit learned preprocessing only on training data, including inside each cross-validation fold. Apply the fitted transformation unchanged to held-out data.

Worked example: A scaler fit on all rows uses test-distribution information. A pipeline within cross-validation helps keep fitting inside each fold.
Exam question: Is unsupervised preprocessing exempt from leakage rules?
Answer: No. Scaling, imputation, PCA and feature selection can leak information too.
Split by unit/time
Training -> fit preprocessing + model
Validation -> transform + choose
Test -> frozen transform + evaluate
In cross-validation, fit transformations anew inside each training fold.

6. Missing values, encoding and scaling

Handle missingness deliberately; encode nominal categories without inventing order; scaling matters for many distance/gradient methods. Preserve the training transformation at inference.

Worked example: Training mean 2 from values 1, 2, 3 scales held-out 100 relative to that training mean, not a new all-data mean.
Exam question: Do trees require every numeric input to be standardized?
Answer: Not generally; preprocessing needs depend on the estimator and data.

7. Linear regression and least squares

A linear model predicts a weighted sum plus intercept. Least squares minimizes squared residuals; a perfect toy fit says nothing about future data.

Worked example: For pairs(1, 2), (2, 4), (3, 6), slope 2 and intercept 0 predict 8 at x=4. Residual variation and extrapolation need care.
Exam question: Why inspect residuals beyond one aggregate score?
Answer: They can expose systematic errors, outliers and model mismatch.

Least-squares line and training-only scaling

from math import sqrt
x, y = [1.0, 2.0, 3.0], [2.0, 4.0, 6.0]
xmean, ymean = sum(x)/len(x), sum(y)/len(y)
denominator = sum((v-xmean)**2 for v in x)
slope = sum((a-xmean)*(b-ymean) for a, b in zip(x, y))/denominator
intercept = ymean - slope*xmean
print("slope:", slope, "intercept:", intercept)
print("prediction at 4:", slope*4+intercept)
# Population scale for this toy training set, not fit on held-out data.
scale = sqrt(sum((v-xmean)**2 for v in x)/len(x))
print("held-out 100 scaled:", format((100-xmean)/scale, ".6f"))
actual, predicted = [2, 4, 6], [2, 5, 5]
errors = [a-b for a,b in zip(actual,predicted)]
print("MAE:", format(sum(abs(v) for v in errors)/len(errors), ".6f"))
print("MSE:", format(sum(v*v for v in errors)/len(errors), ".6f"))

Checked output:

slope: 2.0 intercept: 0.0
prediction at 4: 8.0
held-out 100 scaled: 120.024997
MAE: 0.666667
MSE: 0.666667

8. Loss and gradient descent

Loss quantifies error; gradient descent steps opposite the gradient of a differentiable objective. Learning rate controls step size; objective normalization changes gradient constants.

Worked example: For mean squared error, update slope and intercept using the average residual gradients, as in the offline demo.
Exam question: Does a larger learning rate always train faster safely?
Answer: No. It may oscillate or diverge.

Gradient descent on a small linear-regression objective

x, y = [1.0, 2.0, 3.0], [2.0, 4.0, 6.0]
w, b, rate = 0.0, 0.0, 0.05
for _ in range(20000):
    errors = [w*a+b-target for a,target in zip(x,y)]
    dw = 2*sum(e*a for e,a in zip(errors,x))/len(x)
    db = 2*sum(errors)/len(x)
    w, b = w-rate*dw, b-rate*db
print("slope:", format(w, ".6f"))
print("intercept:", format(b, ".6f"))
print("prediction at 4:", format(w*4+b, ".6f"))
print("MSE:", format(sum((w*a+b-target)**2 for a,target in zip(x,y))/len(x), ".6f"))

Checked output:

slope: 2.000000
intercept: 0.000000
prediction at 4: 8.000000
MSE: 0.000000

9. Logistic regression and thresholds

Binary logistic regression transforms a linear score with a sigmoid and is commonly fitted using log loss. A threshold turns a score into a class; probability calibration is not automatic.

Worked example: Lowering a threshold often increases positives/recall but also false positives; choose it using validation and decision costs.
Exam question: Is logistic regression a numeric-regression model for every continuous target?
Answer: No. Its common binary use models class scores/probabilities.

10. K-nearest neighbors and distance

KNN predicts using nearby labeled training points. Distance, scaling, K and tie handling matter. Prediction can require expensive neighbor search.

Worked example: For labeled one-dimensional points, choose three nearest and majority vote using a documented deterministic tie/order rule.
Exam question: Is KNN the same algorithm as K-means?
Answer: No. KNN uses labels for prediction; K-means clusters without labels.

11. Naive Bayes and conditional independence

Naive Bayes uses Bayes' rule with conditional feature-independence assumptions given the class. Smoothing handles unseen events in appropriate models.

Worked example: A text classifier combines class prior and feature likelihoods; unseen tokens without smoothing can collapse a product likelihood.
Exam question: Does the word naive mean it cannot be useful?
Answer: No. The simplifying assumption can still support useful baselines.

12. Decision trees and split criteria

Trees recursively split data using feature tests; criteria such as impurity reduction guide classification splits. Depth/minimum-sample constraints control complexity.

Worked example: A deep tree may memorize noisy labels; evaluate depth choices under the same validation scheme.
Exam question: Are feature-importance scores proof of causation?
Answer: No. They depend on the model, data and feature relationships.

13. Support vector machines and kernels

SVMs learn a separating decision rule with margin/regularization tradeoffs; kernels represent suitable nonlinear similarities. Scaling and hyperparameter choices matter.

Worked example: Changing C changes the penalty tradeoff; a nonlinear kernel can fit structure unavailable to a linear separator.
Exam question: Can a flexible kernel eliminate the need for validation?
Answer: No. Greater flexibility can also overfit.

14. Ensembles, bagging and boosting

Ensembles combine models. Bagging fits models on resampled data; random forests add feature randomness. Boosting builds an ensemble in successive fitting stages.

Worked example: A forest reduces some single-tree variance; boosting must still control complexity and tuning.
Exam question: Does combining more models guarantee better test accuracy?
Answer: No. Data, model errors and training design determine the result.

15. Neural networks and backpropagation

Neural networks compose parameterized transformations and activations. Backpropagation computes gradients by the chain rule; optimization updates weights.

Worked example: An input layer feeds hidden representations and outputs; loss gradient flows backward while prediction flows forward.
Exam question: Does backpropagation itself pick every hyperparameter?
Answer: No. Architecture, learning rate and training design remain choices.
Input -> hidden transformations -> score
Score + target -> loss
Loss gradient -> backpropagate -> update
Forward prediction and backward gradient computation have different jobs.

16. Overfitting, underfitting and regularization

Underfitting misses relevant structure; overfitting fits training detail without generalizing. Regularization and complexity limits introduce constraints/tradeoffs.

Worked example: High training score and low validation score suggest overfitting, but also check leakage, shift and preprocessing bugs.
Exam question: Does regularization always improve every dataset score?
Answer: No. Excessive constraint can underfit.

17. Cross-validation and hyperparameters

Cross-validation evaluates repeated held-out folds under a stated split strategy. Hyperparameters are selected outside ordinary fitted parameters. Tuning needs separation from final evaluation.

Worked example: Grouped/time-aware folds can be essential. Refit preprocessing in each training fold; nested evaluation can assess a tuning procedure.
Exam question: Can random folds be used blindly for time series?
Answer: No. Future-to-past leakage can make the estimate unrealistic.

18. Confusion matrix and classification metrics

TP, FP, FN and TN depend on the declared positive class. Precision asks correctness among predicted positives; recall asks coverage among actual positives.

Worked example: TP = 30, FP = 10, FN = 5, TN = 55 gives accuracy = 0.85, precision = 0.75, recall = 6/7 and F 1 = 0.80. The demo calculates these and a zero-denominator case.
Exam question: Does accuracy alone describe an imbalanced task?
Answer: No. A majority-only predictor may miss the positive group.

Confusion metrics with explicit zero-denominator handling

def metrics(tp, fp, fn, tn):
    divide = lambda a, b: a / b if b else 0.0
    return (divide(tp + tn, tp + fp + fn + tn),
            divide(tp, tp + fp), divide(tp, tp + fn),
            divide(2 * tp, 2 * tp + fp + fn))
for counts in [(30, 10, 5, 55), (0, 0, 5, 95)]:
    values = metrics(*counts)
    print("counts:", counts)
    for name, value in zip(["accuracy", "precision", "recall", "F1"], values):
        print(name + ":", format(value, ".6f"))

Checked output:

counts: (30, 10, 5, 55)
accuracy: 0.850000
precision: 0.750000
recall: 0.857143
F1: 0.800000
counts: (0, 0, 5, 95)
accuracy: 0.950000
precision: 0.000000
recall: 0.000000
F1: 0.000000

19. ROC, precision-recall and calibration

Threshold curves describe score tradeoffs; precision-recall is useful in many imbalanced settings. Calibration concerns whether predicted probabilities agree with observed frequencies.

Worked example: Ranking quality and probability quality are different; an AUC score is not the operating threshold or the intervention cost.
Exam question: Does a high ROC AUC guarantee well-calibrated probabilities?
Answer: No. Ranking and calibration measure different properties.

20. Regression metrics and uncertainty

MAE averages absolute error; MSE squares error; RMSE returns target units. R-squared compares residual error to variation under defined conventions. Scores depend on split and sample.

Worked example: For actual 2, 4, 6 and predicted 2, 5, 5, MAE 2/3, MSE 2/3 and RMSE sqrt(2/3). Compare under the same rows.
Exam question: Does R-squared always lie between 0 and 1 on held-out data?
Answer: No. It can be negative; constant-target cases require care.

21. K-means and cluster interpretation

K-means alternates nearest-center assignment and center means to reduce its within-cluster squared-distance objective. Initialization, K, scaling and empty clusters need handling.

Worked example: A fixed-initial-center one-dimensional demo finds groups near 1.5 and 8.5; cluster IDs are arbitrary, not supplied class labels.
Exam question: Does a cluster automatically define a meaningful social category?
Answer: No. Interpret with domain evidence and safeguards.
Initial centers
 -> assign nearest center
 -> recompute nonempty means
 -> repeat to stated stop rule
Initialization and distance scaling change clustering. IDs do not supply real-world labels.

Deterministic one-dimensional K-means teaching demo

points, centers = [1.0, 2.0, 8.0, 9.0], [1.0, 9.0]
for step in range(20):
    labels = [min(range(len(centers)), key=lambda j: (abs(p-centers[j]), j)) for p in points]
    new = []
    for j in range(len(centers)):
        group = [p for p,label in zip(points,labels) if label == j]
        new.append(sum(group)/len(group) if group else centers[j])
    if new == centers:
        break
    centers = new
print("centers:", centers)
print("labels:", labels)
print("squared error:", sum((p-centers[j])**2 for p,j in zip(points,labels)))

Checked output:

centers: [1.5, 8.5]
labels: [0, 0, 1, 1]
squared error: 1.0

22. Other clustering and dimensionality reduction

Density/hierarchical methods have different assumptions from K-means. PCA finds variance directions for a linear projection; it is not supervised feature selection by target usefulness.

Worked example: Fit PCA on training folds when used in prediction. A high-variance direction may be irrelevant to the target.
Exam question: Does unsupervised structure guarantee a better classifier?
Answer: No. Useful prediction features require task-specific evaluation.

23. Feature engineering and selection

Features can express meaningful transformations or interactions, but their definition must respect prediction time and fold boundaries. Selection is part of the fitting workflow.

Worked example: Compute rolling history using only past records, not future attempts. Select features within training folds.
Exam question: Why not select the best features on the entire dataset first?
Answer: It exposes held-out information to model choices.

24. Reinforcement learning basics

Reinforcement learning concerns an agent choosing actions in an environment using reward/feedback. States, actions, policy and delayed outcomes differ from ordinary static-label supervision.

Worked example: A simulated control task trades immediate reward against future outcomes; exploration has costs and needs safe limits.
Exam question: Is reward necessarily a complete statement of the user's real goal?
Answer: No. Poor reward design can encourage unwanted behavior.

25. Deployment, drift and reproducibility

Preserve feature/preprocessing/model versions, evaluate serving inputs and monitor relevant drift/outcomes. Seeds help repeat experiments but do not prove future performance.

Worked example: A changed quiz format can shift data; logs and reproducible splits help diagnosis while privacy limits remain enforced.
Exam question: Does deploying the highest validation score finish the ML lifecycle?
Answer: No. Monitoring, data quality, errors and responsible use continue.

26. Privacy, fairness and decision costs

Access permission, sensitive information, group effects and intervention costs matter beyond an aggregate score. Human review and contestability can be necessary.

Worked example: Use support predictions to offer help responsibly; do not deny assistance solely from a noisy estimate.
Exam question: Does removing a sensitive column guarantee fairness?
Answer: No. Proxy features and unequal data quality can preserve harmful differences.

27. Exam and experiment checklist

State task, unit, available features, split, baseline, pipeline, metric and limitations. Demonstrate arithmetic and test assumptions rather than promising accuracy.

Worked example: Draw a no-leakage pipeline and explain one false-positive/false-negative consequence for the positive class.
Exam question: What should accompany every reported model score?
Answer: Dataset/split, metric definition, fitting/tuning procedure, uncertainty and scope of use.

Evaluation boundaries

StageUseAvoid
TrainingFit parameters and transformsUsing held-out labels
Validation / CVSelect model/thresholdRandom folds for every time/group task
Final testEvaluate frozen choicesRepeated tuning on test score
DeploymentMonitor actual serving behaviorAssuming train score persists

Confusion matrix

Actual / predictedPositiveNegative
Actual positiveTP = 30FN = 5
Actual negativeFP = 10TN = 55

Metric arithmetic

MetricCalculationResult
Precision30 / (30+10)0.75
Recall30 / (30+5)0.857143 rounded
Accuracy(30+55) / 1000.85
F160 / (60+10+5)0.80
MAE example(0+1+1) / 30.666667 rounded

Learning method comparison

MethodTarget/structureKey check
Linear regressionNumeric targetResiduals, extrapolation
Logistic / classifierClass score/categoryThreshold, calibration, positive class
KNNLabeled neighborsScaling, K, ties
K-meansUnlabeled centersInitialization, K, empty clusters
PCAVariance projectionTrain-only fit, target relevance
Reinforcement learningActions and rewardsSafe exploration, reward mismatch

Revision and experiment checklist

Define unit and prediction time, establish baseline, split safely, fit preprocessing only inside training boundaries and use a metric linked to decision costs. A perfect toy training fit is not a deployment promise. Check uncertainty, privacy, group effects and drift.

Resources and sources

Official teaching and estimator documentation support the concepts. All demos here are original standard-library examples and do not depend on the version of scikit-learn documentation.

Comments