MGU Computer Science Series — Computer Science Foundations
Part VI: Computing in the Modern World
Data · Visualization · Statistics · Correlation · Prediction · Bias
Chapter 25 of 28
MGU Computer Science Series  ·  Computer Science Foundations  ·  Library Textbook Edition

Chapter 25:
Data Science
Foundations

Datasets, data collection, cleaning, visualization, descriptive statistics, correlation and causation, prediction, bias, and responsible interpretation — how data becomes knowledge

■ Part VI: Computing in the Modern World ■

■ 10 Sections  •  Chapter 25 of 28 ■

Follows Chapter 24: Automation, Robotics, and Embedded Systems  ·  Prepares students for Chapter 26: Artificial Intelligence and Machine Learning Foundations

Purpose and Overview

Every day, enormous quantities of information are recorded, transmitted, and stored. Hospitals record patient measurements and treatment outcomes. Retailers track purchases and browsing behavior. Weather stations measure temperature, humidity, and wind speed every few minutes. Social platforms log every post, like, and scroll. All of this recorded information is called data — but raw data does not automatically answer questions. Data science is the discipline that turns raw data into useful knowledge.

This chapter introduces data science as the study of how to collect, organize, clean, explore, analyze, visualize, model, and interpret data to answer questions, discover patterns, and support decisions. You will learn what datasets are, how data is collected and cleaned, how visualization reveals patterns, how descriptive statistics summarize data, what correlation and causation mean, how prediction works at an introductory level, how bias enters data and models, and how to interpret data responsibly.

No prior statistics or calculus is required. You should be comfortable with arithmetic, ratios, percentages, tables, and basic graph reading. This chapter prepares you for later courses in databases, data science, machine learning, and artificial intelligence.

Opening Question

A school district wants to understand which students are most at risk of falling behind in reading. They have access to attendance records, past test scores, course enrollment data, and socioeconomic indicators collected from surveys. How would you turn that data into a useful decision? What would you need to clean, measure, visualize, and watch out for? This chapter gives you the vocabulary and habits to answer those questions carefully.

10Sections
12Objectives
30+Key Terms
2Worked Examples

Learning Objectives

  1. 1Explain what data science studies and how it differs from machine learning or programming alone.
  2. 2Describe the structure of a dataset using the terms observation, feature, row, and column.
  3. 3Classify features as quantitative, categorical, ordinal, or temporal.
  4. 4Describe how data is collected, distinguish populations from samples, and identify sources of sampling bias.
  5. 5Identify and describe common data quality problems including missing values, duplicates, outliers, and inconsistent formatting.
  6. 6Select appropriate chart types and explain the principles of good data visualization.
  7. 7Calculate and interpret mean, median, mode, range, and interquartile range.
  8. 8Explain correlation, interpret a correlation coefficient, and describe what correlation does and does not tell us.
  9. 9Distinguish correlation from causation and identify confounding variables.
  10. 10Describe how prediction models are built from data and identify the risks of underfitting and overfitting.
  11. 11Identify and explain sampling bias, historical bias, measurement bias, and label bias.
  12. 12Apply principles of responsible data interpretation including honesty, limitation disclosure, and privacy.

Sections at a Glance

Sections 25.1–25.2
What Data Science Studies — and What a Dataset Is
Definition · Datasets · Features · Observations

What Data Science Studies

Data science is the study of how to collect, organize, clean, explore, analyze, visualize, model, and interpret data to answer questions, discover patterns, and support decisions. Data scientists work across medicine, business, science, government, education, journalism, sports, environmental monitoring, and many other fields.

Data science is not a single subject. It sits at the intersection of three disciplines. Computing provides the tools for storing, retrieving, processing, and programming with data. Statistics provides methods for measuring, summarizing, testing, and reasoning under uncertainty. Domain knowledge tells a data scientist which questions matter, what the data actually represents, and whether an answer makes sense.

A data scientist studying hospital readmissions needs all three: programming knowledge to work with the database, statistical reasoning about patient populations, and medical knowledge to interpret what the findings mean in practice.

What Data Science Is Not

Data science is not the same as machine learning or artificial intelligence, though all three are related. Machine learning (Chapter 26) is one technique data scientists sometimes use. Data science is the broader practice of working with data from beginning to end — collecting it, understanding it, cleaning it, summarizing it, visualizing it, modeling it, and interpreting results carefully. It is also not magic: data can be incomplete, biased, mismeasured, or simply irrelevant to the question at hand.

Data, Datasets, and Features

In computer science, data refers to recorded information — numbers, text, dates, images, audio, sensor readings, or any other representation of something in the world. Before data can be analyzed, it must be organized. The most common way to organize data for analysis is a dataset — a structured collection of related data organized as a table.

The Structure of a Dataset

A dataset table has rows, also called records or observations — each row represents one thing being studied. It also has columns, also called features, variables, or attributes — each column represents one characteristic that was measured or recorded.

Student IDAgeStudy HoursPractice Tests TakenScore
10011612378
10021720591
1003168165
10041815483
1005175054

In this dataset, each row represents one student (five observations), each column represents one feature, and the dataset has five features including the ID column. The term observation is useful because it emphasizes that each row is an observation of one real-world thing at one moment in time.

Types of Features

Feature TypeDescriptionExampleArithmetic Meaningful?
QuantitativeMeasurable numbersStudy hours, test score, temperatureYes — averages and differences make sense
CategoricalGroups or categoriesCountry, color, diagnosis (yes/no)No — adding "sophomore + junior" is meaningless
OrdinalOrdered categories, unequal spacingPain scale 1–10, satisfaction ratingPartially — rank is meaningful, spacing is not
TemporalWhen something happenedDate of visit, timestamp, durationSpecial — has direction, periodicity, and gaps
Why Feature Types Matter

