Probability Statistics

Cover

week2.pdf

Table of contents

  1. Visualizing distributions
  2. Describing the center
  3. Measuring spread
  4. Describing the form
  5. Putting the summaries together
  6. Time series
  7. What have we learned? Reading distributions
  8. What have we learned? Summaries and time
  9. This week’s material
  10. Looking ahead
  11. Appendix

1. Visualizing distributions

1.1 Why explore data

Exploring data visually is crucial for several reasons:

  • Data cleaning: It helps identify if the data is clean and ready for analysis, prompting a return to the cleaning phase if necessary.
  • Guiding analysis: Understanding the main patterns in the data suggests appropriate subsequent analytical steps.
  • Providing context: Visualizations reveal the characteristics of main variables, highlighting important features.
  • Completing analysis: In rare cases, exploratory analysis alone can suffice for the entire data analysis.
  • Generating questions: Uncovering interesting patterns can lead to new research questions 4.

1.2 Visualizing distributions

The distribution of a variable describes the frequency of each of its values within the dataset, expressed either as absolute or relative frequencies. Various tools are used to visualize these distributions:

  • Categorical variables: Bar charts and pie charts are suitable for categorical data.
  • Numerical variables: Histograms, stemplots, and boxplots are used for numerical data 5.

📝 A bar chart can illustrate the percentage of US flight delays attributed to various causes, with Carrier delays being the highest at 35.5% 6.

1.3 Bar chart

A bar chart displays the frequency of different categories. For instance, a bar chart can illustrate the percentage of US flight delays attributed to various causes 6.

Cause of delayPercentage
Carrier35.5
Incoming28.9
ATC22.3
Cancelled9.3
Weather4.0

Bar chart showing the percentage of US flight delays by cause, with Carrier delays being the highest.

1.4 Pie chart

A pie chart represents proportions of a whole, often used for categorical data. It can also show the percentage breakdown of US flight delays by cause, similar to a bar chart 7.

This pie chart illustrates the percentage of flight delays in the US categorized by cause.

1.5 Histogram

A histogram is a type of bar chart that shows the frequency of values falling within specific intervals or bins.

  • If a numerical variable has few distinct values, the histogram can show the frequency of each value.
  • If there are many values, the data is grouped into bins of usually equal size.
  • The choice of bin size is critical, as it can be set by deciding the number of bins or the size of each bin.
  • Visual inspection of a histogram reveals key features of the data's distribution 8.

An example histogram displays the distribution of distances of hotels in Vienna to the city center. The x-axis represents this distance, and the y-axis shows the number of hotels at each distance interval 9.

A histogram showing the distribution of hotel distances to downtown in Vienna.

📝 A histogram displays the distribution of distances of hotels in Vienna to the city center, with the x-axis representing distance and the y-axis showing the number of hotels at each distance interval 9.

1.6 The impact of bin choice on histograms

The way data is binned significantly affects how a histogram represents the distribution.

  • Using a small number of wide bins simplifies the visualization but can obscure important details within the data.
  • Conversely, using a large number of narrow bins can reveal finer details but may also exaggerate random fluctuations, making them appear more significant than they are 11.

Two bar charts illustrate how the choice of bin size affects data visualization, with one using 2 bins and the other using 56 bins.

1.7 Patterns in distributions: Cen

Cover

week3.pdf

Table of contents

  1. Numerical summaries with grouped data and Data transformation
  2. Data transformation
  3. Standardized observations
  4. What have we learned?
  5. This week’s material
  6. Looking ahead
  7. Reading for next week
  8. Appendix: details and R code

1. Numerical summaries with grouped data and Data transformation

1.1 What is lost when we group data?

When data is grouped, individual observations are replaced by interval counts and midpoints. This process loses the exact values within each interval but retains the frequency distribution.

For numerical summaries like the mean and standard deviation, interval midpoints serve as representative values, providing approximations of the raw-data summaries 3.

  • Grouping data: Observations are organized into intervals, and the count of observations within each interval is recorded.
  • Information loss: Individual values within an interval are not preserved, only their count.
  • Approximation: Interval midpoints are used as representative values for calculations, leading to estimates rather than exact values for summaries like the mean and standard deviation 3.

Histogram showing the distribution of distances from hotels to downtown Vienna.

1.2 Vienna hotel distances: raw data and histogram

