Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
The focus of this experiment is to trace binary fault decisions at a specified threshold. Students then calculate confusion-matrix metrics and compare thresholds, and evaluate false-positive and false-negative trade-offs on held-out labels. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.
Learning objectives
Trace binary fault decisions at a specified threshold.
Calculate confusion-matrix metrics and compare thresholds.
Evaluate false-positive and false-negative trade-offs on held-out labels.
Identify the configured inputs (Decision threshold (0–1)) and record the corresponding observed outputs with units where applicable.
Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.
Expected learning outcomes
On completion, students can trace binary fault decisions at a specified threshold, calculate confusion-matrix metrics and compare thresholds, and evaluate false-positive and false-negative trade-offs on held-out labels.
Required deliverables
Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing evaluate false-positive and false-negative trade-offs on held-out labels. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to Unsupervised anomaly scoring.
The supplied model, datasets and local Python or Colab notebook. Report the data partition and execution environment; do not claim physical edge-device performance from host measurements.
Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.
M03 · learning outcome
Understand the experiment
Classification · threshold and confusion matrix
Observed labels versus predictions · four counts, not accuracy alone
Logistic scores are probabilities under the model; threshold changes predicted classes. Metrics depend on labeled positives/negatives.
Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.
Scientific theory · Probability threshold and confusion matrix
A logistic model maps a linear score through sigmoid 1/(1+exp(−z)). A classification threshold converts score to a label. Precision=TP/(TP+FP), recall=TP/(TP+FN), and F1 is their harmonic mean when defined. Accuracy alone can hide poor minority-class performance.
Worked example and engineering interpretation
For TP=8, FP=2, FN=4, TN=6, precision=0.8, recall≈0.667, F1≈0.727 and accuracy=0.70. Changing threshold changes the confusion matrix, not the trained model. State the zero-denominator policy when reporting metrics.
Engineering principles · additional worked teaching example
Threshold converts a probability score to a label. For true positives8, false positives2, false negatives4, precision=.8, recall=8/12=.667. Raising threshold may reduce false alarms but also recall; class imbalance makes accuracy misleading.
From theory to experiment
Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.
How to investigate Fault classification & decision thresholds
Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.
Experiment-specific guided practice
Objective: Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
Set Decision threshold (0–1) = 0.5. Observe the calculated results and trace.
Change Decision threshold (0–1) = 0.85. Raising the threshold cannot increase the number of positive predictions.
Restore the reference values. Record TP, TN, FP, FN; compute precision and recall manually. Explore threshold effects but use independent validation for tuning.
Reference check:
Model boundary:
Independent task and submission evidence
2. Change Decision threshold (0–1) = 0.85. Raising the threshold cannot increase the number of positive predictions. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.
Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.
Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
Method: Standardization fitted only on training; 300 full-batch gradient steps.
Data provenance: deterministic generated teaching fixture or configured analytical model. No real sensor data, physical inference performance, or production deployment is claimed.
Worked engineering reasoning and boundary conditions
A confusion matrix separates TP,FP,TN,FN. Precision=TP/(TP+FP), recall=TP/(TP+FN), accuracy=(TP+TN)/N, F1=2TP/(2TP+FP+FN). If denominator zero, state convention rather than invent value.
Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.
Mathematical representation and interpretation
Classification metrics
TP, FP and FN count true positives, false positives and false negatives. Define a zero-denominator convention and use labels from the evaluation set, not training examples.
Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.
Step 1 of 4 · Confusion matrix
Confusion matrix
Confusion matrix
TP=12 FP=3 TN=20 FN=5
Precision
Confusion matrix
TP=12 FP=3 TN=20 FN=5
Precision
12/15=0.8
Recall
Confusion matrix
TP=12 FP=3 TN=20 FN=5
Precision
12/15=0.8
Recall
12/17≈0.7059
F1
Confusion matrix
TP=12 FP=3 TN=20 FN=5
Precision
12/15=0.8
Recall
12/17≈0.7059
F1
24/32=0.75
Teaching example only; inspect live calculations or real practical evidence separately.
Recall the concept before revealing its explanation.
0 / 3 revealed
M03 · 01 / 08What is trained, and where is the confusion matrix evaluated?Reveal explanation
Engineering explanation
Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
M03 · 02 / 08How is the logistic classifier trained?Reveal explanation
Engineering explanation
Standardization fitted only on training; 300 full-batch gradient steps
Raising the threshold cannot increase the number of positive predictions.
M03 · 04 / 08Why can increasing a classification threshold reduce recall?Reveal explanation
Engineering reasoning
Fewer observations are labeled positive; some true positives become false negatives.
M03 · 05 / 08Why not tune the threshold on the final test device?Reveal explanation
Engineering reasoning
It uses test labels to choose policy, invalidating an independent final performance estimate.
M03 · 06 / 08A classifier threshold is changed. Select every technically valid statement.
A. Recompute confusion counts at the chosen threshold.
B. Use separate evaluation observations.
C. Precision equals TP divided by TP plus FN.
D. Changing a threshold guarantees precision and recall both improve.Reveal explanation
Applied scenario
Correct: A. Recompute confusion counts at the chosen threshold.; B. Use separate evaluation observations.
M03 · 07 / 08In Fault classification & decision thresholds, which reference and changed settings are prescribed for Decision threshold (0–1)?Reveal explanation
Controlled configuration
Decision threshold (0–1): 0.5 → 0.85; hold the remaining settings fixed.
M03 · 08 / 08What expected result distinguishes the reference and changed trials in Fault classification & decision thresholds?Reveal explanation
Expected observation
Raising the threshold cannot increase the number of positive predictions.
Loading live engineering instrument…Supplementary research apparatusLoading experiment-specific apparatus…Scientific model · primary investigation
Simulation task
Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
Explore the model using its own controls. Record a prediction before changing a condition. Compare the reference with a changed condition, then use the Experiment tab for the procedure, acceptance criteria and notebook. Model outputs and physical observations must remain separate.
Interactive engineering workbenchM03 · Scientific model
Readout from the original computational model; not physical measurements.
Loading instrument…
Awaiting model display.
Experimental instrumentation · A/B
Compare two model conditions
Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.
Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.
Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.
Prepare a contextual AI prompt
0 characters
Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.
Prepare → review → copy & open your selected provider → paste and submit there.
Independent theoretical exercises
Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.
01 · Predict and derive using the given inputs
For probabilities .2,.4,.6,.9 with labels 0,1,0,1, derive confusion matrices at thresholds .5 and .7.
Engineering method — Threshold converts a probability score to a label. For true positives8, false positives2, false negatives4, precision=.8, recall=8/12=.667. Raising threshold may reduce false alarms but also recall; class imbalance makes accuracy misleading. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Compare or justify using evidence
Compute precision, recall and FPR for each; explain why threshold must be selected without using final held-out labels.
Engineering method — Threshold converts a probability score to a label. For true positives8, false positives2, false negatives4, precision=.8, recall=8/12=.667. Raising threshold may reduce false alarms but also recall; class imbalance makes accuracy misleading. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Data interpretation
Data interpretation · Independent work
TP=9, FP=3, FN=6, TN=12. Derive precision, recall, accuracy and explain the significance of missed faults.
Data interpretation — Threshold converts a probability score to a label. For true positives8, false positives2, false negatives4, precision=.8, recall=8/12=.667. Raising threshold may reduce false alarms but also recall; class imbalance makes accuracy misleading. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.
Expanded independent theoretical exercise bank
Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.
Foundational · Apply the principle
Independent theoretical exercise · M03-01
TP=12,FP=3,TN=20,FN=5: calculate accuracy.
Intermediate · Calculate or trace
Independent theoretical exercise · M03-02
For same matrix calculate precision and recall.
Intermediate · Interpret the result
Independent theoretical exercise · M03-03
Calculate F1 directly from counts.
Advanced · Analyze a condition
Independent theoretical exercise · M03-04
A threshold increase changes TP from 12 to 9 and FP from 3 to 1, with positives fixed at 17. Calculate recall and precision.
Advanced · Diagnose or compare
Independent theoretical exercise · M03-05
Why might high accuracy be misleading with rare faults?
Challenging · Engineering verification
Independent theoretical exercise · M03-06
Design a valid threshold evaluation.
Challenging numerical variant 1
Calculation · Independent work
Held-out counts TP=45, FP=1, FN=5, TN=62. Compute F1 as a percentage rounded to the nearest integer.
Challenging numerical variant 2
Calculation · Independent work
Held-out counts TP=44, FP=1, FN=7, TN=24. Compute F1 as a percentage rounded to the nearest integer.
Challenging numerical variant 3
Calculation · Independent work
Held-out counts TP=43, FP=8, FN=1, TN=57. Compute F1 as a percentage rounded to the nearest integer.
Step-by-step experimental procedure
Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
1 · Reference workbench configuration
Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.
Decision threshold (0–1)0.5
2 · Perform the investigation in order
Set Decision threshold (0–1) = 0.5. Observe the calculated results and trace.
Change Decision threshold (0–1) = 0.85. Raising the threshold cannot increase the number of positive predictions.
Restore the reference values. Record TP, TN, FP, FN; compute precision and recall manually. Explore threshold effects but use independent validation for tuning.
3 · Compare controlled trials
Trial
Independent change
Expected check
Observation
Reference
Use reference inputs above
Raising the threshold cannot increase the number of positive predictions.
Record actual result
Controlled change
Decision threshold (0–1) = 0.85
Raising the threshold cannot increase the number of positive predictions.
Record actual result
4 · Analyze and report
Record TP, TN, FP, FN; compute precision and recall manually. Explore threshold effects but use independent validation for tuning.
Required evidence: Record the fault classification & decision thresholds comparison and justify the changed outcome from the calculated trace.
Model boundary: Standardization fitted only on training; 300 full-batch gradient steps
Controlled investigation · reproducible evidence
Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.
Trial
Independent change
Dependent observation
Reference
Use reference inputs above
Record actual outcome and units
Controlled change
Decision threshold (0–1) = 0.85
Record actual outcome and units
Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.
Loading laboratory-specific procedure…
Python / Google Colab notebook
Original Python reference, generated teaching fixture. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.
Use a threshold of 0.50 and zero temperature shift. Run 40 samples and compute precision and recall from the confusion matrix.
Reset, select 0.85 and run the same 40 samples. Compare false positives and false negatives.
Change the temperature shift during playback and inspect later decisions. Explain why changing settings mid-run produces a mixed-policy history.
Export both controlled runs and identify a separate validation dataset needed for threshold selection.
Evidence: retain your prediction, configuration, observations and exported event history; distinguish calculated teaching-model results from physical measurements.
Complete practical procedure & acceptance
Read the method, enter a prediction and save the reference baseline.
Apply the controlled change and compare metrics and plot. Record TP, TN, FP, FN; compute precision and recall manually. Explore threshold effects but use independent validation for tuning.
Restore the reference and verify that the original metrics return. Enter an invalid parameter and confirm that export is disabled, then restore.
Run the independent local Python computation from the extracted portal root:
BASH · Command
python3 verification/ml168_practical.py all
Expected: ten passing checks and a result object for each lab. This uses Python standard library only. Compare the default result for M03 to the browser output.
Export actual observations and explain one limitation.
Student submission: include your prediction, exported baseline and controlled result, actual terminal output, and a short interpretation. Do not submit the build validation report as your own evidence.
Experimental notebook
Record your own results. Values are not prefilled or independently verified.
Record & discuss
Portfolio exports use related core lab K14 for compatibility. The supplementary experiment ID is preserved in the attachment. Local completion is self-reported.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.
Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.
01Instructions · Markdown
# m03 · Fault classification & decision thresholds
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## Introduction
Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
## How to run
1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook.
2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all.
3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell.
4. Save your own outputs and compare them to the portal Experiment tab.
**Execution boundary:** Original Python reference, generated teaching fixture. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
02Instructions · Markdown
## Experiment-specific preparation
Train a two-feature logistic classifier and interpret a confusion matrix on a separate device.
**Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):**
1. Set Decision threshold (0–1) = 0.5. Observe the calculated results and trace.
2. Change Decision threshold (0–1) = 0.85. Raising the threshold cannot increase the number of positive predictions.
3. Restore the reference values. Record TP, TN, FP, FN; compute precision and recall manually. Explore threshold effects but use independent validation for tuning.
**Evidence:**
**Boundary:**
03Instructions · Markdown
## 1. Objectives and reference condition
- Reproduce the specific computational mechanism in this laboratory.
- Inspect the output, compare the reference condition with a changed or rejected condition where implemented, and explain any discrepancy.
- Distinguish actual local Python execution from mock, physical and external-service observations.
## 2. Environment check
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# M03 | Code cell 01 | Fault classification & decision thresholds
# Purpose: 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implem
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import sys
print("Python",sys.version.split()[0])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sys.version_info >= (3,10)
## 3. Implementation
Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# M03 | Code cell 02 | Fault classification & decision thresholds
# Purpose: implement only the mechanism named in this laboratory.
# Inputs: the explicit fictional fixture and reference parameters below.
# Output: printed observations and assertions for the controlled trial.
# =====================================================================
import math,statistics as st
def fixture():
rows=[]
for i in range(120):
x=18+(i*7%23)+((i*13%9)-4)/10; v=1+(i*11%17)/5
rows.append(dict(id=i,device=f'node-{1+i//40}',x=x,v=v,y=2.1*x+3+((i*19%13)-6)*.4,fault=int(x+3*v+((i*17%11)-5)/2>36)))
return rows
def fit(rows):
# Standardize on training rows only, then full-batch logistic gradient descent.
mu=[st.mean(r[k] for r in rows) for k in ('x','v')]; sd=[st.pstdev(r[k] for r in rows) or 1 for k in ('x','v')]; w=[0.,0.]; b=0.
for _ in range(300):
dw=[0.,0.]; db=0.
for r in rows:
z=[(r[k]-mu[i])/sd[i] for i,k in enumerate(('x','v'))]; e=1/(1+math.exp(-(b+sum(a*c for a,c in zip(w,z)))))-r['fault']; db+=e
for i in range(2): dw[i]+=e*z[i]
b-=.25*db/len(rows); w=[a-.25*d/len(rows) for a,d in zip(w,dw)]
return dict(mu=mu,s=sd,w=w,b=b)
def probability(m,r):
return 1/(1+math.exp(-(m['b']+sum(m['w'][i]*(r[k]-m['mu'][i])/m['s'][i] for i,k in enumerate(('x','v'))))))
def matrix(y,p):
tp=sum(a==b==1 for a,b in zip(y,p)); tn=sum(a==b==0 for a,b in zip(y,p)); fp=sum(a==0 and b==1 for a,b in zip(y,p)); fn=sum(a==1 and b==0 for a,b in zip(y,p)); ratio=lambda a,b:a/b if b else 0
return dict(tp=tp,tn=tn,fp=fp,fn=fn,accuracy=ratio(tp+tn,len(y)),precision=ratio(tp,tp+fp),recall=ratio(tp,tp+fn),f1=ratio(2*tp,2*tp+fp+fn))
### Step 2 · Run the reference calculation
Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# M03 | Code cell 03 | Fault classification & decision thresholds
# Purpose: implement only the mechanism named in this laboratory.
# Inputs: the explicit fictional fixture and reference parameters below.
# Output: printed observations and assertions for the controlled trial.
# =====================================================================
rows=fixture();train,test=rows[:80],rows[80:]
model=fit(train);y=[r['fault'] for r in test];probs=[probability(model,r) for r in test]
# Compare thresholds without retraining or altering the held-out labels.
low=matrix(y,[int(p>=.5) for p in probs]);high=matrix(y,[int(p>=.85) for p in probs]);print(low,high)
assert sum(low[k] for k in ('tp','tn','fp','fn'))==40
assert high['tp']+high['fp']<=low['tp']+low['fp']
## Original portal implementation (reference only)
These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all.
```bash
python3 verification/ml168_practical.py all
```
10Instructions · Markdown
## 4. Results and analysis
Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result.
| Trial | Configuration | Observation | Interpretation |
|---|---|---|---|
| A | Reference | | |
| B | One controlled change | | |
| C | Reference repeat | | |
**Limitations:** Original Python reference, generated teaching fixture. Notebook success does not certify external equipment or services.
11Instructions · Markdown
## Guided reasoning and evidence
A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above.
**Independent task:** 2. Change Decision threshold (0–1) = 0.85. Raising the threshold cannot increase the number of positive predictions. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.
| Trial | Input/configuration | Prediction | Observation | Evidence / limitation |
|---|---|---|---|---|
| A | Reference | | | |
| B | Changed input | | | |
| A repeat | Reference | | | |
A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.
Shared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research