Recognizing the type of each feature is one of the first steps in any data science project. The type of feature determines which operations make sense, which visualizations are appropriate, and which statistical methods apply. Treating a categorical feature like a number — for example, treating grade levels (9, 10, 11, 12) as if their differences are meaningful quantities — leads to incorrect analysis.

Practice 25.1–25.2Concept Check
  1. In your own words, explain what data science studies and how it differs from just "using a spreadsheet."
  2. A dataset records: patient name, age, blood pressure, diagnosis (hypertension / normal), pain rating (1–10), and date of last visit. Classify each column as quantitative, categorical, ordinal, or temporal.
  3. Two datasets have the same number of columns. Dataset A has 50 rows; Dataset B has 5,000,000 rows. Name two ways in which their size difference would affect how a data scientist works with each.
Sections 25.3–25.4
Data Collection and Data Cleaning
Populations · Samples · Observational Studies · Experiments · Cleaning

Data Collection

Before a dataset exists, someone must collect data. How data is collected has enormous consequences for what can and cannot be learned from it.

Methods of Collection

MethodDescriptionExample
SurveysAsking people questions and recording answersAnnual census, customer satisfaction poll
Sensors and instrumentsDevices that automatically record physical measurementsWeather stations, fitness trackers, traffic counters
Transaction recordsEvents recorded as they happenPurchases, hospital visits, web clicks
ExperimentsDeliberately varying conditions and measuring outcomesClinical drug trials, A/B website tests
Administrative recordsData from normal institutional operationsTax records, school enrollment, court records

Populations and Samples

Suppose a data scientist wants to understand the reading habits of teenagers in a country of 50 million people. It would be impossible to survey every teenager. Instead, data scientists typically study a sample — a subset of the full population of interest.

Representativeness is the key property a good sample needs. A representative sample accurately reflects the diversity of the population. A sample of teenagers from one wealthy neighborhood is not representative of all teenagers in a country. When a sample is unrepresentative, the conclusions drawn from it will not apply to the broader population — this is called sampling bias, explored further in Section 25.9.

Observational Studies vs. Experiments

ApproachDescriptionStrengthLimitation
Observational studyObserve things as they naturally occur without interventionCan study situations where experiments are impossibleCannot easily establish causation — confounders remain
ExperimentDeliberately vary one condition; randomly assign subjects to groupsRandom assignment distributes confounders equally; causation more justifiedMay be impossible or unethical in many real situations
What Gets Left Out

Data collection always involves choices about what to measure and what to ignore. A hospital dataset might record treatments but not whether patients had strong family support at home — which could also affect outcomes. What is not in a dataset is often as important as what is. A data scientist must always ask: what information is missing, and could it change the conclusions?

Data Cleaning

Real-world data is rarely perfect when collected. Before analysis, data almost always requires data cleaning — the process of finding and correcting problems so the data accurately represents what it is supposed to represent.

Data cleaning is unglamorous but essential. Experienced data scientists estimate that cleaning consumes a majority of time on most data projects. A small number of errors in a dataset can distort the results of an entire analysis.

Common Data Problems

ProblemDescriptionExamplePossible Handling
Missing valuesData was not collected for some observationsSurvey respondent skipped a questionRemove row, or impute using average of known values
Duplicate recordsSame observation appears more than onceForm submitted twiceRemove the duplicate; keep one copy
Inconsistent formattingSame value represented multiple waysDates as "2024-03-15" and "March 15, 2024"Standardize all values to one format
OutliersValue far from the typical rangeWeight recorded as 1500 kg instead of 150 kgInvestigate: genuine extreme (keep) or error (correct/remove)
Incorrect typesValues stored as wrong typeA number column stored as textConvert to the correct type
Data Cleaning Example
Cleaning a small delivery-time dataset
  • Original Customer ID | Delivery Time (min) ------------|-------------------- 2001 | 32 2002 | 28 2003 | 9999 ← sensor error 2004 | 31 2005 | ← missing 2006 | 29 2001 | 32 ← duplicate
  • ProblemsValue 9999 is clearly a sensor error. Row 2005 is missing a value. Customer 2001 appears twice — the second row is a duplicate.
  • ActionsRemove or correct 9999. Remove the missing row (or impute). Remove the duplicate row for 2001.
  • Result Customer ID | Delivery Time (min) ------------|-------------------- 2002 | 28 2004 | 31 2006 | 29
  • Why it mattersThe cleaned average is (28 + 31 + 29) / 3 = 29.3 minutes. Including the uncleaned value of 9999 would have produced a completely meaningless result.
Practice 25.3–25.4Collection and Cleaning
  1. A researcher polls 500 university students to learn about coffee consumption habits among all adults in the country. Identify one likely source of sampling bias in this study.
  2. A dataset recording student GPAs contains the value −99 in 12 rows. What type of data problem is this? What are two reasonable approaches to handling it?
  3. Explain in your own words why observational studies cannot easily establish causation but well-designed experiments can.
Section 25.5
Data Visualization
Chart Types · Selection Guide · Principles of Good Visualization

Data Visualization

Numbers alone are difficult to interpret, especially in large quantities. Data visualization is the practice of representing data graphically so that patterns, trends, outliers, and relationships become easier to see. A good visualization communicates information more efficiently than a table of numbers. A poor one obscures or distorts information.

Anscombe's Quartet — Why Visualization Matters

