CS 230 — Mathematics, Statistics and Data for AI — Reasoning and Practice

Full teaching sequence and cumulative subject work

Derive and verify a two-parameter least-squares fit — primary material, constructed-response tasks, complete worked model and changed-case examination →

Use this workbook with the full assigned readings. Work independently, then compare each explained solution. Practice and projects are voluntary. Cases and datasets are fictional unless a primary passage is explicitly named.

Shapes, units and the meaning of a matrix product

A matrix product is meaningful when both dimensions and represented units align. Shape compatibility prevents one class of error but cannot establish that features are in the correct order or measured in the intended units. A dot product silently using dollars against a coefficient trained for cents can be numerically valid and semantically wrong.

Keep a feature schema alongside the parameters. Batch rows represent observations; columns represent features in an explicit order. A bias term is an additional model component, not a reason to ignore units.

Worked problem

Two jobs have features [hours,visits]: [2,3] and [4,1]. The coefficient vector is [1000 cents/hour,500 cents/visit], with bias 200 cents. Compute predictions and dimensions.

Trace the complete solution
  1. X has shape 2×2 and w has shape 2×1. Xw has shape 2×1, one prediction per job.

  2. The first dot product is 2000+1500=3500 cents; the second is 4000+500=4500 cents.

  3. Add the 200-cent bias to each result: 3700 and 4700 cents. The bias is not multiplied by the number of features.

  4. Record feature order and units. Swapping hours and visits produces a different model even though the array dimensions still match.

Independent transfer problem

The hours feature is converted to minutes. What coefficient preserves the same prediction, and what error occurs if the old coefficient is retained?

Compare the reasoning and result

Divide the hours coefficient by 60: 1000/60 cents per minute. Then 120 minutes contributes the same 2000 cents as two hours. Retaining 1000 as cents per minute inflates that contribution by a factor of 60. Matching dimensions alone will not detect the unit error.

Open the unit and assigned readings →

A derivative, a finite step and a loss comparison

For squared loss L(w)=(wx−y)², the chain rule gives dL/dw=2(wx−y)x. The sign points toward local increase; subtracting a positive multiple of it is a descent attempt. A finite learning rate can overshoot, so verify the resulting loss instead of assuming any step against the gradient must improve it.

Derivatives depend on the exact loss definition. Including a factor one-half removes the leading two. State the convention before comparing implementations; otherwise two correct derivations can appear inconsistent.

Worked problem

Let x=3, y=12, w=2 and L=(wx−y)². Take a gradient step with learning rate .05, then compare a step with rate .2.

Trace the complete solution
  1. Initially prediction is 6, residual −6, loss 36, and gradient 2×(−6)×3=−36.

  2. At rate .05, w becomes 3.8. Prediction is 11.4, residual −.6 and loss .36.

  3. At rate .2, w becomes 9.2. Prediction is 27.6, residual 15.6 and loss 243.36, worse than 36.

  4. The derivative supplied local direction, not a blanket guarantee for either finite step. Check the loss and document the update convention.

Independent transfer problem

For L=.5(wx−y)² at the same starting point, calculate the gradient and a .05 update. Explain whether the changed result proves a software bug.

Compare the reasoning and result

The gradient is (6−12)×3=−18. The update gives w=2.9, prediction 8.7 and loss .5×3.3²=5.445 under the new definition. The smaller update follows the changed objective scaling; it is not inherently a bug. Compare like loss conventions and adjust the learning rate deliberately.

Open the unit and assigned readings →

Base rates and the correct denominator

Conditional probabilities reverse only with additional information. Sensitivity P(alert|defect) differs from predictive value P(defect|alert). A natural-frequency table makes the denominator visible. Count true alerts and false alerts in the same population before computing what an alert means.

Changing prevalence changes predictive value even if sensitivity and false-positive rate stay fixed. That is a mathematical consequence, not evidence that the test’s internal mechanism necessarily changed. Separate population shift from a changed conditional performance rate.

Worked problem