The dataset includes 428 individual distances from hotels to downtown Vienna. A histogram visually represents this raw data by grouping the distances into intervals for display.

While the histogram groups data for visualization, the individual distances are still available for precise calculations 4.

📝 The interval [0, 2) km has a midpoint of 1 km and contains 314 hotels, representing 73.36% of the total observations 5.

1.3 Grouped frequency table

A grouped frequency table organizes data by intervals, showing the midpoint of each interval, the number of observations (frequency) within that interval, and the relative frequency as a percentage. For example, the interval [0, 2) km has a midpoint of 1 km and contains 314 hotels, representing 73.36% of the total observations. This table allows for calculations using midpoint replacement 5.

A grouped frequency table showing distance intervals, midpoints, frequencies, and relative frequencies.

1.4 Computation of the mean from grouped data

The mean for grouped data (xˉg\bar{x}_g) is calculated by weighting each interval's midpoint (mkm_k) by its frequency (nkn_k) and dividing by the total number of observations (NN). This method treats every observation within an interval as if it were located at the interval's midpoint 6.

The formula for the grouped mean is: xˉg=∑knkmkN\bar{x}_g = \frac{\sum_{k} n_k m_k}{N} Using the Vienna hotel data: xˉg=1(314)+3(88)+5(14)+7(9)+9(0)+11(2)+13(1)428≈1.743 km\bar{x}_g = \frac{1(314) + 3(88) + 5(14) + 7(9) + 9(0) + 11(2) + 13(1)}{428} \approx 1.743 \text{ km}

1.5 Computation of the standard deviation from grouped data

The sample standard deviation (sgs_g) for grouped data is computed using the same principle as the raw data sample standard deviation, but with interval midpoints and frequencies. The formula involves the sum of squared deviations of each midpoint from the grouped mean, weighted by the frequency of each interval, divided by N−1N-1 7.

The formula for the grouped standard deviation is: sg=∑knk(mk−xˉg)2N−1s_g = \sqrt{\frac{\sum_{k} n_k (m_k - \bar{x}_g)^2}{N - 1}} For the Vienna hotel data, using the unrounded grouped mean: sg=1007.728971963428−1≈1.5362 kms_g = \sqrt{\frac{1007.728971963}{428 - 1}} \approx 1.5362 \text{ km}

This diagram shows the formula for calculating the standard deviation (sg) using the square root of the sum of squared deviations divided by N-1.

1.6 Raw summaries versus grouped approximations

Comparing summaries from raw observations with those from grouped data reveals the impact of information loss due to binning. Different binning strategies can lead to varying estimates for the mean and standard deviation.

It is important to report the intervals used when presenting grouped data estimates 8.

Data TypeMean (km)Standard deviation (km)
Raw observations1.6591.596
7 narrow bins (midpoints)1.7431.536
4 equal-width bins (midpoints)2.1921.469
Cover

week4-comprimido.pdf

Table of contents

  1. Week 4: The normal distribution

  2. A normal distribution for can weights

  3. Characteristics of a normal distribution

  4. Standardizing a normal distribution

  5. Procedure to find a value given a percentage

  6. How can we check if a variable approximately follows a normal distribution?

1. Week 4: The normal distribution

1.1 Exploratory analysis strategies

Two main strategies exist for describing the distribution of a numerical variable. The first, which has been used so far, involves creating a graph like a histogram or stemplot to identify the general aspects of the distribution, including its center, spread, form, and any outliers.

The alternative strategy, useful when a distribution has a regular form, is to represent it with a smooth function called a density curve. This curve then allows the distribution to be described more concisely 3.

1.2 Density curves

A density curve is a mathematical model that represents a distribution. It is always non-negative, meaning its values are never below zero.

The total area under any density curve is exactly 1, which corresponds to the total probability of all possible outcomes. The area under the curve over a specific interval represents the proportion of values that the model assigns to that interval.

It is important to note that the height of the curve itself represents density, not probability; a single point has zero width and therefore zero probability in a continuous density model 10.

1.3 Uniform distribution model

A uniform distribution is a type of density curve where equal-length intervals within its range are assigned equal probabilities. This results in a density curve with a constant height.

For example, if waiting times at a cafeteria are assumed to be uniformly distributed between 0 and 5 minutes, the density height must be calculated such that the total area under the curve equals 1. With a range of 5 minutes, the height is 1/5=0.21/5 = 0.2 per minute. Probabilities for specific intervals are then calculated as the area of a rectangle with the interval's width as its base and the density height as its height 6 9.