One of the most famous examples in data science, created by statistician Francis Anscombe in 1973, consists of four small datasets with nearly identical descriptive statistics: the same mean, variance, correlation, and regression line. Yet when plotted, the four datasets look completely different — one is linear, one is curved, one has an outlier, and one forms a vertical cluster. This demonstrates that summary statistics alone can miss important features of data. Visualization catches what numbers summarize away.

Line Charts — Trends Over Time

Line charts connect data points in sequence, usually over time. Use them when a single quantitative feature is measured at multiple ordered points. The line makes seasonal patterns, trends, and sudden changes easy to see.

Line Chart Example — Daily Average Temperature Over a Year
Temperature (°C)
35 |                    ***
30 |                 ***   ***
25 |               **         **
20 |            ***              **
15 |         ***                   **
10 |      ***                        ***
 5 | ****                                ***
   |-------------------------------------------
   Jan    Mar    May    Jul    Sep    Nov    Dec

Note: Pattern of seasonal rise and fall is immediately visible.

Bar Charts — Comparing Categories

Bar charts use rectangular bars to compare quantities across distinct categories. Use them when comparing a quantitative feature across groups.

Bar Chart Example — Average Exam Score Across Five Class Sections
Score
100 |
 90 |         █████
 80 |  █████  █████  █████
 70 |  █████  █████  █████  █████
 60 |  █████  █████  █████  █████  █████
    |  Sec A  Sec B  Sec C  Sec D  Sec E

Note: Bars make it easy to compare five groups at a glance.

Histograms — Distributions

A histogram shows how often values fall into different ranges (called bins) for a single quantitative feature. It reveals the shape of the data — whether it is symmetric, skewed, has gaps, or has multiple peaks.

Histogram Example — Distribution of Standardized Test Scores
Count
12 |        █████
10 |        █████  █████
 8 |  █████  █████  █████
 6 |  █████  █████  █████  █████
 4 |  █████  █████  █████  █████  █████
 2 |  █████  █████  █████  █████  █████  █████
   |  50-59  60-69  70-79  80-89  90-99

Note: Most scores cluster in the 70–89 range.
A bell-shaped histogram is called a "normal distribution,"
though real data does not always take this form.

Scatter Plots — Relationships Between Two Features

Scatter plots place dots on a grid where each axis represents one quantitative feature. Each dot is one observation. Use them to explore whether two numerical features are related.

Scatter Plot Example — Study Hours vs. Exam Score
Score
100 |                        •
 90 |               •    •
 80 |          •         •
 70 |     •    •    •
 60 |  •       •
 50 |  •
    |----------------------------
    0    5   10   15   20   25
         Study Hours

Note: The general upward pattern suggests students who
studied more tended to score higher — but the relationship
is not perfect. Individual variation exists even within a trend.

Pie Charts and Their Limits

Pie charts represent parts of a whole using wedge-shaped slices. They are familiar but frequently misleading. Human eyes are poor at accurately judging the sizes of different-shaped wedges, especially when slices are similar. For most purposes, a bar chart communicates the same information more accurately. Pie charts work reasonably well only when there are a small number of categories and the differences are large and obvious.

Principles of Good Visualization

PrincipleWhat It MeansCommon Violation
AccuracyThe visual should not distort the dataA y-axis not starting at zero makes small differences look dramatic
ClarityLabels, axes, and titles should be readable without guessingNo axis labels or units; illegible font sizes
HonestyThe chart should show what the data actually saysShowing only the time period where a trend looks favorable
Appropriate choiceThe chart type should match the data and the questionUsing a line chart for unordered categories; a pie chart with 15 slices
Practice 25.5Visualization
  1. For each question below, choose the most appropriate chart type and explain your choice.
    a. How has average rainfall in a city changed month by month over three years?
    b. How does average salary compare across five job titles in the same company?
    c. What is the distribution of ages in a sample of 500 survey respondents?
    d. Is there a relationship between hours of sleep and reaction time?
  2. A news article shows a bar chart where the y-axis starts at 92 instead of 0. The bars for Party A and Party B appear to differ by a factor of 4, but their actual values are 95% and 97%. What is wrong with this chart, and what would it look like if drawn honestly?
Section 25.6
Descriptive Statistics
Mean · Median · Mode · Range · IQR · Standard Deviation

Descriptive Statistics at an Introductory Level

Descriptive statistics are numerical summaries that describe the main features of a dataset. Rather than examining every row individually, descriptive statistics compress a dataset's key properties into a small number of meaningful numbers.

Measures of Center

A measure of center describes the typical or central value in a dataset.

Mean, Median, and Mode — Side by Side
Dataset: scores 78, 91, 65, 83, 54
  • Mean Add all values and divide by count.
    Mean = (78 + 91 + 65 + 83 + 54) / 5 = 371 / 5 = 74.2 The mean is sensitive to outliers. Adding a score of 0 (absent student):
    Mean = (78 + 91 + 65 + 83 + 54 + 0) / 6 = 371 / 6 = 61.8 A single extreme value drops the mean by more than 12 points.
  • Median The middle value when sorted. If even count, average the two middle values.
    Sorted: 54, 65, 78, 83, 91 Middle value (3rd of 5): 78 The median is resistant to outliers. Adding the 0:
    Sorted: 0, 54, 65, 78, 83, 91 Two middle values: 65 and 78 Median = (65 + 78) / 2 = 71.5 Median shifted only from 78 to 71.5 — a much smaller change than the mean's shift.
  • Mode The value that appears most often. Most useful for categorical data or data with repeated values. In this dataset, every value is unique — no mode. If scores were A, B, B, C, B, A, C, B — the mode would be B (appears 4 times).
