AAmit’s LibraryLEARN · PRACTISE · REFLECT
Amit’s Library

AI and analytics: seven bounded practical lessons

Original guides with reproducible synthetic examples. Suggested allowance45–90minutes per lesson,excluding advanced extensions;this is an estimate,not measured learner time. Regression and text classification fit small models;monitoring and evaluation inspect supplied predictions. Prompt evaluation checks a mechanical response contract and calls no AI service.

Run locally

Download implementation,tests and expected JSON to one folder,then run:

python3 ai_practice.py
python3 -m unittest ai_practice_test.py

The code uses Python3.10+ and its standard library only. It prints results and performs no network or automatic business action. Editable guide downloads need their own backup;catalogue responses participate in the existing browser learning backup.

Regression: fit, predict and challenge

Expected baseline: Slope2,intercept1;held-out predictions9,11;MAE0.5.

A retailer wants to predict demand from an explanatory variable such as promotional intensity. Begin with a deliberately tiny invented training set: x=1,2,3 and demand y=3,5,7. Ordinary least squares minimises the sum of squared training residuals. Centre x and y around their means, divide the sum of cross-products by the sum of squared centred x values, and calculate the intercept from the means. The hand result is slope2 and intercept1. The implementation actually estimates these parameters from training observations; it does not merely return supplied predictions.

Keep the held-out cases x=4,5 outside fitting. Predictions are9 and11; held-out actuals9 and12 give absolute errors0 and1, and mean absolute error0.5. Explain why training error0 does not imply that new demand is perfectly predictable. These held-out inputs extend beyond the training range; extrapolation deserves particular attention. The demonstration is a classroom check of arithmetic, not evidence that promotion causes demand or that an operational forecast is accurate.

Change one training outcome, refit and describe how the slope changes. Then change only a held-out outcome: the fitted parameters should stay the same while evaluation changes. This distinction is the central leakage check. Try identical x values: slope estimation is undefined and the code rejects that case. Check negative slope, non-finite numbers, booleans and unequal lengths. Input validation protects the calculation but cannot repair a biased sampling process.

Marketing owns the meaning of promotional intensity; operations defines demand and stock availability; analytics specifies the observation window. Ask Who approves the forecast, Whose records were omitted, When the prediction is available, Why a linear relation is plausible and How errors affect replenishment. Foundation: explain slope and residuals in plain language. Undergraduate: reproduce estimation and test error. Postgraduate: compare a constant baseline, residual patterns and omitted variables. Research: propose an observational or experimental design with justified sampling and uncertainty estimation. Submit hand workings, changed-case outputs and a decision memo identifying what the model cannot establish.

Save response and mark a self-reported attempt

A trained majority-class baseline

Expected baseline: Training majority0;four held-out predictions0;accuracy0.5.

An organisation considering a classification system first needs a simple benchmark. Fit a majority-class model using training labels0,0,0,1,1. The learned class is0. Predict0 for each of four held-out labels0,1,1,0; two are correct and accuracy is50%. This is a real fitted baseline, albeit one that deliberately ignores features. A complicated model should earn its additional maintenance cost against such a transparent alternative.

Training and evaluation serve different purposes. The training population has a60% majority, while the held-out fixture is balanced. Do not report the training majority rate as held-out accuracy, and do not inspect the test labels to choose the majority class. For ties, the implementation explicitly chooses0. Naming that policy makes the behaviour reproducible rather than allowing an accidental library ordering to decide.

Refit using1,1,0 and examine the changed learned class. Leave the training data unchanged and alter the test prevalence: observed accuracy changes although the model does not. Now use a business interpretation, such as urgent versus routine requests. An all-routine baseline can look successful when urgent cases are rare while missing every urgent case. Accuracy alone cannot establish service quality; record urgent-case recall, false alarms and the consequences of delay.

Support defines urgency and label quality; analytics separates training from evaluation; managers agree the benchmark and cost of misses. Explain Who labels ambiguous cases, Which baseline is defensible and How changing case mix affects comparisons. Foundation: state what fitting means. Undergraduate: implement and evaluate the baseline. Postgraduate: compare temporal or grouped splits with a random split and investigate subgroup performance. Research: propose an evaluation protocol addressing label disagreement and deployment changes. Submit training labels, tie policy, held-out results and a recommendation. This small fixture supplies no generalisation guarantee, probability estimates or deployed service.

Save response and mark a self-reported attempt

Classification errors and business costs

Expected baseline: TP=TN=FP=FN=1;precision=recall=accuracy0.5;error cost12.

For four invented requests, actual urgent labels are1,1,0,0 and predicted urgent labels are1,0,1,0. Work through each record before reading the result. One urgent case is detected, one routine case is correctly left routine, one routine case triggers an unnecessary escalation and one urgent case is missed. Therefore TP=TN=FP=FN=1; precision, recall and accuracy are each0.5. The fixture evaluates supplied predictions; it does not fit a classifier or derive a threshold.

