Guide to AI and Data Courses · Lecture Notes

Chapter 26: Data Science

A retail chain wants to know whether the new checkout screen in its mobile app increases sales. It has a table of users in which some cells are empty, some values are impossible, and the numbers for the two screens are close to each other. Data science is the course about carrying a question like this from data to a decision: putting the data in order, coping with what is missing, looking at it to get to know it, and then honestly testing whether a difference could be chance. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.

Learning outcomes

Question and process
Turn a business question into one that can be settled by a decision and a metric; list the steps of the data science process.
Tidy and missing data
Reshape a table into tidy form; tell the kinds of missing values apart and compute how simple imputation changes the result.
Exploratory analysis
Apply the five-number summary and the interquartile-range rule by hand; explain with Anscombe's quartet why we must look at plots.
Inference
Compute and interpret the z statistic, p-value and confidence interval for a difference of two proportions in an A/B test.
Place of the course
State how data science relates to machine learning, data mining, statistics and big data systems.

26.1What question does the course ask?

How do we ask the right questions of data and turn the answers into decisions?

Data science is the process that starts with a question and covers finding, cleaning and analyzing data, then communicating the result so that it leads to a decision. It combines statistics, programming and domain knowledge; data mining and machine learning are its tools.

In data science the work starts from a question, not from data. "Did the new checkout screen increase sales?" is a business question; to make it answerable with data we have to name the metric (checkout completion rate), the comparison (old screen versus new screen) and the decision (should the new screen be released to everyone?). The more vague the question, the more likely even the best model is to answer the wrong thing.

Once the question is sharp the process follows a familiar order: get the data, clean it, explore it, model or test, and communicate the result. In practice most of the time goes into the first three steps, because real data is incomplete, inconsistent and usually collected for another purpose. The course therefore teaches less about building models than about knowing what the data says and what it cannot say.

26.1.1What sets the course apart

Data science stands one step back from machine learning, which aims to maximize predictive performance, and from data mining, which looks for patterns in large data: what matters is not the model itself but the decision it supports. That is why the course asks "could this difference be chance?", "whom does this data represent?" and "is this chart telling the truth?" more often than it asks about the details of an algorithm.

26.1.2At a glance

CriterionData Science
Approachquestion, data, analysis, story
Inputraw, messy data
Outputreport, visualization, model
Success measureimpact on decisions, accuracy
Math loadmedium: statistics
Data needsmoderate to large

26.2A short history

YearMilestone
1962In "The Future of Data Analysis", Tukey argues for data analysis as a science separate from statistics.
1977Tukey publishes "Exploratory Data Analysis": look first, then model.
2001Cleveland proposes "data science" as an academic field that extends statistics.
2010Kaggle is founded; data science competitions and open datasets spread.
2012Harvard Business Review calls data scientist "the sexiest job of the 21st century".
2014Project Jupyter splits from IPython; code, plots and text meet in one notebook.

26.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Defining the questionWhat do we want to know, and what decision will follow?
Tidy dataEach row an observation, each column a variable.
Data cleaningFixing missing, wrong and inconsistent records.
Exploratory analysisGetting to know data with summaries and plots.
VisualizationShowing the pattern and result with the right chart.
Hypothesis testingChecking whether a difference is due to chance.
A/B testingComparing two options with a randomized experiment.
ReproducibilityGetting the same result again with code, data and versions.

26.4Tidy data and missing values

Before any analysis the table must have the right shape. In tidy data every variable is a column, every observation is a row, and every type of measurement has its own table. A "wide" table that keeps each month of sales in its own column suits most tools badly; the "long" form, which makes the month a column too, makes both grouping and plotting easy.

Wide (untidy)Long (tidy)
Store | Jan | Feb
A | 10 | 12
B | 8 | 9
Store | Month | Sales
A | Jan | 10
A | Feb | 12
B | Jan | 8
B | Feb | 9

After tidiness, the first problem is missing values. Why a value is missing decides what can be done about it. Three cases are distinguished. If values are missing at random (missing completely at random, MCAR; say a sensor switches off now and then), dropping the rows with gaps does not bias the result, it only shrinks the data. If missingness depends on another observed variable (missing at random, MAR), methods that account for that variable are needed. If missingness depends on the value itself (missing not at random, MNAR; high earners leave the income question blank), the information is simply not in the data and simple methods give wrong answers.