SituationBetter MeasureReason
Data roughly symmetric, no extreme outliersMeanUses all values; most mathematically precise
Data contains extreme outliersMedianResistant to pull from extreme values
Income, housing prices, wealthMedianThese distributions are heavily skewed by high earners
Categorical dataModeMean and median are not meaningful for categories

Measures of Spread

Knowing the center of a dataset is not enough. Two datasets can have the same mean but very different distributions. Dataset A: 50, 50, 50, 50, 50 — mean = 50, no variation. Dataset B: 10, 30, 50, 70, 90 — mean = 50, values spread widely. A measure of spread describes how much variation exists.

MeasureHow to CalculateSensitivity to Outliers
RangeMaximum − MinimumVery sensitive — one outlier changes it completely
Interquartile Range (IQR)Q3 (75th percentile) − Q1 (25th percentile)Resistant — ignores the top and bottom 25%
Standard DeviationAverage distance of each value from the mean (roughly)Sensitive to outliers, but captures all values
Standard Deviation — Conceptual Idea

The standard deviation is a measure of how far typical values are from the mean. A small standard deviation means values cluster closely around the mean. A large standard deviation means values are spread out widely. Students who continue to statistics or data science courses will learn to compute it precisely. For now: small std dev = tightly clustered; large std dev = widely spread.

Reading a Summary Table

FeatureCountMinMaxMeanMedianStd Dev
Age5161816.8170.84
Study Hours552012.0125.52
Practice Tests5052.631.95
Score5549174.27813.7

For the Score feature: the median (78) is higher than the mean (74.2), suggesting the lower scores pull the average down. The standard deviation of 13.7 tells us that typical scores are about 13–14 points away from the mean.

Practice 25.6Descriptive Statistics
A data scientist records delivery times in minutes: 23, 31, 28, 19, 34, 27, 31, 25, 42, 22
  1. Calculate the mean. Show all steps.
  2. Sort the values and calculate the median.
  3. Find the mode and the range.
  4. The value 42 is the highest in the dataset. Recalculate the mean after removing it. What does this tell you about the mean's sensitivity to extreme values?
  5. Would you report the mean or median as the "typical delivery time" for this dataset? Why?
Sections 25.7–25.8
Correlation, Causation, and Prediction
Correlation Coefficient · Confounding Variables · Trend Lines · Overfitting

Correlation and Causation

One of the most important ideas in data science — and one of the most frequently misunderstood — is the relationship between correlation and causation. Two features are correlated when changes in one feature tend to accompany changes in another. Causation means that one thing directly produces a change in another. These are not the same.

The Correlation Coefficient

Correlation is measured by the correlation coefficient, written as r, which ranges from −1 to +1.

r valueInterpretation
+1.0Perfect positive correlation — as one increases, the other always increases proportionally
+0.7Strong positive correlation
+0.3Weak positive correlation
0.0No linear correlation
−0.3Weak negative correlation
−0.7Strong negative correlation
−1.0Perfect negative correlation — as one increases, the other always decreases proportionally

Correlation Does Not Imply Causation

Consider a famous example: cities that sell more ice cream tend to have more drowning deaths. Ice cream sales and drowning deaths are positively correlated. Does eating ice cream cause drowning? Obviously not.

The explanation is a confounding variable: hot weather. When the weather is hot, people buy more ice cream and people swim more, so more drowning deaths occur. Hot weather causes both. Ice cream and drowning are correlated not because one causes the other, but because both are caused by a third variable.

A confounding variable (also called a lurking variable) is a variable related to both the feature being studied and the outcome, creating a spurious appearance of correlation between them.

Diagram 25-C: Correlation and Causation — Four Cases
CASE 1: A causes B
         A ──────────► B
   (Correlation reflects genuine causation)

CASE 2: B causes A
         B ──────────► A
   (They're correlated, but causation runs the opposite direction
    from what was assumed)

CASE 3: A confounding variable C causes both A and B
              C
             / \
            ▼   ▼
            A   B
   (A and B are correlated but neither causes the other —
    a third variable explains both)

CASE 4: Coincidence
   (A and B happen to correlate in this dataset but have
    no real relationship — common in small datasets or
    when many correlations are tested at once)

REMEMBER: A scatter plot or correlation coefficient tells you
          whether A and B tend to vary together.
          It does NOT tell you WHY they vary together.
Worked Example
Identifying a confounding variable
  • ObservationCities with more hospitals tend to have higher rates of disease. A researcher notes a strong positive correlation between hospital count and disease rates.
  • False claim"Hospitals cause disease."
  • ConfoundPopulation size is the confounding variable. Larger cities have more people — which means more hospitals are needed and more disease cases occur in total simply because there are more people.
  • Correct interpretationWhen you look at disease rates per capita rather than total counts, the correlation may weaken or disappear. The appropriate conclusion is not "hospitals cause disease" but "larger cities have more of both because they have more people."
When Can We Claim Causation?

The strongest evidence comes from randomized controlled experiments, where researchers randomly assign subjects to a treatment group or a control group. Random assignment distributes confounding variables equally between groups, so differences in outcomes can be attributed to the treatment. Where experiments are impossible or unethical, scientists use careful observational studies, multiple independent datasets, and accumulated evidence over time. A correlation in data is a clue worth investigating — not a conclusion.

Prediction

One of the most powerful uses of data science is prediction — using patterns found in historical data to estimate unknown or future values. The feature being predicted is called the target or label. The features used to make the prediction are called inputs or predictors.

Inputs (known features)Target (to be predicted)
Study hours, practice tests takenExam score
Patient age, weight, symptomsDiagnosis
Historical temperature, humidityTomorrow's weather
Transaction amount, time, locationFraud or not fraud
House size, location, ageSale price