Among 10,000 jobs, 1% are defective. A screen detects 90% of defects and alerts on 5% of nondefective jobs. Calculate the probability that an alert is a defect.

Trace the complete solution
  1. There are 100 defective and 9900 nondefective jobs. The screen yields 90 true alerts and 495 false alerts.

  2. All alerts total 585. The predictive value is 90/585≈15.38%, not 90%.

  3. The 90% figure uses defective jobs as its denominator; the requested probability uses alerts.

  4. A negative result is another conditional question with a different denominator. Do not obtain it by subtracting the positive predictive value from one.

Independent transfer problem

Prevalence rises to 10% in another 10,000-job population while both conditional alert rates stay the same. Recompute positive predictive value.

Compare the reasoning and result

There are 1000 defective jobs, giving 900 true alerts, and 9000 nondefective jobs, giving 450 false alerts. Predictive value is 900/1350=66.67%. The alert becomes more informative in this population despite unchanged sensitivity and false-positive rate. Transporting the earlier 15.38% without checking prevalence would answer the wrong setting.

Open the unit and assigned readings →

Sampling units, dependence and causal questions

A sample size is a count of observational units, not merely rows. Repeated observations from the same customer can share causes and outcomes. Treating them as independent customers can understate uncertainty. Define the target population, sampling unit, assignment mechanism and estimand before applying a standard error formula.

A narrow confidence interval does not repair a biased selection process. Nor does a precise association automatically estimate a causal effect. A before/after comparison may mix the intervention with seasonality or changes in customer composition.

Worked problem

A service receives 100 ratings from five customers, each rating 20 visits. A report claims a sample of 100 independent customers. Diagnose the inference.

Trace the complete solution
  1. The row count is 100 but there are five customer clusters. Ratings within a customer may be correlated.

  2. If the target is customer experience, first define how visits and customers are weighted. Equal visits and equal customers need not yield the same estimand.

  3. Use an analysis that reflects the sampling/dependence structure, or gather more independently sampled customers. A simple independent-row standard error is not justified by row count.

  4. Generalization also depends on who supplied ratings. Five self-selected customers may not represent the customer population even with many visits.

Independent transfer problem

Ratings improve after a new scheduling system launches in a quiet season. What evidence would strengthen a causal interpretation?

Compare the reasoning and result

Use a credible comparison that separates the system from season and composition changes, such as randomized rollout when appropriate, or a justified comparison design with baseline trends and explicit assumptions. Measure the same outcome consistently. More rows can improve precision conditional on a design, but cannot by themselves identify the system’s causal effect.

Open the unit and assigned readings →

Fitting preprocessing inside the experiment

Preprocessing learns information from data. Imputation, scaling, feature selection and vocabulary construction therefore belong inside the training process. In cross-validation, each fold’s transformer must be fitted on that fold’s training portion. Fitting once on all data before folding lets validation observations influence the representation used to predict them.

A final untouched test set estimates performance after model selection. Repeatedly checking it and changing the pipeline makes it part of development. Keep records of partition logic, especially for grouped or time-dependent observations.

Worked problem

Training values are [2,None,6]; held-out values are [100,None]. Compare training-only mean imputation with a mean fitted on all observed values.

Trace the complete solution
  1. The training-only mean is 4. Replace missing values with 4 in both training and held-out data.

  2. Using all observed values gives (2+6+100)/3=36. This allows the held-out feature distribution to alter the learned transformer.

  3. Even without using labels, the evaluation no longer represents the declared training-only fitting process.

  4. For cross-validation, repeat fitting within each fold. Preserve groups and chronological boundaries where the prediction setting requires them.

Independent transfer problem

Each customer has several rows. Random row splitting places the same customer in train and test. When is that a misleading evaluation?

Compare the reasoning and result

It is misleading when deployment must generalize to unseen customers, because the test can benefit from customer-specific patterns already represented in training. Split by customer for that estimand. If deployment predicts future visits of known customers, a time-respecting design may be more appropriate. The correct split follows the intended deployment question.

