MGU Computer Science Series — Computer Science Foundations
Part VI: Computing in the Modern World
Rule-Based Systems · Machine Learning · Neural Networks · Generative AI · Bias
Chapter 26 of 28
MGU Computer Science Series  ·  Computer Science Foundations  ·  Library Textbook Edition

Chapter 26:
Artificial Intelligence
and Machine Learning
Foundations

What AI actually is beneath the headlines — rule-based systems, machine learning, training data, models, neural networks, generative AI, evaluation, bias, and responsible use

■ CS Level: Foundations ■

■ 10 Sections  •  Part VI of 7 ■

Follows Data Science Foundations  ·  Prepares students for Software Engineering and Ethics

Purpose and Overview

This chapter introduces artificial intelligence and machine learning as areas of computer science concerned with systems that perceive, predict, reason, generate, and support decisions. Students will learn what AI actually is beneath the headlines, how machine learning differs from traditional programming, where training data comes from and why it matters, what models are and how they are evaluated, and how generative AI systems produce text and images.

The chapter is honest about what AI systems can and cannot do, clear about where human choices shape AI behavior, and careful about bias, limits, and responsible use. By the end of this chapter, students should be able to describe an AI system's inputs, model, outputs, and limitations — and ask thoughtful questions about any AI system they encounter.

Opening Question

When you type a message to a chatbot and it responds with a well-organized paragraph, what is actually happening? When a streaming service recommends a show you end up loving, how did it know? When a photo app recognizes your friend's face, what is it doing? These are not tricks or magic. They are the outputs of systems built from data, mathematics, and deliberate human choices — and by the end of this chapter, you will be able to describe exactly what is going on inside them.

10Sections
12Objectives
25+Key Terms
8+Worked Examples

Learning Objectives

  1. 1Explain what artificial intelligence is and is not, distinguishing common misconceptions from accurate descriptions.
  2. 2Describe how rule-based systems work, including their strengths and limitations.
  3. 3Explain the core difference between traditional programming and machine learning.
  4. 4Describe the three main types of machine learning: supervised, unsupervised, and reinforcement learning.
  5. 5Define training data, model, features, labels, and explain how they relate.
  6. 6Distinguish between classification and regression as types of prediction tasks.
  7. 7Explain the basic structure of a neural network, including input, hidden, and output layers.
  8. 8Describe what generative AI and large language models do, including the phenomenon of hallucination.
  9. 9Evaluate an AI system using metrics beyond overall accuracy, including the confusion matrix, precision, and recall.
  10. 10Identify sources of bias in AI training data and describe real-world consequences.
  11. 11Describe the fundamental limits of current AI systems.
  12. 12Apply principles of responsible AI use, including transparency, human oversight, and accountability.

Sections at a Glance

Sections 26.1 – 26.2
What AI Is and Where It Started
What Artificial Intelligence Means · Rule-Based Systems

What Artificial Intelligence Means

A Term with Many Meanings

Artificial intelligence is one of the most talked-about and most misunderstood phrases in modern technology. To some people it suggests human-like robots from science fiction. To others it means a chatbot, a spam filter, or a recommendation algorithm. To computer scientists, AI refers to a broad family of techniques for building systems that perform tasks that would typically require some form of perception, reasoning, or decision-making when performed by humans.

That definition is intentionally wide. AI is not a single algorithm or a single technology. It is a field — a collection of methods, problems, and approaches — that has expanded dramatically over the past several decades and especially over the past ten years.

What AI Systems Do

Artificial intelligence systems are built to perform tasks such as recognizing patterns in images, audio, text, or sensor data; classifying inputs into categories; predicting future values or outcomes from past data; recommending items or actions based on past behavior; translating text between languages; generating new text, images, audio, or video; playing complex games; and controlling robots or vehicles through perception and response.

Notice that this list does not include: "understand the world the way humans do," "reason about ethics spontaneously," or "have goals of their own." These distinctions matter. AI systems can perform remarkable tasks within their training domain while remaining brittle, narrow, and unaware of the broader world.

A Brief History in Four Periods

PeriodApproachKey Development
1950s–1980sSymbolic AI and Rule-Based SystemsExplicit logical rules written by experts; worked on narrow problems, failed on messier ones
1980s–2000sMachine Learning EmergesSystems that learn patterns from data; progress limited by data volume and computing power
2000s–2010sData and ScaleThe internet produced vast data; search engines, recommendation systems, and spam filters became AI systems
2010s–presentDeep Learning and Generative AINeural networks with many layers; large language models; image generation from text