1.4 Calculating probabilities with a uniform distribution

Probabilities for intervals within a uniform distribution can be calculated by comparing the interval's width to the full range of the distribution. For instance, if the full range is 5 minutes and the density height is 0.2 per minute, the probability of waiting between 0 and 2.5 minutes is calculated as the interval width (2.5 minutes) multiplied by the density height (0.2 per minute), resulting in a probability of 0.50. Similarly, the probability of waiting between 1 and 4 minutes is (4−1)×0.2=0.60(4-1) \times 0.2 = 0.60, and the probability of waiting between 2.5 and 3.5 minutes is (3.5−2.5)×0.2=0.20(3.5-2.5) \times 0.2 = 0.20 5 7 8 9.

A histogram displays the distribution of waiting times at a cafeteria, with the x-axis representing waiting time in minutes and the y-axis representing the number of students.

A bar chart illustrating a uniform distribution of waiting time, with density on the y-axis and waiting time in minutes on the x-axis.

A bar chart illustrating the probability density of waiting times, with the blue rectangle representing the interval from 0 to 2.5 minutes.

A bar chart illustrating the probability density of waiting times, with the blue shaded area representing the interval of interest.

A bar chart illustrating the probability density function of waiting times, with a shaded region representing the probability of waiting between 2.5 and 3.5 minutes.