Open the unit and assigned readings →

Metrics and decisions under asymmetric costs

A confusion matrix describes counts at a chosen decision threshold. Accuracy, precision and recall summarize different denominators. Decision usefulness also requires costs, capacity and the consequences of false positives and false negatives. A high score on one metric does not establish a superior operational policy.

Threshold selection belongs in development, followed by evaluation on held-out data. Report the population and threshold with each matrix. A different prevalence or review process can change the practical value even if a reported aggregate score looks similar.

Worked problem

System A has TP=30, FP=10, FN=20, TN=140. Each missed positive costs 100 units and each false alert costs 5. Compute accuracy, precision, recall and error cost.

Trace the complete solution
  1. There are 200 cases. Accuracy=(30+140)/200=85%. Precision=30/40=75%; recall=30/50=60%.

  2. Miss costs total 20×100=2000. False-alert costs total 10×5=50. The stated error cost is 2050 units.

  3. An always-negative system has 150/200=75% accuracy and costs 50×100=5000. Accuracy alone hides the decision benefit.

  4. The cost calculation omits review labor for true alerts and intervention effects unless explicitly included. Do not label it total business profit.

Independent transfer problem

System B has TP=40, FP=40, FN=10, TN=110 under the same costs. Compare error costs and identify a capacity question.

Compare the reasoning and result

B costs 10×100+40×5=1200, less than A’s 2050, despite lower accuracy of 75%. B generates 80 alerts versus A’s 40. If reviewers can handle only 50, the unconstrained cost comparison does not establish deployability. Evaluate a threshold or workflow under the actual capacity constraint.

Open the unit and assigned readings →

Integrated project

Produce a reproducible analysis of fictional service jobs. Include a feature-unit schema, a hand-derived gradient update, two base-rate tables, a grouped/time-aware partition plan, training-only preprocessing and a threshold decision under error costs and review capacity. Supply code and independently calculated expected results.

Evidence and evaluation criteria

  1. Dimensionally valid matrix calculations with documented feature order and units.
  2. A derivative derivation and numerical before/after loss comparison at two learning rates.
  3. Natural-frequency tables distinguishing sensitivity from predictive value.
  4. An explicit sampling unit, estimand and dependence-aware evaluation design.
  5. A fitted preprocessing pipeline confined to development partitions.
  6. A confusion matrix, operational cost calculation, capacity constraint and limitations.
Worked project approach and limitations

For the two-job matrix, obtain 3700 and 4700 cents with the 200-cent bias. Show that converting hours to minutes requires dividing the matching coefficient by 60. Derive the squared-loss gradient before implementing it and compare the resulting losses rather than only the parameter values. In the rare-event screen, 90 true and 495 false alerts yield about 15.38% predictive value; show the changed-population calculation separately. Partition customers according to the deployment estimand and learn imputation inside each training fold. Compare A’s 2050 error cost with B’s 1200 while recognizing B’s 80-alert workload. The report must distinguish causal claims from predictive or descriptive findings.

Cumulative assessment

These are new situations. Explain your choice before opening the feedback.

Problem 1

A feature changes from hours to minutes. Which parameter change preserves its linear contribution?

  1. Divide its coefficient by 60
  2. Multiply its coefficient by 60
  3. Only reorder the rows
Answer and reasoning for every option

Best answer: A

  1. Correct. The feature value increases sixtyfold.
  2. Incorrect. That compounds the scale change.
  3. Incorrect. Rows do not correct feature units.

Problem 2

For x=2,y=8,w=1 and L=(wx−y)², what is the gradient?

  1. −6
  2. 24
  3. −24
Answer and reasoning for every option

Best answer: C

  1. Incorrect. That omits chain-rule factors.
  2. Incorrect. That reverses the residual sign.
  3. Correct. 2×(2−8)×2=−24.

Problem 3

A step opposite the gradient increases loss. Which explanation is possible?

  1. The test data must be corrupted
  2. The learning rate overshot
  3. Derivatives never describe local behavior