What AI Is Not

Common Misconceptions About AI

AI systems are not conscious. They do not experience the world, have desires, or feel emotions. An AI that writes a paragraph about loneliness is not lonely — it is performing a statistical operation over a learned pattern space.

AI Is Not Magic

Every AI system is built from mathematics, data, software, and hardware. Every output can, in principle, be traced back to specific design choices, training data, and model architecture.

AI Is Not Neutral

The choices about what data to collect, what problem to solve, what to optimize for, and how to deploy a system are human choices. Those choices reflect values, priorities, and sometimes biases that get embedded in the system.

Rule-Based Systems

The Oldest Approach to AI

Before machine learning dominated the field, most AI systems were rule-based systems — programs that used explicit if-then rules written by human experts to make decisions. A rule-based system has two main components: a knowledge base (a collection of facts and rules from experts) and an inference engine (a program that applies the rules to inputs and produces conclusions).

Example 26.2.1
A simple rule-based medical diagnosis system
  • Rules RULE 1: IF lesion is red AND raised AND itchy THEN consider eczema RULE 2: IF lesion has irregular border AND multiple colors THEN consider melanoma screening RULE 3: IF rash is ring-shaped AND expanding AND patient was outdoors THEN consider Lyme disease
  • InputPatient arrives with a red, ring-shaped, expanding rash after a camping trip.
  • InferenceThe engine checks each rule. RULE 3 matches all conditions.
  • OutputSystem recommends Lyme disease screening. Every step is fully traceable to the rules.
DimensionRule-Based StrengthRule-Based Limitation
Knowledge sourceWritten directly by human expertsCapturing full expert knowledge in rules is extremely difficult
TransparencyEvery decision traces to a ruleAs rules multiply, they conflict and leave gaps
Variation handlingReliable when the case matches a ruleBrittle on unusual or unanticipated cases
UpdatingPredictable behaviorA human must manually update every affected rule when the world changes
Why Rules Failed for Images

Consider trying to write rules for recognizing cats in photographs. Pointy ears? Four legs? Fur? A tail? Every rule immediately admits exceptions. Rule-based systems struggled with perception tasks because human visual knowledge is too rich and contextual to capture in explicit rules — and this motivated machine learning.

Sections 26.3 – 26.6
Machine Learning: Learning from Data
What Machine Learning Means · Training Data and Models · Features, Labels, and Prediction · Classification

What Machine Learning Means

The Core Machine Learning Idea

TRADITIONAL PROGRAMMING: Input + Rules → Output

MACHINE LEARNING (Training): Input + Output → Learned Model

MACHINE LEARNING (Prediction): Input + Learned Model → Output

In traditional programming, a human writes the rules. In machine learning, a human provides examples of input-output pairs and the learning algorithm discovers the rules automatically.

Example 26.3.1
Spam detection: rules vs. machine learning
  • Rule-basedWrite rules like "if the email contains 'WINNER' in all capitals, mark as spam." Works for some cases but fails as spammers adapt their language.
  • ML approachCollect 100,000 emails already labeled spam or not spam by humans. Show them to a learning algorithm. It discovers patterns — combinations of words, senders, links, and formatting — without being told what to look for.
  • ResultThe trained model classifies new emails it has never seen, as long as their patterns resemble the training data.

Three Types of Machine Learning

TypeWhat the System ReceivesWhat It LearnsExample Task
Supervised LearningInputs paired with correct labelsTo map inputs to correct outputsSpam detection, medical image classification, language translation
Unsupervised LearningInputs only — no labelsStructure, groupings, or patterns in the dataCustomer segmentation, anomaly detection, data compression
Reinforcement LearningActions and feedback (rewards)Strategies that maximize cumulative rewardChess-playing AI, robot locomotion, game agents

Training Data and Models

A training dataset is the collection of examples used to teach a machine learning model. Its quality, size, diversity, and accuracy directly determines what the model can and cannot do. Early machine learning systems were trained on thousands of examples. Modern systems are trained on billions. A large language model may be trained on trillions of words of text.

A model is the mathematical structure that captures the patterns the algorithm found. Think of it as a complex function: Model(input) → output. The model is stored as a large collection of numbers called parameters or weights — adjusted during training to minimize prediction errors. A small model may have thousands of parameters; a large language model may have hundreds of billions.