Linear Prediction — Trend Lines

For two quantitative features with a linear relationship, prediction can be done with a trend line (also called a line of best fit or regression line). The trend line passes through the scatter plot in the direction that best represents the overall relationship.

If the trend line for study hours and scores gives an equation like Predicted score ≈ 45 + 2.5 × (Study Hours), then for a student who studied 16 hours: Predicted score ≈ 45 + 2.5 × 16 = 85. This is an estimate — not a guarantee. A student who studies 16 hours might actually score 79 or 92.

Underfitting and Overfitting

ProblemDescriptionEffect
UnderfittingModel is too simple to capture real patternsPerforms poorly on both training data and new data
OverfittingModel learns the training data too precisely, memorizing noise instead of patternsPerforms well on training data but fails on new data
Good fitModel captures real patterns without memorizing random variationPerforms well on both training data and new data
Prediction Is Not Certainty

Even a good prediction model produces estimates, not guarantees. Presenting model outputs as certainties is one of the most common and harmful mistakes in data science communication. A model that predicts a 73% chance of hospital readmission means exactly that — a 73% probability, not a guaranteed outcome.

Practice 25.7–25.8Correlation, Causation, and Prediction
  1. A study finds that students who own more books score higher on standardized reading tests. Correlation coefficient r = +0.71.
    a. Describe in plain English what this correlation means.
    b. Does owning more books cause higher test scores? Propose one possible confounding variable.
    c. What type of study would provide stronger evidence that book ownership causes better reading outcomes?
  2. A trend line for a dataset of apartment sizes (sq ft) and monthly rent produces the equation: Predicted rent ≈ 800 + 1.2 × (sq ft). Predict the rent for an apartment of 650 sq ft. Is this prediction guaranteed to be correct? Why or why not?
  3. A model trained on historical test data achieves 99% accuracy on that data but only 58% on a separate set of new exam questions. What modeling problem has occurred, and what should the data scientist do?
Sections 25.9–25.10
Bias and Responsible Interpretation
Types of Bias · Recognizing Bias · Honest Reporting · Privacy

Bias in Data

Data science can produce conclusions that are unfair, inaccurate, or harmful when the data itself — or decisions made about it — introduce bias. Bias in data science refers to systematic errors that skew results in a consistent direction.

Type of BiasHow It ArisesExample
Sampling biasThe sample does not represent the intended populationA medication study conducted only on men whose findings do not apply to women
Historical biasTraining data accurately reflects the past, but the past was unfairA hiring algorithm trained on historical decisions learns to reject women in technical roles because fewer were historically hired
Measurement biasThe process of collecting data produces systematic errorsA face-detection system trained mostly on lighter-skinned faces performs poorly on darker-skinned faces
Label biasLabels in training data reflect biased human judgmentsA recidivism prediction model trained on data where some judges were systematically harsher toward certain groups
Confirmation biasThe analyst focuses on patterns that support preexisting beliefsReporting only findings that support a preferred teaching method, ignoring contradictory evidence in the same dataset
Historical Bias Is Especially Difficult

Historical bias is particularly hard to address because the data is technically accurate — it really does reflect what happened. The problem is that what happened was unfair. A system that learns from historical patterns and replicates them is not "neutral" just because it is based on real data. Data encodes the choices, inequalities, and judgments of those who collected it.

Recognizing and Addressing Bias

Recognizing bias requires asking careful questions at every stage of a project. Who collected this data, and who is represented — and who might be missing? Does the training data reflect historical patterns that should not be perpetuated? Could the measurement process systematically favor certain groups? Are the labels produced by reliable, unbiased judgments? Am I looking for evidence that challenges my assumptions, or only evidence that supports them?

No dataset or analysis is perfectly free of bias. Responsible data science involves making bias visible, addressing it where possible, and being honest about its effects on conclusions.

Responsible Data Interpretation

Data science has significant power to influence decisions — in medicine, criminal justice, hiring, education, and finance. With that power comes responsibility.

Principles of Honest Interpretation

PrincipleWhat It Means
Report the full pictureDo not select only results that support a preferred conclusion. Report what the data shows overall, including inconvenient findings.
Distinguish statistical from practical significanceA 0.2-point average score difference might be statistically detectable in a huge dataset but have no practical meaning for real decisions.
State limitations clearlyEvery analysis has limitations: unrepresentative samples, missing variables, models that may not generalize. Stating these is not weakness — it is honesty.
Separate description from prescriptionDescribing what data shows is different from recommending what to do. Decisions require values, context, and judgment that data alone cannot supply.

Privacy and Consent

When data involves people, ethical responsibilities include privacy — data about individuals should be collected and used in ways that protect them. Even data that seems anonymous can sometimes be re-identified when combined with other information. This is called re-identification and is a serious privacy risk.

Consent means people should know what data is being collected about them and have meaningful choices about how it is used. Data minimization — collecting only the data needed for a specific purpose — reduces the risk of misuse or breach.

Diagram 25-A: The Responsible Data Science Workflow
[1] DEFINE THE QUESTION
     What do we want to know?
     What decision will the analysis support?
          │
          ▼
[2] CONSIDER ETHICAL OBLIGATIONS
     Who is affected? What are our responsibilities to them?
          │
          ▼
[3] COLLECT DATA
     Surveys, sensors, records, experiments
     Prioritize representativeness and informed consent
          │
          ▼
[4] CLEAN DATA
     Handle missing values, duplicates, formatting errors
     Document all changes and why they were made
          │
          ▼