Answer and reasoning for every option

Best answer: B

  1. Incorrect. No such conclusion follows from loss increase alone.
  2. Correct. A local direction does not guarantee every finite step improves loss.
  3. Incorrect. The problem can be step size rather than derivative meaning.

Problem 4

A screen has high sensitivity in a rare-event population. What is still needed for positive predictive value?

  1. Prevalence and the false-positive rate
  2. Only sensitivity
  3. Only the number of decimal places
Answer and reasoning for every option

Best answer: A

  1. Correct. All positive results form the relevant denominator.
  2. Incorrect. That conditions on actual positives rather than alerts.
  3. Incorrect. Precision of reporting does not supply missing rates.

Problem 5

A hundred rows come from two subjects. What does row count alone fail to establish?

  1. That any data exist
  2. That all rows are identical
  3. A hundred independent observations
Answer and reasoning for every option

Best answer: C

  1. Incorrect. Rows do exist; independence is the issue.
  2. Incorrect. Dependence does not require identical values.
  3. Correct. Within-subject dependence may matter.

Problem 6

A precise observational association is reported. What additional issue remains for causation?

  1. No issue because the p-value is small
  2. Identification assumptions and confounding
  3. Only a larger font for the estimate
Answer and reasoning for every option

Best answer: B

  1. Incorrect. A significance result does not remove confounding.
  2. Correct. A narrow interval does not establish the causal design.
  3. Incorrect. Presentation does not identify an effect.

Problem 7

A scaler is fitted before cross-validation on the entire dataset. What should change?

  1. Fit it separately on each fold’s training data
  2. Use the final test labels to select scaling
  3. Remove all validation
Answer and reasoning for every option

Best answer: A

  1. Correct. Validation data should not influence learned preprocessing.
  2. Incorrect. That adds leakage.
  3. Incorrect. That removes performance evidence rather than repairing it.

Problem 8

A final test is consulted after every model change. What has happened?

  1. It is still untouched because code has a test variable
  2. The training sample necessarily doubled
  3. It has become part of model selection
Answer and reasoning for every option

Best answer: C

  1. Incorrect. A variable name does not preserve independence.
  2. Incorrect. No new samples are implied.
  3. Correct. Repeated adaptation compromises its untouched role.

Problem 9

TP=12,FP=3,FN=8. What is recall?

  1. 40%
  2. 60%
  3. 80%
Answer and reasoning for every option

Best answer: B

  1. Incorrect. That is the missed fraction of actual positives.
  2. Correct. 12/(12+8)=.6.
  3. Incorrect. 12/(12+3) is precision.

Problem 10

One system has lower accuracy but lower stated error cost. What is warranted?

  1. Metric ranking depends on the decision objective
  2. The cost arithmetic must be invalid
  3. Accuracy is never informative
Answer and reasoning for every option

Best answer: A

  1. Correct. Asymmetric costs can reverse the ranking.
  2. Incorrect. Different objectives can rank systems differently.
  3. Incorrect. It remains a descriptive metric with limitations.

Problem 11

A test split is intended to represent new customers. Which boundary is needed?

  1. Randomly distribute every visit across folds
  2. Sort rows alphabetically only
  3. Keep each customer entirely within one partition
Answer and reasoning for every option

Best answer: C

  1. Incorrect. That can put the same customer on both sides.
  2. Incorrect. Alphabetical order does not enforce customer separation.
  3. Correct. Otherwise customer-specific information can cross partitions.

Problem 12

Two matrices multiply successfully after columns are swapped. What is still required?

  1. Transpose the output until totals look plausible
  2. Check feature order and semantic units
  3. Assume the predictions mean the same thing
Answer and reasoning for every option

Best answer: B

  1. Incorrect. That does not restore the feature contract.
  2. Correct. Shape compatibility is necessary but not sufficient.
  3. Incorrect. The coefficients now multiply different features.

Assigned sources