Example 26.1: Missing answers to an income question

8 households are asked for their monthly income (thousand TL, values are illustrative). Six answer: 20, 22, 25, 28, 30, 35. Two leave it blank; their true values, learned later, are 60 and 90 (the high earners did not answer).

  1. Complete-case analysis. Drop the missing rows: mean 160/6 ≈ 26.7, standard deviation ≈ 5.5.
  2. The truth. The mean of all eight is 310/8 = 38.75, the median 29, the standard deviation ≈ 24.2. The complete-case mean was about 12 thousand TL too low.
  3. Mean imputation. Fill both gaps with 26.7. The mean stays 26.7 (the bias remains) and the standard deviation drops to ≈ 4.6: the data looks less variable than it is.
  4. Conclusion. Because the missingness is MNAR, neither dropping nor mean imputation fixes it; the problem has to be addressed at data collection.

The general rule for missing values is to ask first why they are missing, then choose a method, and show how much the choice changes the result. Median imputation, group-wise imputation and multiple imputation exist; none of them brings back information that is not in the data.

Common mistake

"Cleaning" missing values by silently deleting them or filling them with the mean, and then computing the standard deviation or a confidence interval as if the data were real observations. Imputed values are not observations; the sample looks larger and less variable than it really is.

26.5Exploratory analysis and visualization

Exploratory data analysis means looking at the data with summary numbers and plots before moving to a model or a test. Tukey's principle: look first, then model. The first tool is the five-number summary: the minimum, the first quartile Q1, the median, the third quartile Q3 and the maximum. The mean and standard deviation are strongly affected by extreme values; the median and the quartiles are not.

Definition 26.1 (The interquartile-range rule)

The interquartile range is IQR = Q3 − Q1. In a box plot, values below Q1 − 1.5·IQR or above Q3 + 1.5·IQR are flagged as candidate outliers. A candidate is not deleted until it is shown to be an error.

Example 26.2: The effect of one outlier

Basket totals of nine customers (TL, values are illustrative): 12, 14, 15, 15, 16, 18, 19, 21, 95.

  1. Median. Of nine sorted values the median is the fifth: 16.
  2. Quartiles. The median of the lower half (12, 14, 15, 15) is Q1 = 14.5; the median of the upper half (18, 19, 21, 95) is Q3 = 20. IQR = 5.5.
  3. Fences. 14.5 − 8.25 = 6.25 and 20 + 8.25 = 28.25. 95 lies far outside: a candidate outlier.
  4. Mean. 225/9 = 25; without 95 it is 130/8 = 16.25. The median moves from 16 to 15.5. One value shifted the mean by 8.75 TL and the median by 0.5 TL.

The 95 TL basket may be a data entry error, or it may be the most valuable customer. The decision comes from knowing the data, not from the arithmetic.

Summary numbers are not enough; very different data can produce the same numbers. The classic demonstration is the quartet F. Anscombe published in 1973: four small datasets (11 points each) with almost identical summary statistics.

SetMean of xMean of yVariance of yCorrelation rLineIn a plot
I9.07.504.130.816y = 3.0 + 0.5xscattered but linear
II9.07.504.130.816y = 3.0 + 0.5xa perfect curve
III9.07.504.120.816y = 3.0 + 0.5xon a line, with one outlier
IV9.07.504.120.817y = 3.0 + 0.5xx is always 8, one point at 19

The same line, the same r, the same means; yet a linear model makes sense only for the first set. In the second the line has the wrong shape, in the third removing one point changes the line, and in the fourth a single point determines the slope. This is why a plot is part of the analysis, not decoration.

26.5.1Choosing the right chart

The choice depends on the question. Use a histogram or box plot for the distribution of one variable, a scatter plot for the relationship between two numeric variables, a line chart for change over time and a bar chart to compare categories. The axis of a bar chart must start at zero; a truncated axis makes a small difference look large.

Common mistake