Data SplitPurposeUsed When
Training dataThe model adjusts its parameters based on these examplesDuring the training process
Validation dataCheck generalization; guide decisions about architecture and settingsDuring training (held out from parameter updates)
Testing dataFinal honest estimate of real-world performanceOnce, after training is complete
Overfitting

A model that memorizes its training data perfectly but fails on new examples has not learned anything useful — it has only learned to recognize what it has already seen. This failure mode is called overfitting, and it is one of the most important concepts in machine learning. Honest evaluation always uses a test set the model has never seen during training.

Features, Labels, and Prediction

Features: Describing the Input

A feature is any measurable property of the input that might be useful for the prediction task. Choosing which features to include — feature engineering — is one of the most important skills in machine learning.

Prediction TaskExample Features
Loan approvalAnnual income, credit score, debt-to-income ratio, employment years, past defaults
Tumor classificationCell radius (mean), cell texture, smoothness, symmetry, concave points
Spam detectionWord count, presence of "WINNER," number of links, sender known, uppercase word ratio
Movie review sentimentWord frequencies, presence of positive/negative words, punctuation patterns, sentence length

Labels and Prediction

In supervised learning, each training example also includes a label — the correct output that the model should learn to predict. For a spam filter: spam or not spam. For a tumor classifier: benign or malignant. Labels are typically provided by humans or extracted from historical records.

Once trained, the model is applied to new inputs it has never seen — called inference. It does not look up the input in a table; it applies the mathematical function it learned. Machine learning prediction tasks fall into two main types:

Task TypeOutputExamples
ClassificationOne of a fixed set of categoriesSpam/not spam; cat/dog/bird; digit recognition
RegressionA continuous numberHouse price; sales forecast; tomorrow's temperature

Classification

A classifier assigns an input to one of a set of predefined categories. Classification is one of the most common and practical machine learning tasks. Spam filters, medical diagnostic aids, image recognition systems, fraud detectors, content moderation tools, and voice recognition systems are all classifiers.

A classifier learns a decision boundary — a line, curve, or surface in feature space that separates one class from another. Any new input that falls to one side of the boundary is classified as one category; inputs on the other side are classified differently.

Example 26.6.1
Classifying iris flowers
  • Dataset150 iris flowers from three species: setosa, versicolor, and virginica. Each has four features: sepal length, sepal width, petal length, and petal width.
  • TrainingTrain a classifier on 120 flowers. Test on the remaining 30.
  • New inputSepal length: 5.1 cm, Sepal width: 3.5 cm, Petal length: 1.4 cm, Petal width: 0.2 cm
  • PredictionIris setosa → 97% Iris versicolor → 2% Iris virginica → 1% Final: Iris setosa (confidence: 97%)
  • WhySetosa has much shorter, narrower petals than the other two species. The classifier learned this pattern from training examples.
High confidence scores indicate a strong match to learned patterns. Low confidence (51% vs 49%) signals uncertainty.

The Confusion Matrix

A confusion matrix organizes predictions by actual versus predicted class. It reveals more than simple accuracy by showing exactly which errors the classifier makes.

Predicted: Not SpamPredicted: Spam
Actual: Not Spam940 — True Negatives (TN)20 — False Positives (FP)
Actual: Spam15 — False Negatives (FN)25 — True Positives (TP)
Precision and Recall

Precision = TP / (TP + FP) — Of all predictions of "spam," how many were actually spam?

Recall = TP / (TP + FN) — Of all actual spam messages, how many did the model catch?

A model that predicts "not spam" for every email would achieve high accuracy in a world where most email is legitimate — but would catch zero spam. The confusion matrix reveals this failure where overall accuracy conceals it.

Sections 26.7 – 26.8
Neural Networks and Generative AI
Neural Networks at an Introductory Level · Generative AI

Neural Networks at an Introductory Level

The Basic Unit: A Neuron

A neural network is built from many simple processing units called neurons (or nodes), loosely inspired by biological neurons. Each artificial neuron does something simple:

How a Single Neuron Works

Inputs: x1, x2, x3

Weights: w1, w2, w3

Weighted sum: (x1 × w1) + (x2 × w2) + (x3 × w3) + bias

Activation: output = activation_function(weighted sum)

The activation function introduces nonlinearity — the ability to learn complex, curved decision boundaries rather than just straight lines.

Layers: Input, Hidden, and Output