[5] EXPLORE AND VISUALIZE
     Summary statistics, charts, distributions
     Look for patterns, outliers, anomalies, and sources of bias
          │
          ▼
[6] ANALYZE AND MODEL
     Correlation, prediction, classification
     Evaluate for bias and generalization to new data
          │
          ▼
[7] INTERPRET AND COMMUNICATE
     Report findings, limitations, and uncertainty honestly
     Distinguish what data shows from what should be done
          │
          ▼
[8] INFORM DECISIONS
     Data is one input — not the only one
     Values, context, and human judgment also matter

Note: Steps are often revisited. Analysis may reveal the need
to collect more data or reconsider the original question.
Practice 25.9–25.10Bias and Responsibility
  1. A company trains a loan-approval model on 10 years of historical data from a bank that historically approved loans at different rates for different demographic groups.
    a. What type of bias is likely to appear in this model?
    b. What might happen if the model is deployed without addressing this bias?
    c. Name two steps the data science team could take to investigate and reduce the bias.
  2. A hospital uses a model to predict which patients are likely to be readmitted within 30 days. A doctor tells a patient: "The computer says you'll be back in the hospital next month." What is wrong with the doctor's statement, and how should the prediction be communicated instead?
  3. A research team anonymizes a dataset by removing names and ID numbers before sharing it publicly. A colleague warns that this may not be enough to protect privacy. What risk is the colleague describing, and why does removing names not fully solve it?

Chapter Summary

Key Terms Review

bias
A systematic error that consistently skews data or analysis in a particular direction, causing inaccurate or unfair conclusions.
categorical feature
A feature representing groups or categories, not numerical quantities. Arithmetic on categorical features is usually not meaningful.
confounding variable
A variable related to both a feature being studied and an outcome, creating a misleading appearance of a direct relationship. Also called a lurking variable.
correlation
A statistical relationship where changes in one feature tend to accompany changes in another, measured by the correlation coefficient r (−1 to +1).
data cleaning
The process of finding and correcting errors, missing values, and inconsistencies in a dataset before analysis.
data science
The discipline that uses data, computing, statistical reasoning, and domain knowledge to answer questions, discover patterns, and support decisions.
dataset
A structured collection of related data, typically organized as a table of observations (rows) and features (columns).
descriptive statistics
Numerical summaries that describe the main features of a dataset, including measures of center and spread.
feature
A column in a dataset representing one characteristic measured for each observation. Also called a variable or attribute.
histogram
A chart showing the distribution of a single quantitative feature by grouping values into bins and showing observation counts per bin.
historical bias
Bias that occurs when training data accurately reflects historical patterns that are unfair and should not be replicated in future systems.
imputation
Filling in missing values using a reasonable estimate, such as the mean or median of the known values in that feature.
IQR
Interquartile range — the difference between Q3 (75th percentile) and Q1 (25th percentile). Resistant to outliers.
mean
The arithmetic average: sum of values divided by count. Sensitive to outliers; pulled by extreme values.
median
The middle value in an ordered dataset. Resistant to outliers; preferred when data is skewed.
mode
The value appearing most often in a dataset. Most useful for categorical data or data with repeated values.
observation
A single row in a dataset representing one instance of the thing being studied. Also called a record.
outlier
A value far from the typical range. May represent a genuine extreme or a data collection error; must be investigated before deciding how to handle it.
overfitting
A modeling problem where a model learns training data too precisely, capturing noise instead of real patterns and failing to generalize to new data.
population
The complete group a data scientist wants to learn about. Samples are drawn from populations.
prediction
Using patterns in historical data to estimate unknown or future target values from input features.
quantitative feature
A feature representing a measurable number. Arithmetic operations are meaningful. Examples: height, temperature, score.
range
Maximum value minus minimum value. The simplest measure of spread; very sensitive to outliers.
re-identification
Combining supposedly anonymous data with other sources to identify specific individuals. A serious privacy risk even after names are removed.
sample
A subset of the population actually studied. Must be representative to produce conclusions that generalize.
sampling bias
Bias occurring when a sample does not represent the intended population, skewing results toward over-represented groups.
scatter plot
A chart placing dots on a grid where each axis is a quantitative feature and each dot is one observation, used to explore relationships.
standard deviation
A measure of how far typical values are from the mean. Small = tightly clustered; large = widely spread.
target
The feature a prediction model estimates. Also called the label or outcome.
trend line
A line drawn through a scatter plot representing the direction and strength of the relationship between two features. Used for simple prediction. Also called line of best fit or regression line.
underfitting
A modeling problem where a model is too simple to capture real patterns, performing poorly on both training and new data.

Worked Example Review

Worked Example 25-1
Calculating Descriptive Statistics
  • DatasetDelivery times (minutes) after cleaning: 23, 31, 28, 19, 34, 27, 31, 25, 42, 22
  • Mean Sum = 23+31+28+19+34+27+31+25+42+22 = 282 Count = 10 Mean = 282 / 10 = 28.2 minutes
  • Median Sorted: 19, 22, 23, 25, 27, 28, 31, 31, 34, 42 Even count — average the 5th and 6th values: Median = (27 + 28) / 2 = 27.5 minutes
  • Mode31 appears twice — all others appear once. Mode = 31 minutes
  • Range42 − 19 = 23 minutes
  • InterpretThe mean (28.2) is slightly higher than the median (27.5), suggesting the value 42 pulls the average upward. A data scientist should investigate whether 42 minutes is a genuine extreme or an error in this context.