Use an explicitly invented cost policy: a missed urgent case costs10 units and an unnecessary escalation costs2. Total error cost is12. Change the costs to100 and1 and the same predictions cost101. This is a managerial judgement about consequences, not a universal monetary valuation. State the unit, time horizon and exclusions. For health, safety or regulated decisions, a simple financial score cannot replace the relevant decision obligations.

Try no positive predictions. Precision has a zero denominator and is reported as unavailable, not silently converted into perfect performance. Try no actual positives: recall is unavailable. The code rejects labels outside integer0/1, mismatched lengths and negative or non-finite costs. If comparing systems, use the same labelled cases and cost policy. Separately evaluate coverage, uncertainty and who bears the consequences of mistakes.

Operations owns the escalation process; customer service reviews harms from delay; managers approve the cost assumptions; analytics computes metrics and documents their limitations. Ask Whom a false alarm burdens, Whose case is missed and Which threshold trade-off would be acceptable if scores were available. Foundation: narrate all four outcomes. Undergraduate: derive the confusion matrix. Postgraduate: compare thresholds, prevalence and subgroup error rates using a larger appropriate dataset. Research: design a study of decision utility and human overrides. Submit a record-level table, calculations, two cost policies and an escalation recommendation. No model certification or causal conclusion follows from these four cases.

Save response and mark a self-reported attempt

Forecast monitoring and accountable review

Expected baseline: MAE40/3;mean actual-minus-prediction20/3;limit10 triggers review.

Monitoring compares predictions made earlier with outcomes that have now become available. In the synthetic period, actuals are100,120,80 and forecasts90,100,90. Absolute errors are10,20,10, producing MAE40/3. Signed errors use actual minus forecast:10,20,-10, giving mean error20/3. The positive mean indicates underprediction on average under this sign convention. Always state the convention; another system may reverse it.

The invented review limit is10. MAE exceeds it, so review_required is true. At exactly10 the strict greater-than rule does not flag review. This deterministic policy is not a statistical drift test, prediction interval or proof of model failure. It is a simple monitored error threshold chosen for classroom discussion. A review should investigate data collection, realised demand, unusual promotions, stockouts and forecast timing before deciding whether retraining is appropriate.

Change the forecasts to the actual values: error becomes0. Change one actual sharply and inspect both the aggregate and record-level errors. Discuss why a small number of observations can make an alert unstable and why repeated alerts need an owner and response timetable. Do not automatically substitute later actuals into the stored forecasts; preserve the original prediction timestamp, horizon and model version so that the evaluation remains auditable.

Operations records realised outcomes, analytics computes comparable errors and management decides the tolerable business impact. Customer service may reveal harm that an average misses. Ask When the outcome becomes reliable, Who investigates an alert, Why the threshold was selected and How the review closes. Foundation: explain prediction versus actual. Undergraduate: calculate signed and absolute error. Postgraduate: compare seasonal baselines, segment performance and alert workload. Research: design a prospective monitoring study with stable definitions and an appropriate statistical method. Submit calculations, the changed cases, an alert ownership table and a response memo. This fixture monitors supplied predictions and contains no forecast-fitting or automatic retraining service.

Save response and mark a self-reported attempt

Keyword frequency without semantic claims

Expected baseline: Top3:late2,refund2,parcel1;ties alphabetical;stopword-only input gives empty list.

A support team wants to explore recurring words before choosing a more sophisticated language system. The fixture lowercases English ASCII letters, extracts alphabetic tokens and removes a small declared stopword set: the,a,and,is,to,my. For “The late parcel and late refund. Refund is pending.” the most frequent words are late2,refund2 and parcel1. Ties use alphabetical order, so parcel precedes pending. This explicit rule matters when requesting only three results.

Frequency is a descriptive count, not a determination of what the customer intends. “Not late” still contains late, and removing words can destroy distinctions. The tokenizer does not support all languages, Unicode writing systems, numbers or nuanced negation. A keyword list can guide human inspection of records; it should not automatically accuse staff, refuse a refund or infer a customer’s emotional state.

Run the original phrase, then replace it with stopwords alone: the result is empty. Change punctuation and casing and inspect the stable counts. Add repeated words and check the top-n boundary. The function rejects non-text input and nonpositive or boolean n. A robust project would also define document boundaries, duplicate-message treatment, privacy controls and which language-specific tokenizer is appropriate.