Looking only at the correlation coefficient and the mean and saying "I examined the data". The four sets above give the same summaries; none of them reveals that the second set is a curve or that the fourth hangs on a single point.

26.6A/B testing and inference

The most reliable way to compare two options is a randomized experiment. In an A/B test users are split at random into two groups; one sees the old screen (A), the other the new one (B), and the same metric is measured. Because random assignment evens out other differences between the groups on average, the measured difference comes from the option; the mere observation that "people who see the new screen buy more" cannot say that. One question remains: could the observed difference be chance? A hypothesis test answers it. The underlying probability and sampling distributions belong to Probability and Statistics; here they are only used.

Definition 26.2 (The z test for two proportions)

Null hypothesis: both screens have the same conversion rate. Pooled rate p = (xA + xB)/(nA + nB); standard error SE = √(p(1 − p)(1/nA + 1/nB)); z = (p̂B − p̂A) / SE. The two-sided p-value is the probability of a value farther out than |z| under the standard normal distribution.

Example 26.3: The same difference, two sample sizes

The new screen seems to convert better than the old one (the values are illustrative). First each screen is shown to 200 users: 20 complete the purchase in A, 32 in B.

  1. Rates. p̂A = 20/200 = 0.10, p̂B = 32/200 = 0.16; difference 0.06.
  2. Pooled rate. p = 52/400 = 0.13.
  3. Standard error. SE = √(0.13·0.87·(2/200)) ≈ 0.0336.
  4. z and p. z = 0.06/0.0336 ≈ 1.78; two-sided p ≈ 0.074. Not significant at the 5% level.
  5. Confidence interval. The 95% interval for the difference is 0.06 ± 1.96·0.0335 (here the standard error is computed from each group's own rate) ≈ (−0.006, 0.126): the difference could be anywhere from −0.6 to +12.6 points, zero included.

Had the same rates been seen with 1000 users per group (100 and 160 conversions): SE ≈ 0.0150, z ≈ 3.99, p ≈ 0.00007, and the 95% interval is about (0.031, 0.089). The effect size is the same, the evidence much stronger: the larger the sample, the less the same difference looks like chance.

The first result does not say "the new screen is worse" or "there is no difference"; it says only that nothing firm can be claimed from this data. The confidence interval says more than the p-value, because it also shows how large the effect could be. To decide, this size has to be read together with the cost of the change; even a small but certain difference may not repay the cost of replacing the screen.

Common mistake

Re-running the test every day and stopping the first time p < 0.05. This "peeking" pushes the false-positive rate far above 5%. The sample size and the stopping time are fixed before the experiment; if many metrics and subgroups are tried on the same data (p-hacking), something is bound to come out "significant".

26.7How is the course taught?

26.7.1A typical workflow

Askdecision andmetricGet dataSQL, files,APICleanmissing, wrong,inconsistentExplore andmodelplots, tests,regressionCommunicatereport,dashboard
Figure 26.1: A typical workflow in Data Science

A city council asks, "Should we add more bus trips?" Card tap records are collected, bad timestamps removed, occupancy by line and hour explored with plots, demand estimated with regression, and the result presented to the decision maker in a one-page report.

26.7.2Topics over the semester

  1. The data science process and asking good questions
  2. Reading data in Python or R; tidy data
  3. Data cleaning: missing values and outliers
  4. Exploratory data analysis
  5. Principles of visualization
  6. Sampling and descriptive statistics
  7. Confidence intervals and hypothesis tests
  8. A/B testing and experimental design
  9. Regression and predictive models
  10. Correlation, causation, confounders
  11. Getting data from a database: SQL
  12. Reproducible reports and telling the story

This is a typical semester; the order and coverage vary between universities.

26.7.3Skills you will gain

  • pandas or the tidyverse
  • SQL
  • Matplotlib and seaborn
  • interpreting hypothesis and A/B tests
  • reproducible reports in Jupyter

26.7.4Try it yourself

The Try It: What Drives Grades? slide in the presentation lets you solve a typical problem of this course yourself: The school asks: “Which habit should we advise students on?” We have survey and grade data for 26 students. Pick variables to see the relationship; click a point to drop it from the analysis.

26.8Are you ready for this course?

26.8.1Prerequisites

CourseWhy it is needed
Probability and Statisticshypothesis testing, regression, visualization
Programmingreading files, loops and functions in Python or R
Databases and SQLquerying, joining and grouping data

26.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you explain the mean, median, standard deviation and the normal distribution?Probability and Statistics
Can you read a table in Python or R and group it by a column?An intro programming course, then a short pandas or dplyr tutorial
Can you write a simple SQL query with SELECT, WHERE and GROUP BY?The SQL part of a database course, or online SQL exercises
Can you tell when a chart is misleading?Not required; the course teaches it. If curious, see Tufte's book

26.9Neighboring courses

Explainable AI & EthicsProbability & StatisticsData MiningMachine LearningMLOpsData Science
subfieldbuilds onshares methodsapplication
Figure 26.2: Neighbors of Data Science and the kind of relation

26.9.1Where it overlaps

RelationCourseShared ground
builds onThis course builds on Probability and Statisticshypothesis testing, regression, visualization
shares methodsShares methods with Machine Learningpredictive models
shares methodsShares methods with Explainable AI and AI Ethicsdata bias, fairness metrics
shares methodsShares methods with Data Miningexploratory data analysis
shares methodsShares methods with Machine Learning Systems and MLOpsexperiment tracking, data versioning

26.9.2Where it differs

  • Data Mining: Data mining focuses on finding patterns in large data; data science covers the whole path from question to decision.
  • Machine Learning: ML builds models that predict well on new examples; data science uses a model as one tool for answering a question.
  • Probability and Statistics: Statistics provides the theory of inference; data science combines it with programming, messy real data and storytelling.
  • Big Data Systems: Big data systems store and process the data; data science draws meaning and decisions from it.

26.10In practice

26.10.1Applications

AreaWhat is done
A/B testingIs the new design really better?
Marketing analyticsWhich campaign brings customers?
Public healthTracking outbreaks and disease trends.
Sports analyticsMeasuring player and team performance.
Public policyEvaluating services with open data.
Product metricsWhat keeps users, and what drives them away?

26.10.2Risks and ethics

RiskExplanation
Confusing correlation with causationReading causes into correlations leads to wrong decisions: ice cream sales and drownings rise together because both happen in summer.
p-hackingRun enough tests and something will come out "significant"; the hypothesis must be fixed before looking at the data.
Re-identificationIn data with names removed, ZIP code, birth date and sex are enough to re-identify most people.
Misleading chartsA truncated axis or a cherry-picked time window can tell the opposite story with the same data.

These issues are discussed in depth in Explainable AI and AI Ethics.

26.10.3Tools and datasets

Tools: Python, pandas, Jupyter, R and tidyverse, Matplotlib and seaborn, SQL, statsmodels.

Well-known datasets: Titanic (Kaggle), Gapminder, NYC taxi trips, Palmer Penguins, House Prices (Kaggle), Anscombe's quartet.

26.11Common misconceptions

Common mistake

Data science is training models.

Most of the time goes into sharpening the question, finding and cleaning data, and communicating results.

Common mistake

Data speaks for itself.

Without a question, context and domain knowledge, the same data can lead to wrong conclusions.

Common mistake

A significant p-value is an important result.

Statistical significance says nothing about effect size; many tests produce misleading results.

Common mistake

A chart is decoration for the result.

Anscombe's quartet shows it: data with identical summaries look completely different when plotted.

26.12Summary

  • Data science starts with a question and ends with a decision; it consists of getting data, cleaning, exploring, modeling or testing, and communicating.
  • In tidy data every row is an observation and every column a variable. The reason a value is missing (MCAR, MAR, MNAR) decides the method; deleting or mean imputation does not remove bias under MNAR.
  • Exploratory analysis uses the five-number summary and plots; the median and the interquartile range resist outliers, the mean does not.
  • Anscombe's quartet: data with identical summary statistics can look completely different in a plot; every analysis starts with a chart.
  • An A/B test is a randomized experiment; the z test, p-value and confidence interval tell whether a difference could be chance. The same difference can be insignificant in a small sample and significant in a large one; a small p-value does not mean the effect is important.

26.13Test Yourself

  1. A company wants to "increase customer satisfaction". Turn this into a question data can answer: what could the metric, the comparison and the decision be?

    Answer

    One possible translation: the metric is the mean score of a 1-5 survey after service; the comparison is a new call-center script against the old one, with customers split at random; the decision is to apply the new script to all calls if the mean score rises significantly and by enough. What matters is that the metric, the comparison group and the decision are named explicitly.

  2. Data: 4, 6, 7, 9, 10, 12, 40. Find Q1, Q3, the IQR and the outlier fences. Is 40 an outlier? How does the mean change when 40 is removed?

    Answer

    The median is 9. Lower half (4, 6, 7): Q1 = 6; upper half (10, 12, 40): Q3 = 12; IQR = 6. The fences are 6 − 9 = −3 and 12 + 9 = 21; 40 > 21, so it is a candidate outlier. The mean is 88/7 ≈ 12.57; without 40 it is 48/6 = 8.

  3. In a 10-person survey four income answers are missing, and the six respondents have a mean of 30. How does filling the missing incomes with 30 affect the mean and the standard deviation?

    Answer

    The mean stays 30, because the filled values equal the mean ((6·30 + 4·30)/10 = 30). The four filled values do not deviate from the mean, so the standard deviation shrinks; and if missingness depends on income (MNAR) the mean itself may still be biased.

  4. On the old screen 40 of 400 users buy; on the new screen 60 of 400 do. Compute the z statistic and the two-sided p-value for the difference.

    Answer

    The rates are 0.10 and 0.15; difference 0.05. p = 100/800 = 0.125. SE = √(0.125·0.875·(2/400)) ≈ 0.02338. z ≈ 2.14; two-sided p ≈ 0.032. Significant at the 5% level.

  5. For the same experiment compute the 95% confidence interval of the difference and interpret it.

    Answer

    With each group's own rate, SE = √(0.10·0.90/400 + 0.15·0.85/400) ≈ 0.0233. The interval is 0.05 ± 1.96·0.0233 ≈ (0.004, 0.096). It excludes zero, so the difference is significant; but the lower end is 0.4 points and the upper end 9.6 points: the effect may be tiny, so the decision also depends on the cost of the change.

  6. An analyst runs tests on 20 different metrics and subgroups and finds p = 0.04 in one of them. Why is it a problem to report this as "the new screen works in this group"? If there is no real difference anywhere, what is the probability that at least one p < 0.05 appears?

    Answer

    Each test has probability 0.05 of a false positive when there is no real difference; across 20 independent tests the probability that at least one is significant is 1 − 0.9520 ≈ 0.64. A single p = 0.04 is therefore no evidence; the hypothesis and metric must be fixed before the experiment, or a correction for multiple testing applied.

26.14After this course

Data science is the umbrella of the data courses. From here you can move to machine learning to deepen predictive modeling, to data mining for discovery, to big data systems for scale, or to explainable AI and ethics for questions of fairness and bias.

Related careers: Data scientist, Data analyst, Product analyst, Business intelligence specialist, Research analyst.

26.15Further reading

  • H. Wickham, M. Çetinkaya-Rundel and G. Grolemund, R for Data Science (2nd ed., 2023): presents tidy data, transformation and visualization as one end-to-end workflow.
  • W. McKinney, Python for Data Analysis (3rd ed., 2022): shows reading, cleaning and grouping data with pandas in code.
  • J. W. Tukey, Exploratory Data Analysis (1977): the source of the five-number summary and the box plot; the classic statement of looking at the data first.

26.16References

  1. Wickham, Çetinkaya-Rundel and Grolemund, R for Data Science, 2nd ed., O'Reilly, 2023.
  2. McKinney, Python for Data Analysis, 3rd ed., O'Reilly, 2022.
  3. James, Witten, Hastie and Tibshirani, An Introduction to Statistical Learning, 2nd ed., Springer, 2021.
  4. Tukey, Exploratory Data Analysis, Addison-Wesley, 1977.

Related pages: Slides · Slides (PDF) · Course page