Mean: 28.2 min · Median: 27.5 min · Mode: 31 min · Range: 23 min
Worked Example 25-2
Identifying Correlation vs. Causation
  • FindingA researcher analyzes city-level data and finds that cities with more hospitals have higher rates of disease. Strong positive correlation is observed.
  • False claim"Hospitals cause disease." This is a causal claim made from a correlation without ruling out confounders.
  • ConfounderPopulation size. Larger cities need more hospitals and have more disease cases in total — simply because they have more people. Both are effects of the same cause.
  • Correct approachExamine disease rates per capita. Examine what happens to disease rates when hospital capacity changes over time in specific communities. Control for other variables (poverty, age demographics, pollution). Even then, establishing causation from observational data is difficult.
Correlation is real. Causation is not supported. Population size is the confounding variable.

Concept Check

  1. What is a dataset? Describe its basic structure using row, column, observation, and feature.
  2. Classify each column as quantitative, categorical, or ordinal: (a) GPA; (b) enrollment status (full-time / part-time); (c) year in school (first / second / third / fourth); (d) number of absences.
  3. A researcher surveys 500 university students about their coffee habits to learn about all adults in the country. Is this sample likely to be representative? Why or why not?
  4. What is a missing value? Give one example of how missing values might arise in a patient health dataset.
  5. A dataset has these values: 4, 5, 6, 7, 7, 8, 9, 100. Calculate the mean and median. Which is more representative of the typical value?
  6. Two features have a correlation coefficient of r = −0.82. In plain English, what does this mean?
  7. Countries with higher chocolate consumption per capita have more Nobel Prize winners per capita. Does eating chocolate help win Nobel Prizes? What is the more likely explanation?
  8. A company trains a resume-screening model on 10 years of historical hiring data, during which it hired mostly men in technical roles. What type of bias is likely to appear?
  9. A model predicts a 73% chance of hospital readmission. A doctor tells the patient: "The computer says you'll be back in a month." What is wrong with this statement?
  10. What is re-identification, and why does removing names from a dataset not fully protect privacy?

Practice Questions

Part AVocabulary and Identification
  1. Match each feature to its type (quantitative, categorical, ordinal, or temporal):
    • Temperature in Celsius; customer satisfaction (1–5 stars); country of birth; height in cm; education level (no diploma / high school / college / graduate); date of purchase
  2. A dataset contains 1,000 job applications. The "Years of Experience" column has 47 rows with a value of −1. What type of data problem is this? Describe two reasonable approaches to handling it.
  3. For each chart type, name one situation where it is the most appropriate choice: (a) line chart; (b) bar chart; (c) histogram; (d) scatter plot.
Part BCalculation
  1. Five employees spend the following hours per week in meetings: 8, 12, 6, 14, 10.
    a. Calculate the mean and median.
    b. Find the range.
    c. A sixth employee is added with 52 hours per week. Recalculate the mean. Does the median change significantly? What does this illustrate?
  2. Compare two classes on a reading test:
    Class A: 72, 74, 75, 73, 76
    Class B: 50, 60, 78, 90, 92
    a. Calculate the mean for each class.
    b. Calculate the range for each class.
    c. Which class has higher average performance? Which has more variation? What might a teacher conclude?
  3. A scatter plot of hours of sleep (x) versus reaction time in milliseconds (y) produces r = −0.74.
    a. Describe this correlation in plain English.
    b. Does sleeping less cause slower reaction times? What additional evidence would strengthen that claim?
    c. Sketch a rough scatter plot that would produce r ≈ −0.74.
Part CCorrelation and Causation
  1. For each claim, identify whether it is a causal claim or a correlational claim. If correlational, propose one possible confounding variable.
    a. "Students who eat breakfast score higher on morning tests."
    b. "Increasing the minimum wage causes unemployment to rise."
    c. "Cities with more green space have lower rates of childhood asthma."
    d. "Random assignment to a new drug reduced recovery time by 3 days compared to the placebo group."
  2. A data scientist finds that buses on Route 12 are late more often than on other routes. She concludes: "Route 12 needs better drivers." What assumption is this making? What other features might explain the delays? What additional data would help determine the true cause?

Debugging and Error Analysis

Error 1 — Data Cleaning
A data scientist reports mean delivery time as 147 minutes; other analysts find 29 minutes after cleaning.

What type of data problem most likely explains the discrepancy? What should the data scientist have done before computing the mean?

Error 2 — Misleading Visualization
A bar chart comparing three schools' test scores (97, 98, 99) uses a y-axis starting at 95. School C's bar appears 3× as tall as School A's.

What is wrong with this chart? How does the y-axis choice affect the viewer's perception? What would the chart look like if drawn honestly?

Error 3 — Causation Claim
"Ice cream sales are strongly correlated with violent crime (r = +0.78). We recommend restricting ice cream sales to reduce crime."

Identify two errors in reasoning in this recommendation. What is the likely confounding variable?

Error 4 — Overfitting
A prediction model achieves 98% accuracy on training data but only 61% accuracy on a separate test set.

What problem has occurred? What does it mean, and what should the data scientist do?

Error 5 — Sampling Bias
A researcher surveys 1,000 readers of a fitness magazine about weekly exercise and concludes: "Most adults exercise at least 5 days per week."

Identify the flaw in this conclusion. What population does the sample actually represent?

Design and Application Questions

  1. A school district wants to understand factors that predict student success in standardized reading tests. Design a dataset for this study: (a) What would each row represent? (b) List six features you would include and classify each. (c) Identify two features that might be difficult to measure and explain why. (d) Describe one potential source of bias.
  2. You are given a dataset of 10,000 restaurant inspections including: restaurant name, neighborhood, type of cuisine, score (0–100), number of violations found, date of inspection, and whether the restaurant was open or closed at the next inspection. Choose one question this dataset could help answer and describe: (a) which features you would use; (b) what visualization would help; (c) what descriptive statistics would be relevant; (d) one important limitation.
  3. Sketch a responsible data science workflow for this project: A city wants to predict which neighborhoods are most likely to flood during heavy rain, to prioritize infrastructure maintenance. For each step, identify one decision the team must make and one ethical question they should consider.