Customer service defines the collection and reviews examples; analytics documents preprocessing; managers decide whether the resulting themes answer a useful question. Ask Whose language is underrepresented, What was removed, Where the text came from and Why a word count is relevant to an operational decision. Foundation: explain a token and count. Undergraduate: reproduce the vocabulary and tie ordering. Postgraduate: compare document frequency, phrase extraction and multilingual preprocessing with reviewed samples. Research: propose an annotation study of theme validity and representational bias. Submit token lists, changed examples, a preprocessing specification and a human-reviewed theme memo. This is a reproducible counting baseline, not a deep-learning model or a general language-understanding system.

Save response and mark a self-reported attempt

Fit a small text classifier

Expected baseline: Held-out late parcel->1;excellent thanks->0;unseen-only message->0 with equal priors.

Fit a multinomial naive Bayes teaching model using four invented support messages. Class1 has “late broken parcel” and “late delivery”; class0 has “thanks excellent service” and “excellent support thanks”. Training builds separate token counts, class document counts and a training-only vocabulary. Prediction combines the class prior with smoothed token likelihoods in log space. Add-one smoothing prevents an observed vocabulary word from having zero likelihood simply because it did not appear in one class.

Hold out “late parcel” and “excellent thanks”. The fitted model predicts1 and0 respectively. These two convenient cases illustrate the implementation, not a defensible accuracy estimate. No test text is added to the training vocabulary. Unknown tokens are ignored, so a message containing only unseen words is decided by the class prior. With equal priors the explicit tie policy returns0. That behaviour needs disclosure because an unfamiliar urgent complaint could receive a routine label.

Change the training class balance and inspect the prior-driven behaviour for unseen text. Add a contradictory training example and examine whether predictions change. Explain that the simplifying token-independence assumption is often unrealistic and that repeated words affect the likelihood. The same English ASCII preprocessing limits used by the keyword lesson apply here. A sentence such as “not late” can be misinterpreted; tiny curated examples provide no protection against such failures.

Support supplies reviewed labels; analytics manages splits and training artifacts; management agrees whether predictions assist triage or determine a consequential decision. Human review and escalation are essential parts of the proposed workflow. Ask Who labels messages, Whose writing differs from the fixture and How unfamiliar text should be routed. Foundation: explain training vocabulary. Undergraduate: trace counts and one prediction. Postgraduate: evaluate a larger held-out dataset, leakage, class imbalance and costs. Research: design an annotation and deployment study with uncertainty and subgroup analysis. Submit the fitted counts, two predictions, unseen-word tests and an override policy. No pretrained model, external API or live customer data is used.

Save response and mark a self-reported attempt

Prompt evaluation as a limited contract check

Expected baseline: Valid sample passes mechanical contract;malformed/wrong-key/wrong-ID/wrong-action examples fail;semantic review remains.

Before adopting an AI assistant, define what an acceptable response means and which parts can be checked automatically. This fixture checks supplied response strings against a small JSON contract. The response must be an object with exactly order_id and action; the identifier must equal the supplied expected identifier and the action must be review or escalate. The sample {"order_id":"O1","action":"review"} passes for expected identifierO1.

No language model is called and no prompt is sent. You can write several candidate prompts and manually supply imagined responses, but the result is a mechanical response-contract test, not evidence of a model’s reliability. The checker cannot establish that review was the right action, that the response is factual, that a model followed instructions or that a business decision is safe. A schema-valid response can still be substantively wrong.

Try malformed JSON, a list instead of an object, an extra key, the wrong identifier and an unsupported action such as refund. These fail for different reasons. Compare an automatic format check with a human rubric addressing correctness, source fidelity, uncertainty, privacy and escalation. If later evaluating a real model, preserve a versioned test set, model configuration, response evidence and a held-out evaluation set. Do not tune prompts on the final held-out cases and then describe the score as independent validation.

The business owner defines the decision boundary; IT defines the contract; reviewers judge meaning and consequences. Ask Who may authorise an action, Whom an incorrect identifier affects, Which checks are automatic and How a questionable response is escalated. Foundation: distinguish syntax from meaning. Undergraduate: reproduce accepted and rejected cases. Postgraduate: develop a blinded rubric and analyse reviewer disagreement. Research: propose a controlled evaluation with a baseline and defensible sampling. Submit candidate prompts, supplied response strings, contract results and a separately completed human rubric. A pass remains advisory evidence, and this package supplies no AI integration, automatic transaction execution or semantic judge.

Save response and mark a self-reported attempt

Optional companion reading: Public guide: writing a clearer prompt. Rewrite the lab prompt once to specify the output format and one constraint. Mark what the existing check can verify and what still needs a human check. No AI account or live request is needed for this exercise.

Individually answered assessment

Four questions per subject,with distinct model answers and marking criteria. Draft your answer before revealing guidance;attempts are self-reported.

Connect the evidence

Prediction quality,decision quality and organisational responsibility are different questions. Retain original forecasts and labelled cases;record exclusions,cost policies and human review. These tiny datasets teach methods without supplying real-world accuracy claims.

All practical lessons · Current coverage and remaining queue