Diagram 26-A — Neural Network Structure
Neurons organized into input, hidden, and output layers
INPUT LAYER      HIDDEN LAYER 1    HIDDEN LAYER 2    OUTPUT LAYER

  [x1] ───────► [N] [N] [N]                              [O1] → Cat
                      ↓ ↓ ↓                              [O2] → Dog
  [x2] ───────► [N] [N] [N] ──────► [N] [N] [N] ──────► [O3] → Bird
                      ↓ ↓ ↓
  [x3] ───────► [N] [N] [N]

       features      patterns          higher-level        prediction
                     (edges,           patterns            probabilities
                     textures)         (shapes, parts)

Diagram Questions

  1. What do the neurons in the input layer receive?
  2. What does each hidden layer add that the previous layer does not have?
  3. How does the output layer produce a final classification?

A deep neural network has many hidden layers — sometimes dozens or hundreds. Each layer learns to recognize patterns at a higher level of abstraction than the layer before it. For an image recognition network: early layers detect edges and textures; middle layers detect shapes and parts (eyes, wheels, corners); later layers recognize complex objects (faces, cars, cats). The word "deep" in deep learning simply means many layers.

Training: Learning the Weights

Weights begin as random numbers. Training adjusts them through backpropagation combined with an optimization algorithm called gradient descent:

  1. 1Feed an input through the network and get a prediction
  2. 2Compare the prediction to the correct label — compute the loss (error)
  3. 3Work backward through the network, computing how much each weight contributed to the error
  4. 4Adjust each weight slightly in the direction that reduces the error
  5. 5Repeat for millions of training examples across many epochs
Neural Network StrengthsNeural Network Weaknesses
Learn from raw inputs without hand-engineered featuresRequire very large amounts of training data
Represent extremely complex, nonlinear patternsRequire substantial computing power to train
Scale well: more data and compute tends to improve resultsInternal representations are difficult for humans to interpret
Same basic architecture applies to many problem typesCan be brittle on unusual inputs; can amplify training data bias
Section 26.8
Generative AI
Large Language Models · Image Generation · Hallucination · New Ethical Questions

Generative AI

From Recognition to Generation

All the AI systems discussed so far take an input and produce a prediction or classification. Generative AI systems do something different: they take an input — often called a prompt — and produce new content (text, images, audio, video, or code) that was not explicitly in the training data.

System TypeWhat It ProducesExample
Large language models (LLMs)Coherent text from a text promptExplanations, essays, summaries, code, dialogue
Image generation modelsImages from a text description"A lighthouse at sunset, oil painting style"
Code generation modelsFunctional code from natural language"Write a function that sorts a list by length"
Audio generation modelsSpeech, music, or sound effectsText-to-speech, music composition, sound design

Large Language Models

A large language model is a type of neural network trained on enormous amounts of text — web pages, books, articles, code, conversations — with a simple but powerful training objective: predict what word (or part of a word) comes next. Through this process, the model learns which words follow which, how topics are structured, facts and relationships embedded in the text, and patterns of reasoning and explanation.

Example 26.8.1
How a language model generates text
  • Prompt"The capital of France is"
  • ProcessThe model generates the response one token at a time, each time predicting the most likely next token given everything that came before.
  • Output"Paris"
  • Longer prompt"Explain photosynthesis in simple terms:" → The model predicts token, then next, then next — producing several explanatory sentences.
LLMs generate from learned statistical patterns, not from a lookup table. They do not "know" things the way humans do — they produce plausible continuations of text.