![This table shows the calculation of probabilities for different waiting time intervals based on their share of the full 5-minute interv

Cover

week5 - 1CV50-handouts.pdf

📚 week5 - 1CV50-handouts.pdf

Brief overview

This document introduces queueing theory to analyze and improve system performance in production and material handling. It provides methods for understanding variability, calculating key performance indicators, and evaluating different system configurations.

Key points

  • Introduction to queueing theory, system components, and performance measures.

  • Analysis of single-machine queueing systems using exponential (M/M/1) and general (G/G/1) models.

  • Evaluation of automated material handling systems, including mini-loads and crane retrieval times.

  • Examination of queueing systems with multiple parallel machines (M/M/m and G/G/m).

  • Understanding the impact of variability and machine pooling on waiting times.


1. Introduction to queueing theory and system performance

1.1 What is queueing theory?

  • Queueing theory is the science of waiting.

  • It helps understand the causes of waiting in production lines.

  • It evaluates the impact of variability on key performance indicators.

  • These indicators include work-in-progress (WIP), cycle time, and throughput.

  • Often, total process time is a small part of cycle time. The extra time is waiting time.

1.2 Components of a queueing system

  • A queueing system has three main parts:

    • Arrival process: How jobs enter the system. This can involve single jobs or batches.

    • Service process: How jobs are processed. This includes the number and type of machines and the processing order.

    • Queue: The waiting line for jobs. This can have unlimited or limited space.

  • Processing disciplines include:

    • First-come first-served (FCFS)

    • Last-come first-served (LCFS)

    • Shortest process time first (SPTF)

    • Random

1.3 Queueing notation: A/B/c

  • The A/B/c notation describes a queueing system.

  • A specifies the distribution of inter-arrival times.

  • B specifies the distribution of service times.

  • c specifies the number of servers.

  • Common distribution letters:

    • M: Exponential

    • U: Uniform

    • D: Deterministic

    • G: General

  • Examples of notation: D/D/1, M/M/1, M/G/1, G/G/c.

  • M/M/1/b notation indicates limited queue space with b spots.

📝 Example: M/M/1 means exponential inter-arrival times, exponential service times, and one server.

1.4 Performance measures in queueing systems

  • Queueing theory aims to estimate system performance.

  • Key performance measures include:

    • p_np\_n: Probability of having n jobs in the system.

    • phi_B\\phi\_B: Expected waiting time in the buffer (queue).

    • phi\\phi: Expected cycle time or flow time in the station.

    • w_Bw\_B: Average WIP in the buffer.

    • ww: Average WIP in the station.

    • delta\\delta: Throughput of the station.

  • Relations between these measures exist, including Little's Law:

    • w=deltaphiw = \\delta \\phi

    • w_B=deltaphi_Bw\_B = \\delta \\phi\_B

  • Machine utilization (uu) is calculated as:

    • u=fractextarrivalratetextservicerate=fracr_ar_eu = \\frac{\\text{arrival rate}}{\\text{service rate}} = \\frac{r\_a}{r\_e}

    • For M/M/1, u=fraclambdamuu = \\frac{\\lambda}{\\mu}

1.5 The M/M/1 queueing model

  • This model assumes exponential inter-arrival times (rate lambda\\lambda) and exponential service times (rate mu\\mu).

  • It has an unlimited buffer capacity.

  • Machine utilization is u=fraclambdamuu = \\frac{\\lambda}{\\mu}, which must be less than 1 for stability.

  • The probability of n jobs in the system (p_np\_n) follows a geometric distribution:

    • p_n=(1−u)unp\_n = (1-u)u^n
  • Performance measures for M/M/1:

    • Utilization: u=fraclambdamuu = \\frac{\\lambda}{\\mu}

    • Throughput: delta=lambda\\delta = \\lambda

    • Mean WIP: w=fracu1−uw = \\frac{u}{1-u}

    • Mean flow time: phi=frac1mu(1−u)\\phi = \\frac{1}{\\mu(1-u)}

    • Mean waiting time in buffer: phi_B=fracumu(1−u)\\phi\_B = \\frac{u}{\\mu(1-u)}

    • Mean WIP in buffer: w_B=lambdaphi_B=fraclambdaumu(1−u)=fracu21−uw\_B = \\lambda \\phi\_B = \\frac{\\lambda u}{\\mu(1-u)} = \\frac{u^2}{1-u}

📝 Example: Orders arrive at lambda=10\\lambda = 10 per hour, and pick time is exponential with mu=12\\mu = 12 per hour. Picker utilization is u=frac1012=frac56u = \\frac{10}{12} = \\frac{5}{6}.

📝 Example: For the same order picker, the probability of at least 2 orders in the system is 1−p_0−p_1=u2=(frac56)2=frac25361 - p\_0 - p\_1 = u^2 = (\\frac{5}{6})^2 = \\frac{25}{36}.

Cover

Week 5C.pptx

Table of contents

  1. Causal models
  2. Correlation coefficient for regression lines

1. Causal models

1.1 Associative or causal forecasting models

Associative or causal forecasting models utilize multiple related variables to predict a target quantity. These models are generally more powerful than time-series methods, which rely solely on the historical values of the forecast variable.

  • Associative models: consider various factors that influence the quantity being predicted.
  • Dependent variable: the quantity being predicted (e.g., PC sales).
  • Independent variables: the related factors that influence the dependent variable (e.g., advertising budget, competitor prices, economic conditions).
  • Goal of managers: to establish the best statistical relationship between the dependent and independent variables.

📝 The sales of Dell PCs might be associated with Dell's advertising budget, its pricing, competitors' prices, promotional activities, and even national economic indicators like unemployment rates.

1.2 Linear regression analysis

Linear regression analysis is a common quantitative tool for building associative or causal forecasting models. It establishes a statistical relationship between a dependent variable and one or more independent variables.

The fundamental equation for a linear regression trend line is: y=a+bxy = a + bx

Where:

  • yy represents the value of the dependent variable.
  • aa is the y-axis intercept.
  • bb is the slope of the regression line.
  • xx is the independent variable.

1.3 Steps in linear regression

Developing a linear regression model involves several key steps:

  • Identify variables: Clearly define the dependent variable (yy) and the independent variable(s) (xx).
  • Solve for the slope: Calculate the value of bb in the regression equation.
  • Solve for the y-intercept: Determine the value of aa in the regression equation.
  • Develop the equation: Formulate the final trend line equation (y=a+bxy = a + bx) using the calculated values of aa and bb.

1.4 Linear regression problem

A maker of golf shirts is tracking the relationship between sales and advertising expenditure. The company wants to use linear regression to forecast potential sales if they invest $53 in advertising next year.

This problem requires applying the steps of linear regression to find the relationship and then using the resulting equation to predict sales based on the proposed advertising investment.

2. Correlation coefficient for regression lines

2.1 Regression lines and correlation

Regression lines describe the relationship between two variables, indicating how one variable changes with another. They do not imply causation.

The coefficient of correlation, denoted by rr, quantifies the strength and direction of the linear relationship between two variables.

2.2 The correlation coefficient (r)

The correlation coefficient (rr) is a dimensionless quantity that ranges from -1 to +1. It indicates the degree to which two variables are linearly related.

  • Positive correlation: As xx increases, yy also tends to increase. An rr value close to +1 signifies a strong positive linear relationship, with r=+1r = +1 indicating a perfect positive fit where all data points lie exactly on a line with a positive slope.
  • Negative correlation: As xx increases, yy tends to decrease. An rr value close to -1 signifies a strong negative linear relationship, with r=−1r = -1 indicating a perfect negative fit where all data points lie exactly on a line with a negative slope.
  • No correlation: An rr value close to 0 suggests a weak or no linear relationship between the variables, possibly indicating a random or nonlinear association.

2.3 Strength of correlation

The strength of the linear association is generally categorized as follows:

Correlation Value (r)Description
Close to +1Strong positive correlation
Close to -1Strong negative correlation
Close to 0No or weak linear correlation
>
Cover

week5.pdf

Table of contents

  1. Scatterplots and correlation
  2. Conditional means and regression
  3. Fitting a line by least squares
  4. Interpreting predictions and R2

1. Scatterplots and correlation

1.1 Relationships between two variables

This section introduces the types of relationships that can be explored between variables, focusing on those relevant to scatterplots and correlation. The primary focus is on the relationship between two numerical variables.

  • Two categorical variables: Explores associations between variables like location and transportation mode.
  • Two numerical variables: Examines relationships such as entry grade and first-year average grade. This type of relationship is the focus of scatterplots and correlation analysis.
  • One numerical and one categorical variable: Investigates connections like schooling level and income 4 5 6.

1.2 Exploratory analysis with two variables

The process of exploring relationships between two numerical variables involves several steps, starting with visualization and moving towards numerical summaries. This approach helps in understanding the general patterns and the nature of the association.

  1. Start with a graph: Visualizing the data using a scatterplot is the initial step.
  2. Identify general aspects and main patterns: Observe the overall trend, direction, form, and scatter of the data points.
  3. Use numerical summaries: Employ statistical measures to quantify the observed patterns.
  4. Summarize with a function: Determine if a smooth or regular function can adequately describe the data's distribution 7.

📝 The process of exploring relationships between two numerical variables starts with visualizing the data using a scatterplot, then identifying general aspects and patterns, using numerical summaries, and finally summarizing with a function 7.

1.3 Reading a scatterplot

A scatterplot displays individual data points, where each point represents an observation for two numerical variables. By examining the arrangement of these points, one can infer the nature of the relationship between the variables.

  • Each dot on the plot represents a single observation, such as one month's data for gas consumption and the number of families using heating.
  • Key aspects to observe are the direction (positive, negative, or none), form (linear or non-linear), and scatter (how closely the points follow a pattern).

This scatterplot visualizes gas consumption in a city, with each dot representing one month. 8.

1.4 Positive association

A positive association in a scatterplot indicates that as the values of one variable increase, the values of the other variable tend to increase as well. This suggests a general upward trend in the data.

  • In a positive association, higher values of the independent variable (typically plotted on the x-axis) are associated with higher values of the dependent variable (typically plotted on the y-axis).
  • It is important to note that observing an association does not automatically imply causation; other factors might be influencing the relationship.

A scatter plot showing the relationship between the number of families using heating and gas consumption in a city. 9.

1.5 Exact linear relationship

An exact linear relationship is a specific type of positive association where all data points fall precisely on a straight line. This indicates a perfect linear correspondence between the two variables.

  • In this scenario, the relationship can be described by a linear equation, y=mx+by = mx + b, where every change in xx corresponds to a proportional change in yy.
  • This is a special case of a positive association, where the correlation coefficient, rr, would be exactly +1.

This line graph shows the relationship between meal price and VAT paid, illustrating an exact linear relationship. 10.

1.6 Negative association

A negative association in a scatterplot is observed when an increase in one variable is associated with a decrease in the other variable. This suggests a general downward trend in the data.

  • As the values on the x-axis increase, the corresponding values on the y-a
Cover

week5.pdf

Table of contents

  1. Scatterplots and correlation
  2. Conditional means and regression
  3. Fitting a line by least squares
  4. Interpreting predictions and R2

1. Scatterplots and correlation

1.1 Relationships between two variables

When analyzing data, we often explore relationships between different variables. The type of relationship we look for depends on the types of variables involved.

For two numerical variables, we can examine how they vary together, which is the focus of correlation and regression analysis 7.

  • Two numerical variables: This scenario involves examining the association between two quantitative variables, such as entry grade and first-year average grade for students 5.
  • Two categorical variables: Here, the focus is on the relationship between two qualitative variables, like location and transportation mode 4.
  • One numerical and one categorical variable: This type of analysis explores how a numerical variable, such as income, relates to a categorical variable, like schooling level 6.

1.2 Reading a scatterplot

A scatterplot is a graphical tool used to visualize the relationship between two numerical variables. Each point on the plot represents a single observation, typically corresponding to a specific instance or time period.

By examining the pattern of these points, we can identify the direction, form, and scatter of the relationship 8.

  • Components of a scatterplot:
  • Each dot represents one observation (e.g., one month).
  • The x-axis displays the values of one variable (e.g., families using heating in thousands).
  • The y-axis displays the values of the other variable (e.g., gas consumption in million cubic meters).
  • Interpreting the pattern:
  • Direction: Indicates whether the variables tend to increase or decrease together.
  • Form: Describes the shape of the relationship (e.g., linear, non-linear).
  • Scatter: Refers to how closely the points cluster around a potential trend line 8.

This scatterplot shows the relationship between the number of families using heating and the gas consumption in a city.

📝 The relationship between meal price and the Value Added Tax (VAT) paid, where VAT is a fixed percentage of the meal price 10.

1.3 Positive association

A positive association occurs when higher values of one variable tend to be associated with higher values of the other variable. This means that as the variable on the x-axis increases, the variable on the y-axis also tends to increase.

It is important to note that a scatterplot shows an association, but it does not inherently prove causation 9.

  • Characteristics:
  • As x increases, y tends to increase.
  • The data points generally trend upwards from left to right 9.

This scatter plot shows the relationship between the number of families using heating and the gas consumption in a city.

1.4 Exact linear relationship

An exact linear relationship is a specific type of positive association where all data points fall precisely on a straight line. This indicates a perfect linear correspondence between the two variables.

In such cases, the relationship can be described by a linear equation 10.

  • Definition: A relationship where points lie exactly on a straight line.
  • Example: The relationship between meal price and the Value Added Tax (VAT) paid, where VAT is a fixed percentage of the meal price 10.

A line graph showing the exact linear relationship between meal price and VAT paid.

Cover

week6-handout.pdf

Table of contents

  1. Week 6: Regression diagnosis and non-linear regression
  2. Residual analysis
  3. Influence
  4. Smoothing the relationship
  5. Logarithms
  6. Non-linear relations
  7. Problems

1. Week 6: Regression diagnosis and non-linear regression

1.1 Diagnosing the fitted line using residuals

The quality of a regression model is assessed by examining its residuals, which are the differences between the observed values and the values predicted by the fitted line. Analyzing these residuals helps identify patterns, assess the spread of errors, evaluate the shape of the relationship, and detect unusual observations 2.

  • Residuals: These are the errors of the model, calculated as the observed value minus the predicted value.
  • Purpose of Residual Analysis: To check if the assumptions of the linear regression model are met and to identify potential problems with the fit 2.

📝 Residuals are the differences between observed and predicted values. For instance, if a model predicts a value of 10 for a data point, but the observed value is 12, the residual is 12−10=212 - 10 = 2 2.

1.2 Identifying influential observations

Influential observations are data points that significantly affect the regression line. Identifying and understanding these points is crucial for building a robust model 2.

1.3 Exploring and modeling non-linear relationships

Linear regression assumes a straight-line relationship between variables. When this assumption is violated, non-linear relationships may exist, requiring different modeling approaches 2.

1.4 Recognizing the limits of regression

Regression models have limitations. It is important to understand these boundaries to avoid misinterpreting results or overextending the model's applicability 2.

2. Residual analysis

2.1 From fitting a line to checking the fit

After fitting a line to describe the relationship between two numerical variables, residual analysis examines the errors left by that line. The fitted line provides a prediction (y^i\hat{y}_i) for each observation, and the residual (eie_i) is the prediction error, calculated as ei=yi−y^ie_i = y_i - \hat{y}_i.

The least squares method chooses the line that minimizes the sum of squared errors (∑ei2\sum e_i^2). Residual analysis helps identify what the fitted line might be missing, such as patterns, varying spread, unusual shapes, or outliers 4.

  • Prediction error: The residual (eie_i) is the difference between the observed value (yiy_i) and the predicted value (y^i\hat{y}_i) from the fitted line.
  • Least squares: This method finds the line that minimizes the sum of the squared residuals.
  • Purpose of residuals: They reveal aspects of the data that the fitted line does not capture, guiding further analysis and model improvement.

2.2 Residual analysis for October

The fitted line for gas consumption based on families using heating is Gas^≈1.292+0.201×Families\hat{\text{Gas}} \approx 1.292 + 0.201 \times \text{Families}. For October, with 15.6 thousand families, the observed gas consumption was 5.50 million m³, and the fitted consumption was 4.43 million m³.

The residual for October is eOctober=5.50−4.43=+1.07e_{\text{October}} = 5.50 - 4.43 = +1.07 million m³, indicating the fitted line underpredicts consumption for that month 5.

2.3 Histogram of the residuals

A histogram of the monthly residuals provides a visual summary of the prediction errors. With a small number of observations, the histogram offers limited evidence about the distribution's shape.

Typically, most errors are close to zero, but specific months might show larger positive or negative errors. The histogram helps to see the distribution of these errors and identify any unusual values 6.

This histogram displays the distribution of nine monthly residuals for residual gas consumption.

2.4 Reading the residual plot

A residual plot displays the residuals on the vertical axis against the explanatory variable on the horizontal axis. Each point on the plot represents one observation (e.g., one month).

A residual of zero means the observed value equals the fitted value. Positive residuals indicate the line underpredicts, while negative residuals indicate the line overpredicts 7.

A residual plot showing residual gas consumption against families using heating, with October highlighted.

2.5 What to look for in residuals

Residual analysis involves examining s

Cover

week7.pdf

Table of contents

  1. Week 7: Causality
  2. What could explain the pattern?
  3. What is a causal effect?
  4. How can we learn about causal effects?
  5. How do causal effects inform decisions?
  6. Week 7 lecture slides
  7. Looking ahead

1. Week 7: Causality

1.1 Plan for today

This section outlines the lecture's plan for understanding causality. The discussion will cover how to explain observed patterns, define causal effects, and learn about them.

Finally, it will explore how causal effects inform decision-making 2.

  • Key questions to be addressed:
  • What could explain an observed pattern?
  • What is a causal effect?
  • How can we learn about causal effects?
  • How do causal effects inform decisions 2?

2. What could explain the pattern?

2.1 Storytelling

A story is considered consistent with the data if its logical progression would naturally lead to the observed patterns. This initial phase focuses on brainstorming potential explanations.

It is crucial to distinguish between a story's consistency with the data and its empirical truth. The first question is whether the story logically implies the observed patterns, which is an objective assessment.

The second question is whether the story is actually true, which requires empirical testing to gather evidence that can differentiate between competing stories 4.

2.2 Example: Calçots

Consider the pattern that people in Barcelona who consume calçotades are, on average, healthier than those who do not. Several stories can explain this observation:

  • Health benefits of calçots: The calçots themselves or their accompanying sauce might possess inherent health-promoting properties.
  • Association with income: Calçotades could be positively correlated with higher income levels. Individuals with greater financial resources may have better health outcomes due to factors like improved access to healthcare and fitness facilities.
  • Social interaction: Calçotades are often social gatherings. The positive impact of social contact on health could be a contributing factor.
  • Pre-existing health status: Individuals who are already in better health might be more inclined or able to participate in such events.

This observed association alone is insufficient to isolate a direct causal effect of eating calçots on health 5.

📝 People in Barcelona who consume calçotades are, on average, healthier than those who do not. Possible explanations include the health benefits of calçots, an association with higher income, the positive impact of social interaction at these events, or that healthier individuals are more likely to attend 5.

2.3 Example: Pétanque

Imagine a survey of 10,000 Barcelona residents in 2024, with a follow-up in 2025, revealing that individuals who played pétanque in 2024 were more likely to die within the following year. Several potential stories could explain this finding:

  • Pétanque as a dangerous sport: The direct causal link would be playing pétanque leading to an increased risk of death.
  • Gender differences: Pétanque might be predominantly played by men, who generally have a lower life expectancy than women. In this scenario, sex influences both playing pétanque and the risk of death.
  • Age-related factors: Older individuals may be more likely to play pétanque, and older age is independently associated with a higher likelihood of death due to age-related health issues.

Three elderly men playing pétanque in a park. 6.

3. What is a causal effect?

3.1 Potential outcomes

A potential outcome represents what would happen to a unit (e.g., a person) under a specific condition or intervention. For any given unit, only one potential outcome can be observed at a time, while the others remain unobserved counterfactuals.

  • Observed outcome: The result experienced by a unit under the condition that actually occurred.
  • Counterfactual outcome (cf): The unobserved result that would have occurred for the same unit if a different condition or intervention had been applied 8.

3.2 Causal versus descriptive statements

Causal statements claim that changing one variable will lead to a change in another, whereas descriptive statements merely summarize observed data without implying such a relationship. A linear predictor indicates an association but does not make a causal claim.

  • Causal statement: Asserts that altering a variable X would result in a change in variable Y for the same unit.
  • Descriptive statement: Summarizes data and describes associations between variables without claiming that intervening on one would affect the other.
  • Linear predictor:
Cover

week8.pdf

Table of contents

  1. Relationships with categorical variables
  2. One numerical and one categorical variable
  3. Binary outcomes
  4. Scatterplots across groups
  5. Transport and residence
  6. What have we learned?
  7. This week’s material
  8. Looking ahead
  9. Appendix: R code

1. Relationships with categorical variables

1.1 Two categorical variables

When analyzing two categorical variables, we can examine their joint and marginal distributions, as well as conditional distributions. The joint distribution describes the frequency or proportion of observations that fall into specific combinations of categories for the two variables.

The marginal distribution, on the other hand, summarizes the distribution of a single variable, ignoring the other by summing across its categories. Conditional distributions focus on the distribution of one variable given a specific category of the other variable, effectively changing the denominator for calculating proportions 4 5.

  • Joint distribution: Describes combinations of two variables. For example, the number of people who support a specific team and live in a particular city 4.
  • Marginal distribution: Sums over the other variable to show the distribution of a single variable. This is calculated using row or column totals from a two-way table 5.
  • Conditional distribution: Restricts the denominator to a specific group, showing the distribution of one variable given a category of another. This can be calculated by conditioning on rows or columns of a two-way table 8.

Two bar charts showing the distribution of city of residence and team supported for 20 people. 6.

Two bar charts showing joint distribution, one grouped by city and the other by team. 7.

1.2 Independence and dependence

Two categorical variables are considered independent if the conditional distribution of one variable is the same for every category of the other variable, and this distribution is also equal to the marginal distribution of that variable. If the conditional distributions differ from the marginal distribution, the variables are dependent.

Independence is a symmetric relationship; if variable X is independent of variable Y, then Y is also independent of X 12 13.

  • Independence: Occurs when the distribution of one variable does not change across categories of another variable. For example, if height distributions are the same for both low and high income groups, height and income are independent 12.
  • Dependence: Occurs when the distribution of one variable changes across categories of another variable. For instance, if team preferences vary significantly among residents of different cities, then team supported and city of residence are dependent 11.

1.3 Recap of distributions

This exercise involves analyzing a two-way table of supermarket visits by time of day. It requires calculating joint and marginal distributions, as well as conditional distributions, and visualizing the marginal distribution of time of day 14.

  • Joint distribution: The absolute frequency of (X = Mercadona, Y = Morning) is 10 visits. The relative frequency is 10/100 = 10%.
  • Marginal distribution of supermarket: Bonpreu has a relative frequency of 60/100 = 60%, and Mercadona has a relative frequency of 40/100 = 40%.
  • Conditional distribution of time given Mercadona: The relative frequency of Morning visits conditioned on X = Mercadona is 24/40 = 60%.
  • Conditional distribution of supermarket given Morning: The relative frequency of Mercadona conditioned on Y = Morning is 24/36 ≈ 66.7%.
  • Bar plot of marginal distribution of Y: This would show three bars representing Morning, Afternoon, and Evening with heights corresponding to their total visit counts (36, 30, 34 respectively) 14.

1.4 Simpson's paradox

Simpson's paradox describes a phenomenon where an observed association between two categorical variables can disappear or even reverse when a third, confounding variable is taken into account. This occurs because the third variable influences the relationship between the original two variables by affecting their distributions or the proportions within their categories 16.

  • Simpson's paradox: A statistical phenomenon where a trend appears in different groups of data but disappears or reverses when these group