Real-World Applications

  1. Search engines rank results using models trained on historical user clicks. (a) What type of bias might appear if some user groups are over-represented in the historical data? (b) Why might popular results keep getting more popular even if they are not the most accurate? (c) What would "fairness" mean in a search ranking context?
  2. A hospital uses a model to predict which emergency room patients are most likely to return within 72 hours. High-risk patients receive a follow-up call. (a) What features might this model use? (b) What would it mean if the model performed well on average but poorly for patients over age 80? (c) What are the ethical implications of using a biased model in this context?
  3. A news organization polls 1,200 voters by calling landline phone numbers to predict an election. (a) What sampling bias might affect this poll? (b) How might this bias affect the predictions? (c) What steps could the pollsters take to reduce this bias?

Mixed Review

These questions revisit concepts from earlier chapters.

  1. (Chapter 4) A dataset stores student ages as 8-bit unsigned integers. What is the maximum value that can be stored? Would this be sufficient for a dataset of high school and college students?
  2. (Chapter 12) A dataset of 1,000,000 customer records is sorted by customer ID. A data scientist needs to find a specific customer ID. Compare linear search versus binary search: how many steps does each require in the worst case?
  3. (Chapter 14) What is a CSV file, and why is CSV format commonly used for sharing datasets between different software tools?
  4. (Chapter 18) A database has two tables: one with patient records (patient ID, name, age, diagnosis) and one with prescription records (prescription ID, patient ID, medication, dose, date). A data scientist wants to analyze the relationship between patient age and prescribed medication. In plain English, what SQL operation would be needed to combine these two tables, and why?
  5. (Chapter 22) A data science team removes all names and ID numbers from a dataset before sharing it publicly. A colleague warns that this may not be enough to protect privacy. Who is correct, and why?

Chapter 25 Checkpoint

Chapter 25 Checkpoint
Complete without assistance — assesses all key skills and concepts from Chapter 25
Section 1 — Vocabulary and Concepts
  1. Define data science and explain why it requires more than just computing skills.
  2. Describe the structure of a dataset. What do rows and columns represent?
  3. Explain the difference between sampling bias and historical bias. Give one example of each.
Section 2 — Data and Statistics
  1. A dataset records: employee ID, department, years at company, annual salary, and performance rating (poor/fair/good/excellent). Classify each feature as quantitative, categorical, ordinal, or temporal.
  2. A dataset of annual salaries has values: $42,000 / $45,000 / $48,000 / $51,000 / $310,000. Calculate the mean and median. Which better represents typical salary? Why?
  3. Identify all data problems in this excerpt and explain how you would address each: ID | Salary | Department ---|---------|---------- 01 | 45000 | Marketing 02 | 9999999 | ← ? 03 | | Finance 01 | 45000 | Marketing
Section 3 — Visualization and Analysis
  1. You want to show how monthly sales figures have changed over two years. Which chart type would you choose and why?
  2. A scatter plot of hours studied and test scores has r = +0.68. What does this tell you? Does it prove that studying causes higher scores?
  3. A data scientist reports: "Neighborhoods with more fire stations have more house fires." What is the most likely confounding variable? What would be the incorrect conclusion to draw?
Section 4 — Prediction and Bias
  1. A trend line for apartment size (sq ft) and monthly rent gives: Predicted rent = 700 + 1.5 × (sq ft). Predict the rent for 800 sq ft. Is this guaranteed to be correct?
  2. A model trained to screen job applications performs with 95% accuracy on historical data but flags women-led companies at 3× the rate of men-led companies. What type of bias is this? What should the team do?
  3. A model achieves 97% accuracy on its training set and 54% on a new test set. What problem has occurred? What does it mean for using this model in practice?
Section 5 — Responsible Interpretation
  1. A study finds that red wine drinkers have lower rates of heart disease. The report concludes: "Drink red wine to protect your heart." List three limitations the report should have mentioned before making this recommendation.
  2. A hospital anonymizes patient data by removing names and birth dates, then shares it with a research partner. A privacy expert warns that re-identification is still possible. Explain why.
Looking Ahead
Chapter 26: Artificial Intelligence and Machine Learning Foundations

Chapter 25 built the foundation of data thinking: how to collect, clean, visualize, summarize, and interpret data. Chapter 26 extends these ideas into artificial intelligence and machine learning — systems that learn patterns from data to make predictions, classify inputs, generate content, and support complex decisions.

You have already encountered the core ideas that make machine learning possible: datasets of observations and features, the concept of a model trained on examples to predict new ones, the challenge of avoiding both overfitting and underfitting, and the critical importance of bias in training data. Chapter 26 will show how these ideas are assembled into real AI systems — and what it means to evaluate, trust, and responsibly use them.

MGU Library Connection
  • Data Science and AI Reference — Appendix J of this textbook
  • Files, Tables, and Data Processing — Chapter 14 of this textbook
  • Databases and Information Systems — Chapter 18 of this textbook
  • Privacy, Identity, and Digital Safety — Chapter 22 of this textbook
  • MGU Data Science Foundations (standalone course) — requires Computer Science Foundations
  • MGU Artificial Intelligence Foundations (standalone course) — requires Computer Science Foundations and Data Science Foundations