What LLMs Know (and Don't Know)

LLMs CanLLMs Cannot
Generate fluent, detailed text on topics well-represented in training dataLook things up in real time — they generate from learned patterns
Explain, summarize, translate, and reason about languageKnow what happened after their training cutoff without being told
Produce code, outlines, arguments, and creative writingGuarantee factual accuracy — fluency and accuracy are separate
Follow instructions and adjust tone or styleReason about consequences the way humans reason about ethics
Hallucination

The tendency of language models to generate confident-sounding but factually incorrect information is called hallucination. Models can invent citations, misstate statistics, or confidently describe events that never happened. This is one of the most important practical limitations of large language models — and a reason why LLM output should always be verified for factual claims.

New Ethical Questions from Generative AI

Sections 26.9 – 26.10
Evaluation and Responsible Use
Evaluating AI Systems · Bias, Limits, and Responsible Use

Evaluating AI Systems

Accuracy and Its Limits

The simplest evaluation metric is accuracy: the percentage of predictions the model gets correct. But accuracy can be deeply misleading, especially with imbalanced datasets.

Example 26.9.1
The class imbalance problem
  • Scenario1% of credit card transactions are fraudulent; 99% are legitimate.
  • BaselineA model that predicts "legitimate" for every single transaction will achieve 99% accuracy.
  • ProblemThis "model" catches exactly zero fraud. High accuracy completely conceals total failure at the actual task.
  • Better metricsPrecision, recall, and the confusion matrix reveal the failure that accuracy hides.

Performance Across Groups

An overall accuracy score can hide serious failures in specific subgroups. Consider a face recognition system with 94% overall accuracy. That number might mask 98% accuracy on light-skinned male faces alongside 79% accuracy on dark-skinned female faces. The system performs well on average, but very differently across demographic groups. Evaluation should always examine performance broken down by relevant subgroups.

Evaluation PrincipleWhy It Matters
Use a held-out test setHonest estimate of real-world performance; prevents overfitting from going undetected
Examine performance across subgroupsOverall accuracy can hide systematic failures for specific populations
Test edge cases and robustnessReal deployment exposes inputs very different from training data
Compare to a baselineConfirms the model adds value over a trivial alternative
Monitor after deploymentModel drift: the world changes; performance can degrade over time
Model Drift

AI systems should be monitored after deployment. Real-world data changes over time — what worked well in one year may perform poorly two years later as language, fraud patterns, medical knowledge, or user behavior evolves. Ongoing evaluation and retraining are not optional extras; they are requirements for responsible deployment.

Bias, Limits, and Responsible Use

Sources of Bias

SourceDescriptionExample
Biased training dataIf training data over- or under-represents certain groups, the model learns those imbalancesFace recognition trained mostly on light-skinned men performs worse on dark-skinned women
Measurement biasFeatures used to train may be proxies for protected characteristicsZip codes often correlate with race due to historical housing discrimination
Label biasLabels reflect human judgment, which can be inconsistent or systematically unfairMedical diagnosis labels may reflect historical underdiagnosis in certain populations
Feedback loopsA deployed system changes the data it later trains on, reinforcing initial patternsPredictive policing: more police → more arrests → more training data → same prediction
Example 26.10.1
Biased hiring: how historical data encodes injustice
  • SetupA company trains a resume-screening model on ten years of past hiring decisions. Over those years, most successful hires were male.
  • What the model learnsThe model associates male names and male-associated resume patterns with successful candidates. It is not explicitly told to discriminate — it learns the discrimination from the data.
  • ConsequenceWhen deployed, the model reproduces and potentially amplifies historical discrimination against women.
  • Key lesson"We just trained it on historical data" is not a defense against bias. Historical data can encode historical injustice.

Real-World Consequences of AI Bias

The Limits of AI Systems

LimitationWhat It Means in Practice
BrittlenessAI systems can fail dramatically on inputs that differ from their training distribution, even when the change is invisible to humans (adversarial examples)
Narrow expertiseA model trained to diagnose skin conditions does not have general medical knowledge; applying it outside its training domain can be dangerous
HallucinationLanguage models generate confident-sounding but factually wrong information; fluency and accuracy are separate properties
OpaquenessDeep neural networks are difficult to interpret; a model may produce the right output for the wrong reasons
No common senseAI systems do not understand physical reality, social context, or the consequences of their outputs the way humans do

Principles of Responsible AI Use

Transparency

Users should know when they are interacting with or affected by an AI system. Presenting AI-generated content as human-created, or AI-assisted decisions as purely human decisions, is a form of deception.

Human Oversight

High-stakes decisions — medical diagnosis, criminal justice, hiring, credit, housing — should not be made by AI systems without meaningful human review. "The algorithm decided" is not acceptable accountability.

Explainability

Where possible, AI systems used in consequential decisions should be able to explain why they produced a particular output. An applicant denied a loan or a defendant assessed as high-risk deserves an understandable reason.

Accountability

When AI systems cause harm, someone must be accountable. AI systems themselves cannot be held accountable. The humans and organizations that build, deploy, and use them bear that responsibility.

Chapter Summary

Key Terms Review

artificial intelligence
The broad field of computer science concerned with building systems that perform tasks associated with perception, reasoning, prediction, and decision support.
rule-based system
An AI system that makes decisions by applying explicit if-then rules written by human experts to inputs, using an inference engine.
machine learning
A branch of AI in which systems learn patterns from data rather than following handwritten rules.
supervised learning
Machine learning in which the training data includes both inputs and correct output labels. The most common type.
unsupervised learning
Machine learning in which the system discovers structure or patterns in data that has no labels.
reinforcement learning
Machine learning in which a system learns by taking actions in an environment and receiving feedback about whether those actions led to good or bad outcomes.
training data
The collection of labeled examples used to teach a machine learning model. Quality, size, and diversity all affect what the model learns.
model
A mathematical structure that captures patterns learned from training data and uses them to make predictions on new inputs.
parameters (weights)
The adjustable numbers stored in a model that determine how it transforms inputs into outputs. Adjusted during training to minimize error.
overfitting
When a model performs well on training data but poorly on new unseen data — having memorized examples rather than learned general patterns.
feature
A measurable property of an input used to represent it for a machine learning model. Choosing features is called feature engineering.
label
The correct output associated with a training example in supervised learning (e.g., "spam" or "not spam").
classification
A machine learning task in which the model assigns inputs to discrete categories (e.g., cat/dog, spam/not spam, benign/malignant).
regression
A machine learning task in which the model predicts a continuous numerical value (e.g., house price, temperature forecast).
confusion matrix
A table summarizing classifier predictions versus actual labels, revealing true positives, true negatives, false positives, and false negatives.
precision
Of all cases the model predicted as positive, the fraction that were actually positive. Answers: "When it says yes, how often is it right?"
recall
Of all actual positives, the fraction the model correctly identified. Answers: "Of all the real positives, how many did it find?"
neural network
A machine learning model built from many simple processing units (neurons) organized in layers, capable of learning complex patterns from data.
deep learning
Machine learning using neural networks with many hidden layers. "Deep" refers to the number of layers, not the sophistication of reasoning.
backpropagation
The algorithm used to compute how much each weight in a neural network contributed to prediction error, enabling targeted adjustments.
generative AI
AI systems that produce new content — text, images, audio, or code — from prompts, rather than classifying or predicting from fixed categories.
large language model
A neural network trained on vast amounts of text to predict likely next tokens, capable of generating fluent text on almost any topic.
hallucination
The tendency of language models to generate confident-sounding but factually incorrect information. Fluency and accuracy are separate properties.
bias (in AI)
Systematic errors or unfair patterns in AI outputs that disadvantage particular groups or misrepresent reality, arising from data, measurement, labels, or feedback loops.
model drift
The degradation of a deployed model's performance over time as real-world data changes from the distribution the model was trained on.

Diagram Review

Diagram 26-B — The Machine Learning Pipeline
From raw data to deployed model and ongoing monitoring
┌─────────────────────────────────────────────────────────────────┐
│                     MACHINE LEARNING PIPELINE                   │
│                                                                 │
│  Raw Data → Feature Engineering → Training Data                 │
│                                         │                       │
│                                         ▼                       │
│                                   Learning Algorithm            │
│                                         │                       │
│                                         ▼                       │
│                                       Model                     │
│                                         │                       │
│                         ┌───────────────┴──────────────┐        │
│                         ▼                              ▼        │
│                    Evaluation                     Deployment    │
│               (validation / test)           (new inputs arrive) │
│                         │                              │        │
│                         ▼                              ▼        │
│                  Adjust and Retrain              Predictions    │
└─────────────────────────────────────────────────────────────────┘

Diagram Questions

  1. What is the purpose of the evaluation step before deployment?
  2. Why does an arrow go back from "Adjust and Retrain" to earlier stages?
  3. What happens to the model when new inputs arrive during deployment?
  4. At which stage does feature engineering happen, and why does it come before training?

Worked Example Review

Worked Example 1
Tracing a simple classifier decision
  • SetupA classifier predicts whether a student will pass or fail based on hours studied per week and assignment completion rate. Decision rule (simplified):
    IF hours ≥ 8 AND completion ≥ 0.75 → PASS
    ELSE IF hours ≥ 12 OR completion ≥ 0.90 → PASS
    ELSE → FAIL
StudentHours/weekCompletion RateTracePrediction
Ana100.8210 ≥ 8 AND 0.82 ≥ 0.75 → both conditions metPASS
Ben60.916 < 8 (branch 1 fails); 0.91 ≥ 0.90 → branch 2 appliesPASS
Cara50.705 < 8 (branch 1 fails); 5 < 12 AND 0.70 < 0.90 (branch 2 fails)FAIL
Worked Example 2
Computing a confusion matrix and precision/recall
  • SetupA medical AI screens 200 patient scans. 120 patients actually have the condition; 80 do not. The model predicted 130 positive; of those, 110 actually have the condition.
  • Compute TP = 110 (predicted condition, actually has it) FP = 130 − 110 = 20 (predicted condition, actually does not) FN = 120 − 110 = 10 (predicted no condition, actually has it) TN = 80 − 20 = 60 (predicted no condition, actually does not)
  • Metrics Precision = TP / (TP + FP) = 110 / 130 ≈ 84.6% Recall = TP / (TP + FN) = 110 / 120 ≈ 91.7%
Interpretation: When the model predicts the condition, it is right about 85% of the time. Of all patients who actually have the condition, it catches about 92%. The 10 false negatives — missed patients — are potentially the most dangerous errors in a medical context.

Concept Check

Answer these questions before attempting the longer practice questions.

  1. What is the difference between traditional programming and machine learning?
  2. Name the three main types of machine learning and give one example task for each.
  3. What is a feature? Give three examples of features for predicting whether a movie review is positive or negative.
  4. What is the difference between the training set and the test set?
  5. What does overfitting mean? Why is it a problem?
  6. What is hallucination in the context of large language models?
  7. What is a large language model trained to do?
  8. Why is overall accuracy sometimes a misleading evaluation metric?
  9. Give two sources of bias in AI training data.
  10. What does human oversight mean in the context of AI decision-making?

Practice Questions

Section AVocabulary in Context
  1. A hospital uses a model that analyzes X-ray images to predict the likelihood of pneumonia. Identify: (a) the type of learning, (b) an example feature, (c) what the label in training data would be, and (d) what overfitting would look like for this system.
  2. A streaming service recommends movies based on a user's watch history and ratings. Is this more likely a classification system, a regression system, or neither? Explain your reasoning.
  3. Explain the difference between precision and recall in your own words. Describe a real-world scenario where high recall matters more than high precision, and another where high precision matters more.
  4. What is model drift? Describe a scenario in which a deployed AI system would experience model drift over two years.
Section BExplanation and Comparison
  1. Compare rule-based systems and machine learning systems on four dimensions: how knowledge is acquired; transparency of decisions; ability to handle variation; and how they are updated when the world changes.
  2. A company trains a facial recognition system on a dataset where 75% of photographs feature light-skinned individuals, 20% medium-skinned, and 5% dark-skinned. Predict what the confusion matrix broken down by skin tone might look like. Explain the source of the problem and propose one way to address it during training.
  3. Explain what a neural network's hidden layers do. Why are many layers useful for tasks like image recognition?
  4. Describe the difference between a classification task and a regression task. Give two examples of each.
Section CTracing and Application
  1. A classifier is given features for two loan applications. Application A: income $38,000, credit score 590, debt-to-income 0.45, defaults 2. Model outputs rejection with 88% confidence. Application B: income $38,000, credit score 720, debt-to-income 0.22, defaults 0. Model outputs approval with 79% confidence. (a) What two features appear most influential in distinguishing the decisions? (b) Should the bank deploy this model for automated loan decisions without human review? Justify your answer. (c) What information would you want to examine before trusting this model?
  2. A large language model is asked: "What is the fastest animal on land?" It responds: "The peregrine falcon can reach speeds of over 200 mph and is widely considered the fastest animal on land." (a) Identify two errors in this response. (b) What AI phenomenon does this illustrate? (c) What does this example suggest about using language models as authoritative sources?
Section DDesign and Analysis
  1. You are tasked with building a spam filter for an email system. Describe the complete machine learning pipeline: (a) what training data would you collect, (b) what features would you extract, (c) what label each training example would carry, (d) how you would evaluate the model, and (e) what kind of errors would be most costly and why.
  2. A company wants to use an AI system to screen job applications and rank candidates before human review. Describe three potential sources of bias that could affect this system, one consequence of each, and one technical and one policy measure to address it.

Debugging and Error Analysis

Error Set 1
A neural network looks up new inputs in a table of training examples and returns the closest match. This is why it needs so many training examples — the table has to cover all possible inputs.

Identify two errors in this description. Explain what actually happens during neural network inference.

Error Set 2
Our model achieves 99.2% accuracy on the test set of 10,000 transactions (80 fraudulent). We are confident it is ready for deployment.

(a) Calculate the accuracy a trivial "always predict legitimate" baseline would achieve. (b) Explain why 99.2% accuracy is not sufficient evidence of readiness. (c) What additional metrics should be reported?

Error Set 3
The overall accuracy is 94%, better than the 91% human baseline. The system clearly outperforms humans and is ready for use in law enforcement identification.

Identify three problems with this reasoning.

Design and Application Questions

Design Task 1: Hospital Readmission Risk
Feature design, bias identification, and responsible deployment
The Task

Design the feature set for a machine learning model that predicts whether a patient is at risk for hospital readmission within 30 days of discharge. List at least eight features, specify the data type of each (number, category, or Boolean), and explain why each feature might be predictive. Then identify one feature that might introduce bias and explain why.

Design Task 2: Essay Scoring Systems

You are evaluating two AI systems for automated essay scoring. System A: neural network trained on 500,000 graded essays; 87% accuracy within one grade point. System B: rule-based system counting sentence variety, vocabulary richness, transitions, and paragraph structure; 81% accuracy. (a) For which use — helping a teacher review essays quickly versus automatically assigning final grades — would each system be more appropriate, and why? (b) What two additional pieces of information would you want before recommending either system for high-stakes use?

Real-World Applications

  1. Medicine. AI systems have been developed to detect diabetic retinopathy from photographs of the retina. Describe: (a) what the training data would consist of, (b) what the features might be, (c) what the label would be, and (d) what would make this AI system useful as a screening tool in resource-limited settings.
  2. Search engines. When you type a query, multiple AI systems are working: one to understand your query, one to rank results, one to generate a direct answer. Identify two places where bias could enter this pipeline and describe a real-world consequence of each.
  3. Content moderation. Social media platforms use AI to detect content that violates their rules. Describe the classification task, the challenge of labeling training data, and two types of errors the system could make. Which type of error is more harmful — and does the answer depend on who you ask?
  4. Generative AI in education. A school allows students to use AI writing assistants for drafts but requires that final essays reflect the student's own thinking. Describe two ways a student could use generative AI responsibly and two ways that would undermine their own learning.
  5. Criminal justice. A county uses an AI risk assessment tool to help judges decide whether to grant bail. The tool predicts the likelihood a defendant will fail to appear for their court date. Describe: (a) what training data the model likely used, (b) one potential source of bias, (c) what human oversight should look like in this context, and (d) what would need to be true for this system to be used responsibly.

Mixed Review

These questions connect Chapter 26 to earlier chapters.

  1. Ch. 4 — Binary representation. A neural network stores its parameters as 32-bit floating-point numbers. A model has 175 billion parameters. Approximately how many bytes of storage are required? Express your answer in terabytes. (1 terabyte = 1012 bytes.)
  2. Ch. 12 — Efficiency. A training dataset has 50 million examples. The model trains for 3 epochs (passes through the full dataset), processing 1,000 examples per second. How many seconds does training take? How many hours?
  3. Ch. 13 — Abstraction. A large language model is described as a "black box." (a) What does this mean in the context of abstraction? (b) Why might opacity in an AI model be more problematic than opacity in a word processing application?
  4. Ch. 21 — Cybersecurity. AI systems can be attacked through adversarial examples (manipulated inputs that cause misclassification) or data poisoning attacks (corrupted training examples). Describe how each attack connects to the cybersecurity concepts of threat, vulnerability, and risk.
  5. Ch. 25 — Data science. Describe a case where a machine learning model learns a spurious correlation from training data (a correlation that appears in the data but does not reflect a real causal relationship) and explain what could go wrong when the model is deployed.
Looking Ahead
Chapter 27: Software Engineering and Team Projects

Chapter 27 introduces software engineering — the disciplined process of designing, building, testing, deploying, and maintaining software systems. Where this chapter described how AI systems are trained and evaluated, the next chapter zooms out to the entire software development lifecycle: gathering requirements, designing before coding, implementing incrementally, testing systematically, collaborating with version control, documenting for future maintainers, and managing real projects with deadlines, teams, and changing requirements. Many of the AI systems discussed in Chapter 26 are themselves complex software projects, and understanding software engineering will help you see how systems like these move from an idea to a working, maintained product.

MGU Library Connection
  • Artificial Intelligence Foundations — the specialized follow-on course covering this material in depth
  • Data Science Foundations, Chapter 25 — datasets, bias, and responsible data interpretation
  • Cybersecurity Foundations, Chapter 21 — adversarial attacks and AI system security
  • Appendix J: Data Science and AI Reference — quick reference for key terms from this chapter
  • MGU Dictionary entries: machine learning, neural network, training data, hallucination, model, bias