All classes
basic definitions: prediction versus forecasting and parameter estimation
Data Science Definitions
- Data science definition (Naur, 1974): Science dealing with data once established, delegating data relation to other fields 3.
- Data science definition (Dhar, 2013): Study of generalizable knowledge extraction from data 3.
- Data science practical definition (Varian, 2014): Concerns prediction, summarization, data manipulation, and visualization tasks 3.
Procurement Context Definitions
- Public procurement: Purchase of goods, services, and works by governments and state-owned enterprises 4 5.
- Public procurement activity is substantial, approximating 15% of global Gross Domestic Product (GDP) 4 5.
- Collusion: Agreements among sellers to fix prices or reduce output to increase profits 6.
- Bid rigging: A form of collusion where firms coordinate bids on procurement or project contracts 6.
- Antitrust: Field of economic policy and laws managing monopoly and monopolistic practices 7.
Collusion Detection versus Prediction
- Collusion detection (ex post): Identifies behavior that has already occurred, using post-event information for investigation/conviction 12.
- Collusion prediction (ex ante): Assesses the likelihood of collusion before it happens, using pre-event information for monitoring/prevention 12.
Statistical Screens for Bid-Rigging Markers
- Fewer bidders (ni=∣Fi∣) suggest suppressed competition 13.
- Fewer bids (mi=∣Bi∣) may indicate bid suppression or cover bidding 13.
- Coefficient of variation (cvi=si/bˉi) is lower under collusion, indicating compressed bids 13.
- si is calculated as mi−11∑j=1mi(bi,j−bˉi)2 13.
Kamikaze Auctions
- Kamikaze strategy: Low bidder wins, withdraws bid without fulfilling requirements, causing the second-lowest bidder to win at a higher price 22.
- Outcome variable: Kamikazei=1 if the lowest bidder of auction i does not win, 0 otherwise 22.
- Kamikaze auctions result in 18 percent higher prices than non-kamikaze auctions 23.
Reproducible Research Principles (Foundational Context)
- Replication exercise yields the same quantitative results, implying parameter estimates share the original study's sampling distribution 77.
- Verification (pure replication): Repeating analysis with the same sample to detect measurement or coding errors 83 84.
- Reproduction: Applying the same analysis to a new sample from the same population to test across sample realizations 83 87.
- Reanalysis: Applying a different statistical analysis to the same or new sample to test robustness to model specifications 88 89.
- Extension: Applying the original analysis to a new population (different place/time) to test generalizability 88 90.
-
Tip: Scientific reproducibility relies on organizing work, coding for others, and automation
- Structure projects by separating inputs (raw data) and outputs (estimates)
- Use sequential numbering for program execution order (e
Data organization principles
Core idea
- Organize work via shared folders, version control (e.g., GitHub), and collaborative tools .
- Manual version control involves saving separate code files for outputs using date suffixes .
Code style and documentation
- Code should prioritize simplicity, clarity, and generality .
- Layout convention suggests limiting line length (e.g., 80 characters) and spacing around operators like
$=$. - Naming conventions should be consistent, meaningful, and may use prefixes to denote variable type (e.g.,
dumfor indicator,shrfor share) . - Follow the DRY principle: Don't Repeat Yourself, using functions to avoid repeating code blocks .
- Code must be documented with a self-contained description at the top and comments explaining code blocks .
Automation and reproducibility
- Automate every possible step; avoid manual point-and-click tools like MS Excel .
- Export results into portable formats (e.g.,
.TXTfor tables,.PNGfor graphs) using software-specific commands . - Write a master program to sequence analysis scripts logically (Sample, Descriptive, Causal, Robustness, Mechanisms) .
- Master programs should define paths and parameters using local/global macros for uniformity .
- Dynamic documents (e.g., R Markdown) integrate coding and text for reproducible reporting .
Data quality issues: Duplicates, missing data, and outliers
Duplicated data
- Duplicated data can bias estimates and distort sample representativeness if overweighting occurs .
- Detection methods depend on the existence of a unique identifier .
- If a unique ID exists, check for identical observations; if identical, drop one .
Missing data
- Missing data causes include machine error, human error, data merging issues, and survey non-response .
- Econometrics suffers from inconsistent estimates due to non-random missingness; Data Science suffers reduced predictive accuracy .
- Detection involves identifying coded missing values (e.g., NA, “-9”) during import .
- Case deletion removes units with any missing value, risking sample size reduction and bias if missingness is non-random .
- Imputation replaces missing values (e.g., using mean or regression prediction) to maximize sample size, but risks bias if missingness is non-random .
Outliers
- Outliers are observations deviating markedly, possibly generated by a different mechanism .
- Outliers can drive research conclusions or signal events like fraud or tax evasion .
- Univariate outlier detection involves visual inspection (Box Plot fences: Q1−1.5×IQR to Q3+1.5×IQR) .
- Descriptive statistics flags outliers via high Coefficient of Variation (CV(x)>1), Skewness (∣Skew(x)∣≥1), or Excess Kurtosis (Kurt(x)−3>1) .
- The simple z-score rule of thumb (zi=sxxi−xˉ>3) suffers from masking/swamping because xˉ and sx are biased by outliers .
Multivariate outliers: detection and solutions
Feasible estimates for Mahalanobis distance (MD)
- The Mahalanobis distance squared is MDi2=(xi−μ)⊤Σ−1(xi−μ) .
- Population parameters μ and Σ are replaced by feasible estimates μ^ and Σ^ in practice .
- The estimated mean vector is μ^=N1∑i=1Nxi=xˉ .
- The estimated covariance matrix is Σ^=N−11∑i=1N(xi−μ^)(xi−μ^)⊤ .
Distributional results for MD
- If x∼N(μ,Σ), then Σ−1/2(x−μ)∼N(0K,IK) .
- If x∼N(0K,IK), then x⊤x∼χK2 .
- It follows that MDi2∼χK2 .
- The cutoff value for detecting an outlier at significance level α is χK,1−α2 .
Feasible rule of thumb for multivariate outliers
- Observation i is an outlier if dMD2=(xi−μ^)⊤Σ^−1(xi−μ^)>χK,1−α2 .
- A robust rule of thumb uses estimates μ^ and Σ^ derived only from the 75−90% observations closest to each other .
Solutions for multivariate outliers
- Robust detection: Trim observations with very high Mahalanobis distances using a robust rule of thumb .
- Robust estimation: Use estimation methods less sensitive to outliers, such as quantile regression instead of OLS, if removal is not ideal .
Data visualization principles
Principle 1: Show the data
- Make the data itself the primary focus of the graph .
- Remove the y-axis or labels if they do not add value .
- Highlight important values to guide the reader’s attention .
Principle 2: Reduce the clutter
- Remove all visually unnecessary elements like gridlines and tick marks .
- Axes elements (title, tick marks, labels) should be removed if they provide no value .
Principle 3: Integrate graphics and text
- Remove legends where possible and label data points directly near the data .
- Align labels and match their colors to the corresponding data elements .
- Titles should summarize the graph's takeaway, avoiding purely descriptive statements .
- Use text explainers to clarify crucial points of the data .
Principle 4: Avoid the spaghetti chart
- Use the small multiples approach instead of plotting all data in one dense graph .
- Small multiples involve creating several smaller graphs using fractions of the data, arranged logically .
Principle 5: Start with gray
- Plot all graph elements in neutral gray initially .
- Use thick lines and points, then selectively add colors to highlight contrasts .
Main classes of graphs
Comparing categories
Time series
Distribution
Relationship graphs: Scatterplots and binscatter
Simple Linear Regression Model
Problems with the linear regression model
Regression outliers
Regression outliers and influential observations
Vertical outliers (y-outliers)
- An observation has a typical x value but an atypical y value .
- Rule of thumb: Observation i is a y-outlier if ∣SD(ei)ei∣>3 .
- Estimate SD(ei) using robust methods in practice .
Horizontal outliers (x-outliers)
- An observation has a typical y value but an atypical x value .
- Simple regression rule of thumb for high leverage: hi>N4 .
- Leverage hi:=N1+∑j=1N(xj−xˉ)2(xi−xˉ)2 .
- Cutoff is roughly twice the average leverage value .
- Multiple regression rule of thumb uses high Mahalanobis distance (dMD2) .
- dMD2=(xi−μˉ)⊤Σ^−1(xi−μˉ)>χK,1−α/22 .
- MDi2 is proportional to leverage hi, providing the same case ranking .
Regression outlier map categories
- Good leverage points: Small standardized residual AND MDi inside the critical range .
- Bad leverage points: Large standardized residual AND MDi outside the critical range .
Influential observations
- Leverage statistic (hi) measures influence on the fitted value y^i .
- Observation i is influential if it has a large DFBETA: ∣DFBETAij∣>N2 .
- DFBETAij=β^j−β^j(i) measures coefficient change when observation i is excluded .
Solutions for regression outliers
- Vertical outliers and bad leverage points can severely bias the OLS estimator's signal .
- Good leverage points can downward-bias the estimated standard errors .
- If results are unchanged: Add a robustness section showing stability under different outlier criteria .
- If results change: Apply transformations (e.g., log, Box-Cox) or use robust estimation (e.g., Least Trimmed Squares) .
- In Finance/Business practice, Winsorizing, Trimming, and Dropping (WTD) are common solutions .
Multiple linear regression: Basic structure and extension
Matrix notation and assumptions
- Multiple linear regression model: y=Xβ+ε .
- The five defining hypotheses ensure OLS estimators are unbiased, efficient, and support valid inference .
- Exogeneity assumption E[ε∣X]=0 ensures OLS unbiasedness .
Partitioned regression theorem
- For y=X1β1+X2β2+ε, β^1=(X1∗X1∗)−1X1∗y∗ .
- Where X1∗=M2X1 and M2=I−P2 .
Models with fixed effects (FEs)
Models with interactions
Basic definitions: Prediction versus parameter estimation
Prediction versus forecasting
Prediction versus parameter estimation
In-sample versus out-of-sample prediction
Point prediction in linear regression
Point prediction and error
Prediction distribution and interval
Selecting the best model and evaluating performance (Quantitative)
Model selection algorithms
Information criteria
Evaluating quantitative prediction performance
Predicting a qualitative variable (Classification)
Classification model specification
Converting probability to category
Evaluating classification performance
Evaluating performance beyond accuracy
Key facts on F1-Statistic
- The F1-Statistic combines Precision and Sensitivity into one measure .
- It is the harmonic mean of Precision and Sensitivity .
- A high F1-Statistic signals a good trade-off between false positives and false negatives .
- It is particularly useful when dealing with imbalanced datasets .
Key concepts on ROC curve and AUC-ROC
- The Receiver Operating Characteristic (ROC) curve plots model performance across all possible thresholds .
- The ROC curve plots Sensitivity (y-axis) against 1 minus Specificity (x-axis) .
- Performance improves as the curve moves farther from the diagonal line (random guessing) .
- The Area Under the ROC Curve (AUC-ROC) quantifies performance across all thresholds .
- AUC measures the probability that a randomly chosen positive case ranks higher than a negative case .
- AUC ranges from 0.5 (random guessing) to 1 (perfect classification) .
- AUC values of 0.7 to 0.8 are generally considered acceptable model performance .
Basic definitions for out-of-sample prediction
Key concepts in terminology
- In data science prediction, y is the response and X are the predictors (features) .
- Econometrics terminology often uses y as the outcome and X as covariates (regressors) .
- Supervised learning requires both predictors and a response variable to map inputs to outputs .
- Classification tasks predict a categorical response y, aiming for Pr[y=k∣x] .
- Regression tasks predict a numerical, continuous response y, aiming to estimate E[y∣x] .
- Out-of-sample prediction assesses generalization using data unseen during model estimation .
Statistical learning and parameter estimation
Core idea of statistical models
- The statistical model relates a quantitative response y to predictors x: y=f(x)+ε .
- f(x) is the unknown function relating predictors to the expected response, and ε is the zero-mean error term .
- Statistical learning estimates f from observed data to minimize the reducible error .
- The expected squared prediction error is decomposed into reducible error (model fit) and irreducible error (Var(ε)) .
Flexibility versus interpretability
- Parametric methods assume a specific functional form for f, providing high interpretability .
- Non-parametric methods estimate f directly, offering flexibility but lower interpretability .
- Highly flexible methods can obscure the relationship between predictors and response .
- No single method maximizes predictive accuracy for all datasets; choice depends on data and true form of f .
Measuring predictive accuracy and overfitting
Resampling methods and regularization
Resampling for model assessment
Regularization (Shrinkage Methods)
collusion and bid rigging in procurement
Core idea
- Public procurement is the purchase of goods, services, and works by governments or state-owned enterprises 4 5.
- Procurement is a sizable economic activity, representing approximately 15 percent of global Gross Domestic Product 4 5.
- This topic uses public procurement as a case study for applying data science to economics 4 5.
- Antitrust policy addresses monopoly and monopolistic practices, also known as competition law 7.
Key facts
- Collusion involves agreements among sellers to fix prices or reduce output to increase profits 6.
- Bid rigging is a specific type of collusive price-fixing in procurement contracts 6.
- E-procurement data can aid governments in combating collusion 10 8 9.
- E-procurement data usage is divided into two primary applications: ex-post and ex-ante 10 8 9.
Key concepts
- Collusion definition: combinations or conspiracies among sellers to raise or fix prices 6.
- Bid rigging definition: firms coordinating their bids on procurement or project contracts 6.
- Ex-post use of data: provides evidence for conviction and investigation 10 8 9.
- Ex-ante use of data: offers guidance for preventive action against collusion 10 8 9.
Implications
- Governments can utilize open e-procurement auction data to detect and prosecute cartels 10 8 9.
- Examples of open e-procurement auctions include those on the Brazilian CNET and BOSA websites 10 8 9.
- Understanding these concepts is crucial for economists studying market failures and regulatory effectiveness 4 7.
-
Tip: Focus on the definitions of collusion and bid rigging as they are central to the case study methodology described 6
the kamikaze bidding strategy and its implications
Core idea
- The kamikaze strategy involves a firm submitting a very low bid to win, then withdrawing to allow the second-lowest bidder to win at a higher price 22.
- This scheme often involves an explicit agreement where the kamikaze firm receives compensation, such as a subcontract 24.
- The strategy exploits dynamic reverse auctions used for procuring standardized goods and services in Brazil 18.
Key facts
- In competitive auctions, bidders see the lowest bid but not the identity of the bidder 19.
- Each new bid submitted must be lower than the bidder's previous bid 19.
- The lowest bidder wins provisionally, pending a post-bidding documentation review 18 19.
- Kamikaze firms withdraw their bid without fulfilling subsequent filing requirements 22.
- The outcome variable, Kamikazei, is 1 if the lowest bidder of auction i does not win, and 0 otherwise 22.
- Kamikazei={10if the lowest bidder of auction i does not winotherwise 22
- Fazio and Zaldokas estimate 17 percent of auctions involve kamikazes 23.
- Auctions employing kamikaze bidders result in prices 18 percent higher than those without them 23.
- The strategy is known by alternative names, including "diver" or "rabbit" 24.
Key concepts
- Disqualification reasons include failing to appear to sign the contract 23.
- Other disqualification reasons involve intentionally omitting required documents or submitting incorrect documentation 23.
- Firms may also be disqualified for claiming prices differing from those registered in the bidding system 23.
- The strategy relies on collusion, where the kamikaze bid secures the win for the next bidder in exchange for illicit payment 24.
Implications
- The main implication is that the final procurement price is elevated compared to the lowest bid submitted 22 23.
- The use of competitive electronic auctions generates extensive procurement data, allowing for the identification of this tactic 18.
- The strategy indicates potential failures in contract enforcement or documentation review processes 23.
- The strategy effectively circumvents competitive pricing to the detriment of the procuring entity 24.
-
Tip: Competitive auctions prone to collusion, like dynamic reverse auctions, are key environments where the kamikaze strategy is implemented 18
definitions of key procurement entities and structures
Core idea
- Procurement involves defining the agency, the product, and the structure of the purchasing event 26 29 30.
- Entities include the Purchasing Agency (PA) and the Procurement Manager/Official 26 31.
- The procurement event itself is structured via Auctions, Bundles, and Tenders 29 30.
Purchasing Agency and Product
- Purchasing Agency (PA) is the office organizing the procurement, denoted by a 26.
- Examples include universities and hospitals 26.
- Roughly 4.8 thousand PAs organized auctions between 2005 and 2021 26.
- Product is defined by a 4-digit code from materials/services catalogs 26.
- Products can be goods (e.g., classroom chairs) or services (e.g., cleaning services) 26.
- PAs purchased over 139 thousand distinct products between 2005 and 2021 26.
- A product is denoted by p 26.
Auction and Bundle Structure
- Auction is electronic bidding where the PA procures a fixed quantity of one product, denoted by i 29.
- Example: A university procuring 500 classroom chairs 29.
- Bundle is a grouping of multiple auctions under one public notice, denoted by b 29.
- Eighty percent of bundles contain only a single auction 29.
- The average bundle contains 1.2 auctions 29.
Tender Structure
- Tender is a group of auctions issued under one public notice for related products, denoted by j 30.
- Example: A tender for office furniture covering chairs and desks 30.
- The median tender structure is 3 bundles and 5 auctions 30.
Procurement Personnel
- Procurement Manager (PM), denoted by m, performs administrative tasks 31.
- PM tasks include market research and selecting bidding methods 31.
- PM is usually the head of the PA’s procurement office 31.
- Procurement Official (PO), denoted by o, handles execution tasks 31.
- PO conducts bidding, evaluates proposals, negotiates, and indicates the winner 31.
- PO typically does not draft the tender notice 31.
- PO is usually junior staff in the procurement office 31.
timeline: the procurement process and data observability
Structure of the training set vectors
- The training set vector xi is composed of eight components: xi=(x1,a(i),x2,p(i),x3,m(i),x4,j(i),x5,b(i),x6,i,x7,o(i),x8,f(i)) 33 34 35.
- x1,a(i): characteristics vector of the Procuring Authority (PA) organizing auction i 33.
- x2,p(i): characteristics vector of the product purchased in auction i 33.
- x3,m(i): characteristics vector of the Procurement Manager (PM) managing auction i 33.
- x4,j(i): characteristics vector of the tender containing auction i 34.
- x5,b(i): characteristics vector of the bundle containing auction i 34.
- x6,i: characteristics vector of the auction i itself, including quantity and value 34.
- x7,o(i): characteristics vector of the Procuring Organization (PO) implementing auction i 35.
- x8,f(i): characteristics vector of the firms bidding in auction i 35.
Procurement process steps and feature determination
- Steps 1 and 2 of the timeline determine the features x1,a(i), x2,p(i), and x3,m(i) 36.
- Steps 3 through 5 determine the features x4,j(i), x5,b(i), and x6,i 37.
- Step 6 determines the characteristics vector x7,o(i) 38.
- Step 9 determines the feature vector x8,f(i) and the kamikaze outcome variable kamikazei 40.
Data observability timeline
- The set (x1,a(i),x2,p(i),x3,m(i),x4,j(i),x5,b(i),x6,i,x7,o(i)) becomes publicly observable after Step 7 (legal approval) and tender notice publication 39.
- The feature vector x8,f(i) becomes visible just before the bidding phase, specifically when firms log into the auction page 40.
-
Tip: Observability of features depends on the specific step in the procurement timeline, impacting when predictive models could access them.
Characteristics examples
- x4,j(i) includes complexity of the tender notice and month indicators 34.
- x5,b(i) includes indicator for set-aside for MSEs 34.
- x8,f(i) includes indicator for young firm and past kamikaze outcomes for bidders 35.
organization and setup tasks for the integrated assignment
Organization tasks
- Coordination is required to form groups of 3–4 people 44.
- Names must be added to one of the designated GROUPS within UFORA 44.
- A service for sharing data must be selected, such as Google Drive, Dropbox, or OneDrive 44.
- Deadlines should be checked for overlaps with other courses' deadlines and exams 44.
- Some deadline adjustments are possible upon review 44.
Assignment 1 context and goals
- Assignment 1 involves a reproducible graphical analysis 42 45.
- The goal is to write a policy report on bid-rigging in public procurement for the antitrust agency 46.
- The agency seeks a summary of characteristics of kamikaze auctions 46.
- Guidance is required on investigating and sanctioning kamikaze auctions 46.
- Legal action is appropriate only if kamikaze auctions suggest anti-competitive practices like collusive behavior 46.
Assignment 1 data preparation and analysis
- The raw input data is in the file
data science assignment 1 group x.csv47. - The dataset requires cleaning before analysis can commence 47.
- Data cleaning hints include identifying duplicate auctions 47.
- Identify auctions that cannot be kamikaze by definition during cleaning 47.
- Outliers in the distribution of collusion markers must be identified 47.
- Ensure all graphs use the same set of non-missing and non-outlier observations 47.
- Derive insights from unconditional and conditional distributions of the kamikaze indicator 48.
- Analyze how the frequency of kamikaze auctions varies across time and space 48.
- Compare the collusion markers between kamikaze and non-kamikaze auctions 48.
- Assess if the magnitude of difference in markers changes when comparing auctions within the same year or agency 48.
Assignment 1 reproducibility and structure
- Readers must be able to reproduce the estimating sample from raw data using the report's data section 49.
- Provide "press-play" reproduction codes for generating the estimating sample 49.
- Provide reproduction codes for generating all graphs in the report 49.
- Follow best practices of scientific reproducibility outlined in Lecture 2 49.
- A README file must explain how to run the code to reproduce results 49.
instructions for assignment 1
Reproducibility requirements
- Ensure the reader can reproduce the estimating sample from raw data using the data section 49.
- Provide press-play reproduction codes for generating the estimating sample 49.
- Provide press-play reproduction codes for generating the graphs 49.
- Follow best practices for scientific reproducibility presented in Lecture 2 49.
- Write a README file detailing how to run the code to reproduce results 49.
Report structure
- The report must begin with an executive summary stating key insights concisely, ideally in bullet points 50.
- Each graph in the report must summarize one of the key insights from the executive summary 50.
- Follow principles of data visualization presented in Lecture 2 50.
Deliverables
- Assignment 1 consists of three deliverables in total 51.
- Deliverable 1: Policy report in PDF format 51.
- Deliverable 2: Replication package in R 51.
- Deliverable 3: README file in TXT format 51.
Suggested plan of action
- Avoid splitting tasks and working in isolation 52.
- Collaborate by sitting together and working on one computer 52.
- Rotate the role of the main coder among team members 52.
- Ensure everyone runs and fully understands all the provided code 52.
-
Tip: Comprehensive reproducibility requires providing both the data steps and runnable code snippets 49
instructions for assignment 2: reproducible regression analysis
Core idea
- The assignment requires writing a technical note based on the policy report from Assignment 1 concerning kamikaze auctions 54.
- The audience is an antitrust agency needing to evaluate economic costs and target legal action 54.
- The analysis must be fully reproducible, providing code to generate the sample, graphs, and results 59.
Data handling and regression setup
- The basic input is the raw data from the file
data science assignment 2 group x.csv55. - Data cleaning of missing variables must occur before regression analysis 55.
- Ensure regressions across table columns use the exact same set of non-missing observations 55.
- The dependent variable for regression models must be the logarithm of the unit price 56.
- Outlier cleaning must be performed after the regression analysis 58.
Regression analysis requirements
- Derive insights from the relationship between the unit price paid by the government and the kamikaze indicator 56.
- Investigate how the kamikaze effect on unit prices varies across time, products, and agencies 56.
- Replicate Table 2, Columns and from Fazio and Zaldokas as a starting point 1 2 57.
- Use Ordinary Least Squares (OLS) regression with fixed effects (FEs) to estimate the Average Treatment Effect (ATE) 57.
- Use OLS regression with interactions between the treatment and control variables to estimate Conditional Average Treatment Effects (CATE) 57.
- Prediction methods are explicitly not allowed in Assignment 2 57.
- The partition regression theorem can help specify simpler regressions that recover coefficients from multiple fixed effects models 58.
Outlier detection and visualization
- Use graphical tools to assess how results change under different outlier-cleaning methods 55 58.
- Identifying outliers in multivariate regressions containing many fixed effects is a complex task 58.
- Use statistical methods to identify regression outliers 58.
-
Tip: For outlier identification in high-dimensional FE models, methods leveraging the partition regression theorem might simplify the calculation of influence statistics 58.
Reproducibility and structure
- Provide press-play reproduction codes for generating the estimating sample and the graphs 59.
- Follow scientific reproducibility best practices outlined in Lecture 2 59.
- Write a README file detailing how to run the code to reproduce all results 59.
- The technical note must begin with an executive summary stating key insights concisely, preferably in bullets 60.
- Each graph presented must summarize one key insight from the executive summary 60.
- Deliverables include: Technical note (PDF), Replication package (R), and README file (TXT) 61.
instructions for assignment 3: prediction model
Core idea
- The assignment requires estimating a prediction model for the likelihood of a kamikaze auction in-sample 64.
- The goal is to uncover features predicting risk and measure risk using pre-auction information 63.
- The prediction model is built for internal auditors of a court of audits to prevent illegal practices like collusion 63.
- Out-of-sample prediction methods are explicitly disallowed for this assignment 65.
Key facts
- The core modeling technique required is estimating a Generalized Linear Model (GLM) 64.
- The GLM's likelihood output must be converted into a discrete prediction (kamikazei=0,1) for each auction 64.
- Required outputs based on discrete predictions include calibration plots and a confusion matrix 64.
- Performance statistics related to the model must also be computed 64.
- The model choice and variable inclusion must be carefully motivated using statistical or economic arguments 65.
Key concepts
- The model's objective dictates the careful motivation of both the choice of GLM and the included predictor variables 65.
- The discrete prediction variable is binary, representing the event (kamikaze or not) 64.
- Model performance assessment relies on the confusion matrix and derived performance statistics 64.
- Calibration plots are required to visually assess how well predicted probabilities match observed outcomes 64.
Implications
- Methodological choices (model and variables) must be justified explicitly in the presentation 65 66.
- The final product is intended for practical use in identifying and preventing potential illegal auction practices 63.
- The presentation must dedicate time to presenting and motivating the main methodological choices 66.
-
Tip: Since only in-sample prediction is allowed, focus heavily on model fit justification and interpretation rather than cross-validation techniques 65
Deliverables
- The assignment requires three distinct deliverables 67.
- Deliverable one: Slides presented in PDF format 67.
- Deliverable two: Replication package coded and delivered in R 67.
- Deliverable three: A comprehensive README file supplied in TXT format 67.
-
Example: The presentation should use a table to display calculated performance statistics and a graph to show predictor importance 66
assignment 4: out-of-sample prediction context and goals
Core idea
- Assignment 4 requires creating an algorithm for out-of-sample prediction of kamikaze auctions 69.
- The goal is to develop an Early-Warning System (EWS) for internal auditors 69.
- The EWS must flag auctions identified as high-risk for kamikazes before they occur 69.
Context and objectives
- The context is predicting events (kamikaze auctions) using previously developed technical insights 69.
- The client is a court of audits aiming to prevent illegal practices like collusion 69.
- The final product must clearly specify how the forecasting model output selects auctions receiving a red-flag 71.
Methodological considerations
- Must carefully motivate decisions regarding unbalanced classes in the data 70.
- Must justify the selection of the preferred performance metric 70.
- Must justify the preferred prediction method and model specification used 70.
- Justifications can rely on statistical or economic arguments 70.
- Citing references that motivate best practices for forecasting events is necessary 70.
- Causal machine learning tools are explicitly not allowed for this assignment 71.
Out-of-sample usage
- The EWS specification must detail how model output translates into red-flag selection 71.
- Citing references that motivate using out-of-sample prediction to build risk measures is recommended 71.
-
Tip: Ensure all motivations for performance metrics and class handling directly align with the goal of building a reliable EWS for auditors 70
defining reproducible research and its classes
Core idea
- The first definition of reproducible research involved the possibility of replication by other scientists 76.
- Reproducible research is generally categorized into two classes: replication and robustness 76 77.
Key facts
- A replication exercise must yield the same quantitative results as the original study 77 78 79 80.
- Robustness exercises are distinguished from replication exercises by this strict requirement for identical quantitative results 77 78 79 80.
Key concepts
- Replication: Requires that the estimated parameters in the new study share the sampling distribution of the original study's parameters 77 78 79 80.
- Robustness: Distinguished from replication by not strictly requiring the same quantitative results 77 78 79 80.
Implications
- The distinction between replication and robustness centers on the required similarity of numerical outcomes 77 78 79 80.
-
Tip: When studying, remember that replication demands statistical identity (same sampling distribution of estimates), whereas robustness implies broader confirmation under varied conditions
definitions: replication versus robustness
Core idea
- Reproducibility is categorized into two main classes: replication and robustness 77 78 79 80.
- The distinction between replication and robustness hinges on the expected quantitative outcomes 77 78 79 80.
Key concepts
- A replication exercise is expected to yield the same quantitative results as the original study 77 78 79 80.
- In a replication, estimated parameters in the new study share the sampling distribution of the original study's parameters 77 78 79 80.
- Robustness exercises are distinguished from replications by not being required to yield the exact same quantitative results 77 78 79 80.
Implications
-
Tip: Remember that replication focuses on exact numerical correspondence, whereas robustness assesses stability across minor variations
- Replication confirms the original findings' precision based on shared statistical distributions 77 78 79 80.
- The primary goal of robustness is showing that conclusions hold even when slight changes are made to the analysis 77 78 79 80.
definition and types of robustness checks
Core idea
- Economic analysis relies on parameter estimates, like sample averages or treatment effects 81.
- Parameter estimates vary based on statistical methods, population definition, and sample realization 82.
- Replication involves estimating parameters with the same sampling distribution 83.
- Robustness involves estimating parameters from a different sampling distribution 88.
Types of replication
- Replication has two main forms: verification and reproduction 83.
- Verification (or pure replication) repeats the analysis using the exact same sample 84 85.
- Verification detects measurement, coding, or data construction errors, and scientific misconduct 84 85.
- Reproduction applies the same statistical analysis to a new sample from the identical population 87.
- Reproduction tests result stability across different sample realizations 87.
- Reproduction can detect sampling error, low statistical power, and verification-detectable errors 87.
Types of robustness checks
- Robustness checks include reanalysis and extension 88.
- Reanalysis applies a different statistical analysis to the same data or another sample from the same population 89.
- Reanalysis tests result holding under alternative model specifications 89.
- Reanalysis detects specification search and selective coding of variables 89.
- Extension applies the original analysis to a new population (e.g., different time or place) 90.
- Extension tests result generalization beyond the initial study context 90.
- Extension detects issues related to external validity and the exclusion of influential outliers 90.
-
Tip: Replication (Verification/Reproduction) checks internal validity by keeping the sampling distribution constant, while Robustness (Reanalysis/Extension) checks external validity by varying the distribution or model 83 88
why should we care about replication failures?
Core idea
- The public should worry about replication failures according to the verification criteria 96.
- Replication failures are concerning because flawed research can lead to the implementation of costly policies 96.
Key facts
- Active learning is a related concept to understanding replication issues 96.
- The concern about replication failures relates directly to public policy implications 96.
Implications
- Flawed research driven by failures to replicate can result in substantial financial expenditures for the public 96.
- Understanding replication challenges is necessary for sound, evidence-based decision-making in policy formation 96.
-
Tip: Focus on how the reliability of scientific findings directly impacts real-world resource allocation and policy effectiveness
replication examples and responses
Core idea
- Replication examples demonstrate the process of reproducing prior research findings .
- These examples follow a structure involving an initial study, the replication attempt, and the subsequent responses to the replication results .
- The document outlines at least three distinct examples of replication scenarios .
Key facts
- Example 1 focuses on a study followed by its replication attempt and responses .
- Example 2 details a second scenario involving replication and subsequent responses .
- Example 3 presents a third specific instance related to replication .
Implications
- Analyzing these varied examples helps understand the dynamics of scientific verification and reproducibility .
- Responses to replication outcomes are critical components in interpreting the robustness of original findings .
-
Tip: Focus on the structure: Original Study → Replication → Response, as this pattern is consistent across all examples
replication examples
Core idea
- Replication examples illustrate the concept of reproducibility in research settings .
- The examples provided span across Example 2, Example 3, and Example 4 of the replication analysis .
Key facts
- Replication Example 2 details its responses on page 105 .
- Replication Example 3 is detailed across pages 106 and 107 .
- Example 3 includes responses documented on page 107 .
- Replication Example 4 is presented on page 108 .
- Responses for Example 4 are specifically listed on page 109 .
Implications
- The sequential nature of these examples implies a structured evaluation of replicability .
- Tracking responses across examples (2, 3, and 4) suggests an increasing complexity or variety in the replication assessment .
-
Tip: Focus on identifying what specific metric or result is being replicated or questioned in each sequential example (2, 3, 4) during study review
managing file sharing and version control practices
Core idea
- Reproducible research relies on organizing work, coding for others, and automating processes .
- File organization and version control are critical components of organizing the research workflow .
Organizing workspace for reproducibility
- Structure the project directory so folders contain homogeneous elements like data, codes, text, and documentation .
- Distinguish between inputs (e.g., raw data) and outputs (e.g., regression results) within the structure .
- Establish and systematically follow a consistent naming convention for programs and files .
- Use short names, lower case characters, and underscores for separation in file naming .
- Avoid using special characters or white-spaces when naming files .
- Design a workflow starting from raw data and ending with a final output document (e.g., PDF report) .
- Use numbers at the start of program names to dictate the required order of execution .
- Example order:
0 download raw data.R,1 preparing data.R,2 ols regressions.R.
File sharing and version control systems
- Sharing files should be managed via a shared online folder system like Dropbox, Google Drive, or OneDrive .
- A standardized preamble should be created for use across all scripts and among collaborators .
- Version control systems (VCS) like GitHub or GitLab are recommended for tracking changes .
- Collaborative writing tools such as Google Docs and Overleaf support joint document creation .
-
Tip: While VCS and collaborative writing tools are recommended, this course does not cover their practical implementation .
Manual version control practices
- Manual version control involves creating separate code files for each distinct graph or table output .
- Save a new version of the code file every time a relevant update is made to the resulting outputs .
- Use descriptive suffixes to identify the specific version of code scripts .
- Example suffixes:
0 download raw data 01102025.Ror2 ols regressions v13.R. - Maintain a dedicated subfolder within the main code folder to archive previous versions of the code scripts .
-
Example: If the final paper costs 100 dollars, ensure documentation reflects this amount clearly. (Note: This specific example citation appears related to context outside version control, but is included
principles for writing code readable by others
Core idea
- Code must be written for others, including your future self .
- Key programming style goals include simplicity, clarity, and generality .
- Consistency, distinctiveness, and meaningfulness are vital for naming conventions .
Convention on layout
- Limit the number of characters per line, typically to 80 .
- Place spaces around mathematical operators, e.g., use
x = 1instead ofx=1. - Define variables at the top, followed by functions, and then executed statements .
- Write one script dedicated to a single, specific task .
Convention on naming
- Names should be consistent, distinctive, and highly meaningful .
- Choose a convention combining uppercase/lowercase letters, underscores, and digits .
- Use uppercase letters for parameters .
- Use lowercase letters for variables and functions .
- Use prefixes to indicate variable type, such as indicator, share, percentage, or count .
- Example prefix for an indicator variable:
dum women.
-
Example: The name
dum womenis preferred overgenderbecause it reveals that it is an indicator variable, wheredum women=1if the observation is a woman
Writing generic code
- Adhere to the DRY principle: Don’t Repeat Yourself .
- Avoid repeating code blocks by utilizing functions and scripts .
- Use relative paths at the start of the code .
- Set usernames in macros, especially in collaborative projects .
- Follow Drukker’s dictum: Never type anything that can be obtained from a saved result .
master program for research automation principles
Core idea
- Automation must be prioritized for research steps to ensure reproducibility .
- A master program coordinates all analytical steps in a logical sequence .
- Documentation should cover any steps that absolutely cannot be automated .
Automating the process
- Code everything to avoid manual steps like point-and-click tools (e.g., MS Excel) .
- Drag-and-drop and copy-and-paste actions are difficult to reproduce reliably .
- Save all resulting code, output logs, tables, and figures generated during the analysis .
Automating output and exports
- Create one distinct script file for generating each specific output, like tables or graphs .
- Produce outputs in portable formats, such as.TXT or.TEX for tables .
- Use formats like.PNG or.JPG for graphical outputs .
- Utilize software-specific commands to directly produce desired output formats (e.g.,
texregin R oresttabin Stata) .
Linking and dynamic documents
- Use shell or batch scripts (for Windows) to integrate different software tools sequentially .
- Modern packages (e.g., R Markdown) create dynamic documents blending code execution and text narrative .
- Inline code generation automatically updates quantitative data, like sample counts or descriptive statistics, within the document .
-
Tip: Dynamic documents ensure that if the underlying code changes, all statistics and tables in the final document update automatically, enhancing reproducibility
Master program structure
- The master program should begin with a clear preamble section .
- Use relative file paths within the master program structure .
- Define machine, user, and folder specifications using local macros .
- Set uniform analysis parameters (e.g., clusters, cutoffs) using global macros .
- Group variables (e.g., outcomes, treatments, controls) using global macros for easy referencing .
- Sections of the program should map directly to the structure of the final paper .
- Order should generally follow: Sample, Descriptive analysis, Causal analysis, Robustness, and Mechanisms .
- The master program calls a separate script for every distinct paper output required .
-
Example: A Stata master program illustrates calling specialized scripts sequentially corresponding to the paper's logical flow
master program example 2 structure
Core idea
- This section details the structure of Example 2 within the Master Program context .
- The structure is presented across sequential pages, illustrating specific components of the example .
Key facts
- Example 2 follows Example 1 in the sequence presented in the material .
- Page 141 begins the description of Master Program Example 2, marked as page 56 in the source .
- Page 142 continues Example 2, noted as page 57 .
- Page 143 continues Example 2, noted as page 58 .
- Page 144 continues Example 2, noted as page 59 .
- Page 145 continues Example 2, noted as page 60 .
- Page 146 concludes the presented segment of Example 2, noted as page 61 .
Key concepts
- The structure relies on sequential presentation across multiple document pages .
- Each page segment (56 through 61) contributes to the complete understanding of Example 2's structure .
- The example's structure must be inferred from the continuous presentation across these pages .
-
Tip: Since specific details of Example 2's content are not provided, focus on recognizing the sequential scaffolding used to present complex program structures
Implications
- Understanding Example 2 requires referencing the entire sequence from page 141 through 146 .
- The structure demonstrates how comprehensive examples are documented across an entire booklet section .
- This template suggests Master Program examples are detailed and extensive .
duplicated data issues and handling
Duplicated data causes
- Duplicated data can arise from system errors, like software exporting records twice .
- Inconsistent identifiers across different data versions contribute to duplication .
- Human error includes typing or uploading data multiple times without changing the ID .
- Joining operations may append the same dataset twice, causing duplicates .
- Survey issues include mistakenly assigning one ID to two respondents or interviewing the same person twice .
Key questions addressed
- Economists must consider why duplicated data matters .
- Detection methods for identifying duplicated records are crucial .
- Handling strategies for managing identified duplicates must be decided .
Motivation for concern
- Duplicated data severely distort the representativeness of the dataset .
- Overweighting these duplicates leads to biased estimates and flawed statistical inference .
Detection and handling when a unique identifier exists (Case 1)
- Step 1: Verify if multiple observations share the exact same unique identifier .
- Step 2: If IDs match, check if the corresponding observations are completely identical .
- Step 3: If identical, the standard action is to drop one of the duplicate observations .
- If observations are not identical but corrupted (e.g., missing values), drop the corrupted cases .
- If observations are not identical but none are corrupted, randomly drop one instance .
Detection and handling when a unique identifier does not exist (Case 2)
- Step 1: Check if multiple records are entirely identical across all fields .
- Step 2: If identical, verify these records truly represent duplicates of the same underlying unit .
- Step 3: The final action is to keep only one observation for each set of duplicates found .
-
Tip: Data manipulation is essential because "dirty data lead to misleading results"; clean data clearly show when a model fails
example of detecting and dealing with duplicated data
Core idea
- Detecting and dealing with duplicated data is essential for maintaining data quality and integrity in analysis .
- Duplication can occur due to merging, joining, or multiple data entry points .
- The process involves identifying potential duplicates and then deciding on an appropriate resolution strategy .
Detecting duplicated data
- Duplicate records share identical values across all relevant attributes or a key subset .
- Simple filtering can identify exact duplicates across all columns .
- For identifying records that are almost identical, fuzzy matching or similarity metrics are required .
- A basic SQL example uses
GROUP BYandHAVING COUNT(*) > 1to find exact duplicates .
- The query groups records based on selected columns .
- It then filters groups where the count exceeds one .
- To find duplicates based on a subset of columns (e.g., name and address), only those columns are included in the
GROUP BYclause . - When checking for duplicates across a large dataset, performance considerations suggest using indexing on the key columns .
Dealing with duplicated data
- Once duplicates are identified, the next step is deduplication or merging .
- Strategies depend on whether one record should be kept or if data needs to be merged across duplicates .
- A common method involves selecting one record to keep (the "master" record) .
- If only one complete record needs to be retained, the duplicates can be deleted after selecting the keeper .
- Deduplication often requires a deterministic rule to choose which record prevails .
- For example, keeping the record with the most recent timestamp or the most complete set of fields .
-
Tip: When dealing with potentially non-exact duplicates, consider calculating a similarity score (like Jaro-Winkler distance) instead of relying solely on exact matches
-
Example: To find records duplicated solely by name and birth date:
SELECT name, birth_date, COUNT(*) FROM table GROUP BY name, birth_date HAVING COUNT(*) > 1;
missing data handling and analysis
Core idea
- Economists care about missing data because non-random missingness causes inconsistent estimates in econometrics 15 16.
- Data scientists are concerned because frequent missing data reduces predictive accuracy 15 16.
- Handling missing data involves addressing three key questions: why it matters, how to detect it, and how to handle it 14.
Causes of missing data
- Causes include machine errors like power cuts or internet failures 13.
- Human errors, such as mistakes during data entry, lead to missing observations 13.
- Merging data sets that have non-overlapping observations is a common source 13.
- Survey issues such as non-response or respondents dropping out create missing values 13.
Detecting missing data
- Detection involves three main steps for imported files 15.
- Step 1: Identify the specific codes used for missing values in the input file (e.g., " ", "-", or ".") 15.
- Step 2: Import the data and verify that these codes are converted correctly, often appearing as
NAin statistical software like R 15. - Step 3: Inspect remaining variables for specific missing data codes often used in surveys (e.g., "-7", "-8", or "-9") 15.
Understanding missingness patterns
- Assess the frequency of missing observations; very small frequencies suggest randomness 18.
- Check if missingness is concentrated in specific variables, which might indicate non-response or incomplete merges 18.
- Determine if missingness clusters within certain units, suggesting those units disappeared from the dataset 18.
- Examine correlation between missingness and observable variables; no correlation suggests missingness is random 18.
-
Tip: Duplicated data is a related issue requiring separate attention, distinct from handling missing values 11
managing missing data
Understanding missing data causes
- Frequency of missing observations can suggest randomness if very small .
- Missingness concentrated in a few variables suggests non-response or incomplete merges .
- Missingness concentrated in a few units suggests units are disappearing from the data .
- No correlation with observables suggests the missingness is random .
Solutions for missing data: Case deletion
- Case deletion removes all units missing data in at least one variable .
- This ensures consistency across all tables and graphs using the same observations .
- Problem: Decreases sample size when missingness is frequent .
- Problem: Causes bias if the missingness is non-random .
Solutions for missing data: Imputation
- Imputation replaces missing values using reasonable estimates .
- Simple imputation uses the mean, median, or recent non-missing observations .
- Regression imputation uses predicted values from a regression model on non-missing data .
- Imputation maximizes sample size and avoids sample selection bias .
- Problem: Imputation can introduce bias if the missingness mechanism is non-random .
-
Tip: Assessing where missingness is concentrated (variables vs
- units) informs potential causes
-
Example: If missingness correlates with an observed variable, case deletion might introduce bias due to non-random missingness
motivation for studying outliers
Core idea
- Outliers are observations deviating markedly from the rest of the sample data .
- Economists study outliers because their inclusion or exclusion significantly alters research conclusions .
Key facts
- An outlier can be suspected of being generated by a different underlying mechanism .
- Causes of outliers include human errors, such as typing mistakes (e.g., 100 vs. 1000) .
- Data processing errors are another cause, like incorrect unit conversions (e.g., dollars vs. cents) .
- Sampling errors can introduce outliers by mixing distinct populations (e.g., firm vs. household income) .
- Outliers are not always errors; they can represent genuine extreme values, such as the income of the top 0.1 percentile .
- The decision to keep or drop outliers can dramatically drive research findings .
Key concepts
- Grubbs' definition: An observation that appears to deviate markedly from other sample members .
- Barnett & Lewis' definition: An observation inconsistent with the remainder of the data set .
- Hawkins' definition: An observation deviating enough to suggest a different generation mechanism .
- Outliers may signal events of significant interest, such as fraud or tax evasion .
Implications
- Researchers must be aware that findings might change based on the treatment of extreme observations .
- Identifying outliers allows for the investigation of potentially significant underlying phenomena .
- Proper handling of these deviations is crucial for maintaining the validity and generalizability of economic models .
-
Tip: When analyzing data, always document the decision criteria used for including or excluding any extreme observations to ensure transparency in research
outliers as variables of interest and cases
Outliers as variables of interest
- Outliers can serve as variables of interest in specific analytical contexts .
- Detecting corporate corruption: Abnormally low tax payments relative to revenue in "spaceman firms" suggest fund diversion .
- Detecting trade misreporting: Univariate outliers in the export/import gap between two countries for a product signal misreporting .
- Detecting electoral fraud: Bivariate outliers combining unusually high turnout and incumbent vote share can identify ballot stuffing .
Outliers as cases
- Outliers can be categorized based on the dimensionality of the data they affect .
- This includes univariate outliers .
- Multivariate outliers are also a category, covered in a later section .
- Regression outliers are another distinct case type, covered elsewhere .
- Specific case types in regression include x-outliers .
- Specific case types in regression also include y-outliers .
-
Tip: When outliers are the primary subject of inquiry (variables of interest), standard anomaly detection techniques are applied to flag suspicious observations
-
Example: If analyzing tax data, the observation where RevenueTax Paid is near zero for a high-revenue firm would be an outlier of interest
univariate outlier detection via visual inspection
Core idea
- Visual inspection is one primary method for detecting univariate outliers .
- This contrasts with methods using descriptive statistics or rules of thumb .
Key tools for visual inspection
- The Box and Whisker Plot is a key visualization tool for outlier detection .
- Kernel Density Plots are used to nonparametrically visualize data density .
Box and whisker plot elements
- The plot relies on the median, Med(x) .
- It uses the Interquartile Range, calculated as IQR(x)=Q3(x)−Q1(x) .
- The fences define the limits for non-outlier data points .
- The lower fence is Q1(x)−1.5×IQR(x) .
- The upper fence is Q3(x)+1.5×IQR(x) .
- Points falling outside this fence interval are flagged as potential outliers .
-
Tip: The $1
- 5 \times \text{IQR}$ multiplier is a standard convention for defining mild outlier fences on a box plot
Kernel density plot interpretation
- Kernel Density Plots show the distribution shape of the variable x .
- Outliers can be suggested by density plots showing non-normal shapes .
- Look for evidence of right skew, left skew, or multimodality .
- Observations far from the main density peaks may indicate outliers, especially those with "fat tails" .
-
Example: If a Kernel Density Plot shows two widely separated peaks, this indicates multimodality and suggests potential separate groups or outliers
univariate outlier detection via descriptive statistics
Core idea
- Descriptive statistics indicate the presence of outliers through metrics reflecting dispersion, asymmetry, and tail weight .
- A primary limitation is that these methods show if outliers exist but not which specific observations they are .
Key concepts
- Coefficient of Variation (CV): Measures relative variability; high values suggest extreme dispersion .
- Indicates potential outliers if CV(x)>1 .
- Formula: CV(x)=xˉσSD(x) .
- Skewness: Quantifies the asymmetry of the distribution .
- A large absolute skewness, ∣Skew(x)∣≥1, suggests long tails indicative of outliers .
- Formula: Skew(x)=N1∑i=1N(σSD(x)xi−xˉ)3 .
- Excess Kurtosis: Measures the heaviness of the distribution tails relative to a normal distribution .
- Outliers are suggested if Excess Kurtosis, Kurt(x)−3>1 .
- Formula definition for Kurt(x): N1∑i=1N(σSD(x)xi−xˉ)4 .
Implications
- High CV signals substantial relative spread, often driven by extreme values .
- Skewness values ≥1 or ≤−1 point to distributions heavily weighted towards one side by extreme points .
- High excess kurtosis suggests the presence of heavy tails or extreme observations .
-
Tip: Descriptive statistics provide an initial diagnostic check for data quality but must be supplemented by identification methods like box plots or Z-scores for pinpointing specific outliers
problems and solutions for the univariate outliers rule of thumb
Core idea
- The standard rule of thumb for univariate outliers has four main problems .
- Outlier detection methods can suffer from masking (failing to flag true outliers) or swamping (flagging non-outliers as outliers) .
Problems with the standard rule of thumb
- Problem 1: It relies solely on univariate statistics, ignoring multivariate relationships .
- Problem 2: Its application assumes the underlying data distribution is normal .
- Problem 3: The fixed cutoff value does not account for sample size (N) or required statistical significance (α) .
- Problem 4: The sample mean (xˉ) and standard deviation (sx) used are sensitive to and biased by the presence of outliers themselves .
Solutions for univariate outlier problems
- For Problem 1, use multivariate statistics like the Mahalanobis distance as a solution .
- For Problem 2 (non-normal continuous data), use transformations like y=Log(x) .
- For Problem 2 (discrete variables), solutions include using the bottom and top percentiles, such as P1 and P99 .
- For Problem 3, the significance level must be corrected for multiple hypothesis testing due to sample size dependence .
- The actual probability of rejecting H0 (no outliers) becomes α∗=1−(1−α)N .
- For a two-sided test, the relevant standardized scores are zα∗/2 and z1−α∗/2 .
- For a one-sided test, the cutoffs are zα∗ or z1−α∗ .
- Formally, no outliers exist if sxxi−xˉ≤z1−α for all i, where x(N)=max{x1,…,xN} .
- For Problem 4, replace xˉ and sx with robust statistics such as the median and IQR .
Robust rule of thumb
- The robust rule flags observation i as an outlier if:
- 7413 \times \text{IQR}(x)} > 3$$
- The sample median Med(x) is robust because it converges in probability to the mean (μ) under normality .
- The sample median for ordered data x≤⋯≤x(N) is x(2N+1) (N odd) or 2xN/2+xN/2+1 (N even) 1 .
- The Interquartile Range (IQR(x)) is robust to outliers .
- Under normality, IQR(x) converges in probability to approximately 1.3496×σ .
- IQR(x) is calculated using quartiles: x(⌊N/4⌋) and x(⌈3N/4⌉) .
-
Tip: The factor $0
- 7413intherobustruleisderivedfromtherelationshipbetweentheIQRand\sigmaundernormality(since1/1
motivation for studying multivariate outliers in economics
Core idea
- Economists care about multivariate outliers because they affect measurements depending on multiple variables .
- Multivariate outliers can bias the measurement of statistics dependent on multiple variables .
- They can bias estimates of correlations and causal effects between variables .
Key facts
- Univariate outlier inspection is insufficient because some data points are outliers only in the multivariate sense .
- Multivariate outliers can represent outcomes of specific economic interest .
- Examples of affected statistics include per capita municipal statistics .
- Firm-level statistics normalized per worker are also susceptible to bias .
Key concepts
- An outlier in multivariate space may not be an outlier in any single univariate distribution .
- Height vs. Weight Example: An adult profile of 1.95 m height and 55 kg weight might be a multivariate outlier, though neither measure is individually extreme .
- Risk vs. Return Example: A stock with low risk and high return can be a bivariate outlier even if individual risk and return metrics are not extreme .
- Economic Interest Example: A data point showing low self-declared income coupled with high consumption is an outcome of interest .
- Economic Measurement Example: Excess return over risk is a variable measurement affected by multivariate outliers .
Implications
- Ignoring multivariate outliers leads to incorrect measurement of multi-dimensional economic variables .
- Failure to address them leads to biased estimates of partial correlations among variables .
-
Tip: Always consider relationships between variables; relying only on individual variable inspection can mask crucial, unusual economic observations
multivariate outliers: feasible estimates and distributional results
Core idea
- Multivariate outlier detection measures distance from the mean vector μ .
- The full measure requires feasible estimates for μ and Σ .
- The standardized squared Mahalanobis distance, MDi2, follows a Chi-squared distribution under normality assumptions .
Distance measures evolution (Bivariate case)
- Euclidean Distance (Di): Measures raw distance, Di=(x1i−μ1)2+(x2i−μ2)2 .
- Problem: It is unscaled, weighting all components equally regardless of variance .
- Scaled Distance (Ignoring Correlation): Used when Σ is diagonal, MDi=σ12(x1i−μ1)2+σ22(x2i−μ2)2 .
- Problem: It ignores correlation (ρ12) between variables .
- Full Mahalanobis Distance (MDi): Accounts for variance and correlation structure .
- MDi=(xi−μ)⊤Σ−1(xi−μ) .
-
Tip: The Mahalanobis distance is the natural generalization of the squared Z-score to multiple dimensions, inherently accounting for correlation
Feasible estimates
- Population parameters μ and Σ are unknown and must be estimated from data X={x1,…,xN} .
- Feasible estimate for the mean vector (μ): μ^=xˉ=N1∑i=1Nxi .
- Feasible estimate for the covariance matrix (Σ): Σ^=N−11∑i=1N(xi−μ^)(xi−μ^)⊤ .
Distributional results (Assuming x∼N(μ,Σ))
- Result 1: Transformation to standard normal: Σ−1/2(x−μ)∼N(0K,IK) .
- Result 2: Squared standard normal vector follows Chi-squared: If z∼N(0K,IK), then z⊤z∼χK2 .
- The squared Mahalanobis distance relates to these results: MDi2=(xi−μ)⊤Σ−1(xi−μ) .
- This implies MDi2∼χK2 .
- The cutoff value for detecting an outlier at significance level α is χK,1−α2 .
-
Example: For a K=3 dimensional dataset (p=3), if the data is multivariate normal, the squared Mahalanobis distance of an observation follows a χ32 distribution
detecting and handling multivariate outliers
Core idea
- Multivariate outlier detection and handling are crucial steps in data analysis .
- Solutions involve robust detection methods or employing robust estimation techniques .
Robust detection methods
- Apply a robust rule of thumb for initial identification .
- Trim observations exhibiting very high Mahalanobis distances .
Robust estimation alternatives
- When outlier removal is undesirable, use estimation methods less sensitive to extreme values .
- An example is utilizing quantile regression instead of Ordinary Least Squares (OLS) .
-
Tip: Always consider the impact of outliers on model assumptions before deciding between removal and robust estimation
-
Example: If outliers significantly skew the mean calculation, robust methods focus on central tendencies less affected by them
principles for integrating graphics and text
Title style
- Titles should resemble a newspaper headline .
- Titles must summarize the main takeaway of the graph, not just describe it .
- Avoid titles that are purely descriptive .
Adding explainers
- Include text that explicitly explains the crucial points found within the data .
- Use colors within the graphic to highlight visual gradients .
- For example, use red to denote decreases and blue for increases in a measured variable .
-
Tip: Effective integration means the graphic and accompanying text work together to deliver a clear, immediate message
principle 4: avoiding the spaghetti chart
Core idea
- The goal is to actively avoid creating a "spaghetti chart" visualization .
- The recommended strategy is the "small multiples approach" .
- Do not plot excessive amounts of data within a single graph .
Key concepts
- The small multiples approach involves creating several smaller graphs using fractions of the same dataset .
- Examples include showing different variables within one sample or one variable across different samples .
- Arrange these smaller graphs in a clear, logical order .
- Maintain consistency across all small multiples regarding layout, size, font, and color choices .
- Ensure that each individual graph remains easily readable .
Implications
- Implementing the small multiples approach is facilitated by Principle 2 of scientific reproducibility .
- Principle 2 emphasizes "Code for the others," specifically using functions for generic, non-repeating code blocks .
-
Tip: Small multiples break down complex data into manageable, comparable chunks, improving interpretability over a single crowded chart
-
Example: Instead of one graph showing temperature, pressure, and humidity over time, create three separate small line charts for each variable, aligned by their shared time axis
main types of graphs: comparing categories
Core idea
- The objective is comparing variable values across different groups or categories 3.
- The bar chart is the superior choice for comparing categories 3.
- Bar charts plot vertical or horizontal bars where length/height represents the data value 3.
- Bar charts rank highly perceptually because plotted values are not distorted 3.
Key facts
- Bar charts can be simple, paired, or stacked variations 3.
- The y-axis (value axis) must start at zero to prevent distorting relative magnitudes 4.
- If there are few categories, sort the bars based on their y-values 4.
- If there are many categories, sort them using x-values, such as alphabetical order 4.
- Bar charts should not have broken bars to accommodate outliers 5.
- Use multiple plots if dealing with data requiring a broken scale 5.
Key concepts
- Use short labels for categories and avoid rotation on the axis 5.
- Rotate the axis labels if the category labels are too long to fit 5.
- Avoid tick marks on the axes unless they help group categories on the x-axis 5.
- When categories are limited, display values directly on the bars instead of using gridlines 5.
Implications
-
Tip: Since bar charts are judged by length/height, ensuring the value axis starts at zero is the most critical formatting rule for accurate comparison 4
- Proper formatting, especially axis scaling and sorting, ensures the comparison objective is met effectively 4 5.
- Labeling and clutter reduction improve the reader's ability to focus on the data comparison 5.
visualizing data distributions with histograms
Core idea
- Histograms are the best way to visualize data distributions and statistical uncertainty .
- They display the frequency of data points falling into distinct, ordered intervals called bins .
- The height of each bar in the histogram represents the number of observations within that specific bin .
Key concepts
- Bin selection: Choosing appropriate bin widths is crucial for effective visualization .
- Wide bins can hide important patterns in the distribution .
- Narrow bins can obscure the overall shape by making the plot too detailed .
- It is advisable to use automated binning options initially and then adjust them manually if needed .
Plotting multiple distributions
- Two histograms can be overlaid on the same graph to compare distributions across two different groups .
- Use contrasting colors, such as orange and blue, when overlaying histograms for clarity .
Data visualization in R using ggplot
- The basic logic for creating simple plots in
ggplotfollows the structure: Input + Geometry + Labels + Appearance . - Input: Defined using
ggplot(data, aes(x =..., y =...))specifying the data frame and aesthetic mappings . - Geometry: Specifies the plot type; use
geom_histogram()for histograms .
- Other geometries include
geom_bar()for bar graphs andgeom_line()for line graphs .
- Labels: Added using
labs()to set the title, subtitle, caption, and axis labels (x, y, fill) . - Appearance: Controlled using
theme()functions .
theme_minimal()applies a clean, simple background style .- Specific elements like axis titles (
axis.title.x) or plot titles (plot.title) can be customized individually . - Elements can be removed using
= element_blank(). -
Tip: When comparing distributions, ensure the bin width is consistent between the overlaid histograms for a fair visual comparison
relationship graphs for data analysis
Core idea
- Relationship graphs belong to Class 6 of graph types .
- The primary objective is to understand the relationship between the mean of a dependent variable y and an explanatory variable x .
- The most common type of relationship graph is the scatterplot .
Key facts
- Scatterplots display all points {(xi,yi)}i=1N from a sample of size N in a Cartesian coordinate graph .
- The study will cover the composition of the scatterplot and the binned scatterplot (or binscatter) .
- For scatterplots, reveal the association type (e.g., positive or negative correlation) in the graph title .
- The label for the y-axis must be placed below the graph title in parentheses .
- Use short labels for the x-axis label .
Key concepts
- Formatting scatterplots involves using colors to highlight a cluster or contrast multiple clusters .
- A fitted line can be used to emphasize the type of correlation present .
- A bubble chart incorporates a third variable by varying the size of the plotted dots .
- To avoid clutter, do not include labels for every single point in the graph .
- Relationship graphs are distinct from graphs comparing categories, time series, or distributions (Class 5) .
-
Tip: When formatting, ensure the title clearly states the observed correlation type, such as "Positive Correlation between X and Y"
Implications
- Relationship graphs are fundamental for initial diagnostics before applying regression models .
- Visualizing relationships helps identify potential issues addressed later, like regression outliers .
- Visual checks guide decisions on model complexity, such as moving towards multiple linear regression or fixed effect models .
- Proper labeling ensures clear interpretation of the bivariate relationship being analyzed .
scatterplots and formatting
Core idea
- Scatterplots display the relationship between two quantitative variables using Cartesian coordinates 7 8.
- Formatting scatterplots is crucial for clear and accurate communication of data patterns 8.
Key facts
- A scatterplot requires two paired numerical variables, typically represented as (xi,yi) pairs 7.
- The variable plotted on the horizontal axis (x) is generally the independent or predictor variable 7.
- The variable plotted on the vertical axis (y) is usually the dependent or response variable 7.
- Each observation in the dataset is represented by a single point on the plot 7.
Key concepts
- Axis Scaling: The range and tick marks chosen for the x and y axes significantly affect the perceived pattern of the data 9.
- Aspect Ratio: The ratio of the vertical scale to the horizontal scale influences the visual steepness of the relationship shown 9.
- Data Ink Ratio: Maximizing the proportion of ink used for displaying the data itself, rather than non-data elements, improves clarity 9.
- Overplotting: When many data points fall on the same location, distinguishing them requires specific formatting adjustments 10.
- Transitivity of Scale: Changes in scale should not fundamentally change the interpretation of the underlying relationship 9.
Implications for visualization
- Use minimal grid lines, favoring clear axis labels over extensive background markings 9.
- Avoid using 3D effects or chart junk, as they obscure the data interpretation 9.
- Axis origins should typically start at zero unless explicitly necessary to highlight local variation 9.
- If using transparent colors or jittering, ensure the density of points remains interpretable 10.
- Properly labeling the axes with units of measurement (if applicable) is essential for context 8.
-
Tip: When examining scatterplots, always look for the three main features: direction (positive/negative), form (linear/curved), and strength 7
-
Example: If both axes are scaled identically (aspect ratio of 1:1) but the vertical axis is compressed, the positive slope might appear artificially shallow 9
- </document_content>
binscatter as an alternative to scatterplots
Core idea
- Binscatter is the most common alternative when standard scatterplots yield uninformative results .
- It assesses the plausibility of assumptions about the conditional expectation function (CEF) functional form .
Relationship graphs: binscatter step by step
- Step 1: Divide the range of the independent variable (x) into J bins .
- Examples for J include deciles (J=10) or ventiles (J=20) .
- Step 2: Calculate the within-bin means (xˉj, yˉj) for every bin j∈{1,…,J} .
- Step 3: Plot the resulting points (xˉj,yˉj) on a standard Cartesian coordinate graph .
Key concepts
- Binscatter allows assessment of assumptions like linearity, monotonicity, or convexity of the CEF .
- Recent advances address data-driven choice of the optimal number of bins (J) .
- Modern methods incorporate confidence bands to capture uncertainty in estimating the CEF .
- Techniques exist for correct covariate adjustment when estimating conditional effects .
Implications
- Advantage: Provides a clear tool for visually evaluating the assumed functional relationship .
- Disadvantage: Involves a significant loss of information compared to using all individual data points .
-
Tip: Use binscatter when the relationship appears non-linear or noisy in a traditional scatterplot, focusing on the averaged trend within discrete segments
simple linear regression model: basic hypotheses and assumptions
Core idea
- The Simple Linear Regression Model (SLRM) uses an additive model where the stochastic component enters additively: yi=E[yi∣xi+ϵi .
- The model relies on observing a random sample of size N: {(xi,yi)}i=1N .
- The five basic hypotheses (H1-H5) ensure OLS estimators are unbiased, efficient, and allow valid statistical inference .
Basic hypotheses
- The SLRM is defined by five basic hypotheses (H1 through H5) .
- H1: Linearity of the conditional expectation function (CEF) .
- H2: Exogeneity of the regressors .
- H3: Homoskedasticity of the errors .
- H4: No serial correlation among errors .
- H5: Normality of the error term .
Key assumptions (H1-H5 details)
- H1 (Linearity): The CEF of y given x is linear: E[yi∣xi=β0+β1xi .
- H2 (Exogeneity): The error term and the regressor are mean-independent: E[ϵi∣xi=0 .
- H3 (Homoskedasticity): The error term possesses constant variance across observations: Var[ϵi∣xi=σ2 .
- H4 (No serial correlation): Error terms are uncorrelated across different observations: E[ϵiϵj∣xi,xj=0 for i=j .
- H5 (Normality): The error terms are normally distributed: ϵi∼N(0,σ2) .
Implications and Context
- The error term ϵi captures all unobserved factors influencing yi .
- Each pair (xi,yi) in the sample is drawn independently from the population .
- H1-H5 are foundational for deriving desirable statistical properties of OLS estimators .
-
Tip: Remember that H1 through H5 together form the Classical Linear Regression Model (CLRM) assumptions, critical for statistical inference
simple linear regression model: inference and variance estimation
Estimating error variance
- Estimator of the error term variance is σ^2=N−21∑i(yi−y^i)2=N−2RSS .
-
Tip: N−2 is the degrees of freedom in simple linear regression
Variance and standard error estimation
- The variance of the OLS estimator β^ given x is estimated by Var[β^∣x]=∑i(xi−xˉ)2σ^2 .
- The estimated standard error of the OLS estimator is SE[β^∣x=Var[β^∣x] .
Implications of low regressor variation
- Low variation in the regressor rt inflates the variance of the slope estimator β^1 .
- Small variation in rt results in a small denominator ∑t(rt−rˉ)2 in the variance formula .
- Example: If real interest rates (rt) have been nearly constant in the EU, the setting is poor for estimating β1 with precision .
Simple linear regression model: hypothesis testing
The t-test
- Under normality assumptions, the test statistic for H0:β=0 follows a Student’s t-distribution: t=SE(β^)β^∼tN−2 .
- tN−2 denotes a Student’s t-distribution with N−2 degrees of freedom .
- For a two-sided test (H1:β=0) at significance level α, reject H0 if t is outside the interval [tα/2,t1−α/2] .
- tα/2 and t1−α/2 are the α/2 and 1−α/2 quantiles of the t-distribution .
Interpretation of significance levels
- Vertical bars at ±1.96 in balance check graphs often correspond to the critical values for a 5% significance level t-test .
- If estimated coefficients fall between ±1.96, it suggests the means of control and treatment groups do not differ significantly at the 5% level via the t-test .
problems with the linear regression model: heteroskedasticity
Core idea
- Heteroskedasticity occurs when the variance of the error term is not constant across observations .
- Mathematically, this means the variance is unequal, i.e., σi=σj for some observations i and j .
- It is a violation of one of the key assumptions necessary for OLS estimators to be the Best Linear Unbiased Estimators (BLUE) .
Detection
- A primary detection method involves examining a scatter plot (binscatter) of the residuals (e) against the fitted values (y^) .
- Under homoskedasticity (constant variance), the dispersion of residuals should show no systematic dependence on the fitted values .
- Heteroskedasticity is suggested by patterns like a funnel shape, where residual dispersion systematically changes as y^ changes .
-
Example: Case 1 suggests heteroskedasticity because the dispersion of residuals clearly increases with the fitted values, forming a funnel shape
Solutions
- If the structure of the variance (σi2) is known, Feasible Generalized Least Squares (FGLS) estimation can be applied .
- FGLS uses the estimated variance structure to reweight observations, improving efficiency .
- For instance, σi might be inversely proportional to population size when analyzing per capita outcomes .
- If the variance structure is unknown, use a heteroskedasticity-robust estimator for the variance of the OLS coefficients .
- White’s robust estimator is a common example of such a robust variance estimator .
-
Tip: Using White’s robust estimator ensures that the standard errors used for hypothesis testing are consistent, even if the underlying error variance is not constant
problems with the linear regression model: serial correlation
Core idea
- Serial correlation occurs when error terms across different observations are non-zero correlated .
- This means the off-diagonal elements of the error covariance matrix are not zero, i.e., σij=0 .
Key concepts
- Detection involves plotting residuals (ei) against the observation index (i) .
- No serial correlation implies residuals should be randomly distributed around zero with no dependence on i (e.g., time) .
- Case 2 in residual graphs suggests strong autocorrelation because the sign and magnitude of residuals persist over time .
-
Tip: Persistence in the sign or magnitude of sequentially ordered residuals is a strong visual indicator of serial correlation
Implications and solutions
- If the covariance structure of the errors is known, Feasible Generalized Least Squares (FGLS) should be applied after estimating σij .
- FGLS is often applicable when the degree of autocorrelation is known, such as in time-series regressions .
- If the covariance structure is unknown, employ a serial-correlation-robust estimator for the Ordinary Least Squares (OLS) variance .
- Robust standard errors clustered by time or spatial radius are examples of robust variance estimators .
regression outliers and the outlier map
Core idea
- The outlier map visually distinguishes between different types of influential points in regression analysis .
- Outliers are categorized based on standardized residuals and leverage measures .
Key concepts
- Vertical outliers (y-outliers): Points with large standardized residuals, ei/\SD(ei)∈[−3,3] .
- Horizontal outliers (x-outliers): Points with high leverage, MDi∈(−χK,1−α/22,χK,1−α/22) .
- Good leverage points: Points that are horizontal outliers but not vertical outliers: ei/\SD(ei)∈[−3,3] and MDi∈/(−χK,1−α/22,χK,1−α/22) .
- Bad leverage points: Points that are both horizontal and vertical outliers: ei/\SD(ei)∈/[−3,3] and MDi∈/(−χK,1−α/22,χK,1−α/22) .
- The outlier map uses standardized residuals plotted against the Mahalanobis distance (MDi) .
Implications
- Identifying these categories helps assess the influence of individual observations on the regression fit .
- Vertical outliers violate the assumption of normally distributed errors .
- Leverage points indicate unusual patterns in the predictor variables .
- Building the outlier map involves calculating MDi and standardized residuals (ei/\SD(ei)) .
-
Tip: For K predictors, the squared Mahalanobis distance, MDi2, follows a chi-squared distribution with K degrees of freedom under certain assumptions
-
Example: A point falling outside the central region defined by ±χK,1−α/22 on the horizontal axis indicates high leverage
solutions for dealing with regression outliers
Consequences of not dealing with outliers
- Vertical outliers and bad leverage points severely bias the Ordinary Least Squares (OLS) estimator's signal and significance .
- Good leverage points can cause a downward bias in the estimated standard errors of the OLS estimator .
Strategy when results are robust to outlier inclusion/exclusion
- Solution 1: Include a robustness section confirming results hold despite different outlier definitions or removal criteria .
Strategy when results change based on outlier inclusion/exclusion
- Solution 2: Apply transformations, such as logarithmic or Box–Cox, to regularize regression outliers .
- Solution 3: Remove identified outliers completely from the sample .
- Solution 4: Employ robust estimation methods to reduce the influence of vertical outliers and bad leverage points .
- Examples include Least Trimmed Squares or Quantile Regression .
-
Tip: Robust estimation methods (Solution 4) are specifically designed to mitigate the impact of extreme observations on model parameters
Solutions used in practice (Active Learning)
- Finance research primarily uses Winsorizing, Trimming, and Dropping (WTD) when addressing outliers in OLS studies .
- Business research also relies heavily on WTD methods .
- Winsorizing is the most common approach in Business studies .
- This is followed by robust methods and the removal of extreme values in Business literature .
-
Example: Winsorizing involves capping extreme values at a specified percentile (e
- g
- , the 5th and 95th percentiles) rather than complete removal or transformation
basic hypotheses defining the multiple linear regression model
Core idea
- Five basic hypotheses (H1 through H5) define the Multiple Linear Regression Model 4.
- These hypotheses together guarantee OLS estimators are unbiased, efficient, and valid for inference 4.
The five basic hypotheses
- H1: Linearity of the conditional expectation function (CEF) 4.
- H2: Full rank of the regressor matrix 4.
- H3: Exogeneity of the regressors 4.
- H4: Homoskedasticity and no serial correlation of the errors 4.
- H5: Normality of the error term 4.
Detailed assumptions
H1: Linearity
- The CEF is linear in parameters: E[y∣X=Xβ 5.
- For any observation i: E[yi∣xi=xi′β=β1x1i+⋯+βPxPi 5.
H2: Full column rank
- The regressor matrix X must have full column rank: rank(X)=K 5.
- This condition is equivalent to X′X being invertible 5.
- Ensures the Ordinary Least Squares (OLS) estimator is uniquely defined 5.
H3: Exogeneity
- Requires mean independence between errors and regressors: E[ε∣X=0 5.
- This assumption guarantees the unbiasedness of the OLS estimator 5.
H4: Homoskedasticity and no serial correlation
- The variance of the errors is constant and cross-covariances are zero: Var[ε∣X=σ2IN 6.
- Each error term εi has variance σ2 6.
- εi is uncorrelated with εj for all i=j 6.
H5: Normality
- The error vector follows a multivariate normal distribution: ε∼N(0,σ2IN) 6.
- This assumption allows for exact small-sample t and F inference 6.
-
Tip: The matrix notation for the basic model is y=Xβ+ε 3
-
Example: In matrix form, X is an N×K matrix, where K=P+1 (including the intercept) 3
multiple linear regression: partitioned model
Core idea
- The partitioned regression model structure is defined as y=X1β1+X2β2+ε .
- X1 (N×K1) and X2 (N×K2) represent the blocks of explanatory variables .
- The OLS estimator β^ is partitioned as [β^1β^2] .
Partitioned regression theorem
- The theorem provides the OLS estimators β^1 and β^2 for the partitioned model .
- β^1 is calculated using transformed variables: β^1=(X1∗X1∗)−1X1∗y∗ .
- The transformed variables relate to the annihilator matrix M2=I−P2, where P2=X2(X2⊤X2)−1X2⊤ .
- Specifically, X1∗=M2X1 and y∗=M2y .
- β^2 can be calculated using the initial estimate β^1: β^2=(X2X2)−1X2(y−X1β^1) .
-
Tip: The matrix M2 acts as a projection matrix that removes the effect of X2 from the variables
Implications and estimation steps
- The partitioned regression theorem allows obtaining the OLS estimator β^ in a sequential, three-step process .
- Step 1: Regress y and each column of X1 separately on X2, saving the residuals from these regressions .
- Step 2: Estimate β^1 by regressing the residuals of y on X2 against the residuals of each column of X1 on X2 .
- Step 3: Estimate β^2 by regressing the residuals of (y−X1β^1) on X2 .
-
Example: This method is equivalent to running the full OLS regression but allows isolating the effects of β1 after accounting for X2
multiple linear regression: models with fixed effects
Core idea
- Fixed effects (FEs) models include indicator variables for groups to which observations belong .
- Groups can be defined by time periods (month/year) or spatial units (state/municipality) .
- The FE model structure is y=Xβ+Dα+ε .
- D is the matrix of G group indicator variables, and α is the vector of G group indicator effects .
Key facts
- For an observation i, the model form is yi=β0+β1x1i+⋯+βPxPi+∑g=1Gαg⋅1(i∈g) .
- The presence of D is often costly to invert if the number of groups G is large .
- The partitioned regression theorem allows computing the estimate β^ efficiently .
- Computational efficiency is achieved by demeaning y and X variables by their respective group means .
- Software often uses
absorb()orpartial()options to implement this demeaning process . - The full matrix [X,D] is not full rank because D is collinear with the constant term .
- To achieve full rank, either the constant term or one group indicator must be dropped .
Implications
- FEs decrease the likelihood of omitted variable bias by accounting for unobserved group-specific heterogeneity .
- FEs usually make treatment and control units within a group more comparable .
- Including FEs can decrease standard errors by increasing the variation explained by the model .
- Comparing coefficient estimates with and without FEs is an important method to test robustness .
-
Tip: Stringency tables are a critical tool used to demonstrate the robustness of the main coefficient of interest across models incorporating different sets of fixed effects (e
- g
- , product, year, state)
-
Example: A stringency table compares coefficients (like Num
- of Bidders) while systematically adding Product FEs, Year FEs, and State FEs across columns
- In the example table, the coefficient for Num. of Bidders remains stable around −0.008 to −0.024 across specifications .
- The inclusion of State-Year FEs results in the highest adjusted R2 value of 0.842 in the provided example .
- </document_content>
multiple linear regression: models with interactions
Core idea
- Linear and additive assumptions for the conditional expectation function (CEF) can be overly restrictive .
- Interactions allow relaxing the strict assumption of linear additivity in explanatory variables .
- Interactions help capture heterogeneous effects that are central to the research question .
- Interactions can improve predictive accuracy by accounting for nonlinearities in the CEF .
Key concepts
- The linear regression model with an interaction term (for P=2) is: yi=β0+β1x1i+β2x2i+β3x1ix2i+εi .
- The coefficient β3 measures how the effect of x1i on yi changes with x2i (and vice versa) .
- Researchers use interaction terms to estimate certain causal effects, such as in difference-in-differences designs .
- One functional form choice is the linear interaction x1i⋅x2i .
- It is also common to specify binary interaction terms based on percentiles, like x1i⋅1(x2i≥Pα(x2i)) .
Implications
- If theory suggests a nonlinear CEF, or data indicates correlation between error and predictors, interactions are warranted .
- Including interactions helps test the robustness of primary coefficients by comparing estimates with and without them .
- If using a binary source of heterogeneity (H), heterogeneous effects can be estimated by running separate regressions for subsamples where H=0 and H=1 .
Practical issues
- Hierarchical principle: If an interaction term (x1i⋅x2i) is included, the main effects (x1i and x2i) must also be specified .
- Omission of main effects should occur even if their associated coefficients are not statistically significant .
-
Tip: Recent advances suggest that if controls (X) are included, the source of heterogeneity (H) should be interacted with all variables in the model, not just the treatment (T),
- Omitting the interaction X×H when X is included can bias results when estimating the heterogeneous effect T×H .
basic definitions: in-sample versus out-of-sample prediction
Core idea
- In-sample prediction evaluates a model using the data it was estimated on .
- Out-of-sample prediction assesses the model using new, unseen data .
- In-sample fit tends to overstate the true predictive power of the model .
- Out-of-sample evaluation provides a more realistic measure of generalization accuracy .
In-sample prediction uses
- In-sample forecasting is useful when the sample size is small .
- It remains useful when data splitting is expensive or difficult .
- It serves as a necessary benchmark against which out-of-sample performance is compared .
- Computationally, in-sample prediction is simpler to calculate .
- Coefficients derived from in-sample fits retain interpretable signal and magnitudes .
Applications of in-sample prediction
- Major applications include macroeconomic forecasting, such as GDP growth rates .
- It is used in forecasting inflation rates in macroeconomic contexts .
- An application is the artificial regressor, using fitted values to proxy unobservable variables .
- In-sample fitted values can be used to replace missing data observations .
- Examples include Mincerian regressions and hedonic price regressions .
-
Tip: Always prefer out-of-sample evaluation for assessing true predictive accuracy, but in-sample measures are vital for model diagnostics
Point prediction in linear regression
- Linear regression point prediction often involves calculating the expected outcome y^ .
- The predicted value y^i for observation i is based on the estimated parameters β^ .
- For a model y=Xβ+ϵ, the fitted value is y^=Xβ^ .
- The formula for the prediction error variance is key for inference .
-
Example: If estimating wage (y) based on years of education (X), in-sample prediction uses observed education levels to estimate wages for the same group
point prediction in linear regression
Core idea
- Point prediction involves estimating the unobservable response y0 using observed predictors x0=(1,x10,…,xP0)′ and sample data X .
- The best point prediction is the conditional expectation y^0=E^[y0∣x0=x0′β^ .
- The OLS estimator is β^=(X′X)−1X′y .
- Prediction expands as y^0=β^0+β^1x10+⋯+β^PxP0 .
Prediction error decomposition
- The prediction error decomposes into estimation uncertainty and irreducible error: y0−y^0=x0′(β−β^)+ε0 .
- Estimation uncertainty arises from the variation in β^ due to finite sample size .
- Irreducible error is the inherent randomness in the new observation ε0 .
Variance of prediction error
- The variance of the prediction error conditional on X and x0 is Var[y0−y^0∣X,x0=σ2(1+x0′(X′X)−1x0) .
- This variance splits into estimation variance σ2x0′(X′X)−1x0 and irreducible variance σ2 .
-
Tip: The variance always includes the irreducible variance σ2, which ensures the total variance is always greater than the variance of y^0 alone
Distribution under known variance
- Assuming normality, β^∣X∼N(β,σ2(X′X)−1) .
- If ε0∣X,x0∼N(0,σ2), then x0′β^∣X,x0∼N(x0′β,σ2x0′(X′X)−1x0) .
- The prediction error has an exact normal distribution when σ2 is known: y0−y^0∣X,x0∼N(0,σ2(1+x0′(X′X)−1x0)) .
Distribution under unknown variance
- When σ2 is unknown, the standardized error follows a t-distribution: σ^1+x0′(X′X)−1x0y0−y^0∼tN−K .
- The estimated error variance is σ^2=N−Ke′e, where e is the OLS residual vector .
Prediction confidence interval
- The (1−α) confidence interval for y0 is constructed using the t-distribution .
- The interval bounds are y^0±tN−K,1−α/2⋅σ^1+x0′(X′X)−1x0 .
-
Example: If the significance level is five percent ($\alpha = 0
- 05)anddegreesoffreedomareN-K,thecriticalvalueusedist_{N-K, 0
- 975}$
selecting the best regression model using subset selection methods
Core idea
- With P predictors, there are 2P possible linear regression model specifications .
- Subset selection methods aim to choose the best model among these possibilities .
- Model selection relies on evaluating models using criteria like the Residual Sum of Squares (RSS) and information criteria .
Best subset selection
- Step 1: Start with M0, the null model containing no predictors .
- Step 2: For k=1,2,…,P, fit all models containing exactly k predictors .
- Step 3: Select the best model of size k based on the smallest Residual Sum of Squares (RSS) .
- The number of models of size k is (kP)=k!(P−k)!P! .
- Step 4: Select the final single best model from the sequence M0,M1,…,MP using an information criterion .
Forward stepwise selection
- Step 1: Begin with M0, the null model with no predictors .
- Step 2: For k=0,1,…,P−1, consider all P−k models that add one predictor to Mk .
- Step 3: Choose the best new model, Mk+1, based on the smallest RSS among the options .
- Step 4: Select the final model from the sequence M0,M1,…,MP using an information criterion .
Backward stepwise selection
- Step 1: Start with MP, the full model containing all P predictors .
- Step 2: For k=P,P−1,…,1, consider all k models excluding one predictor from Mk .
- Step 3: Select the best model, Mk−1, based on the smallest Residual Sum of Squares (RSS) among the k models .
- Step 4: Select the final model from the sequence M0,M1,…,MP using an information criterion .
-
Tip: All three subset selection algorithms first identify a sequence of best models based on minimizing RSS before using an information criterion to select the final model
model selection using information criteria
Core idea
- Information criteria balance model fit (lower Residual Sum of Squares, RSS) against model complexity (number of predictors) .
- The best model is selected by choosing the one that minimizes the information criterion value .
Key facts
- Model complexity is often approximated by the number of estimated parameters, K=P+1 .
- Adjusted R2 increases only when a new predictor improves fit beyond what is expected by chance .
- Akaike Information Criterion (AIC) penalizes complexity using a term of 2K .
- Bayesian Information Criterion (BIC) penalizes complexity using a term of Klog(N) .
Key concepts
- The formula for Adjusted R2 is Radj2=1−N−KRSSN−1TSS .
- The AIC formula is: AIC=Nlog(NRSS)+2K .
- The BIC formula is: BIC=Nlog(NRSS)+Klog(N) .
- AIC and BIC are increasing functions of the RSS, so the minimum value indicates the best fit .
Implications
- BIC tends to select simpler models (fewer predictors) than AIC for typical sample sizes .
- BIC applies a heavier penalty when N>e2≈7.4, because log(N)>2 when N>8 .
- When N<e2≈7.4, AIC imposes a greater penalty on complexity than BIC (AIC>BIC if 2K>Klog(N)) .
-
Tip: Since BIC imposes a larger penalty factor (log(N) vs 2), it favors parsimony more strongly than AIC for large datasets
motivation and overview of classification tasks
Motivation for classification
- The primary goal is to predict a qualitative response variable .
- Classification contrasts with regression, which predicts a quantitative response .
Examples of classification tasks
- Predicting if a client will default on a loan .
- Predicting whether a financial transaction is fraudulent .
- Predicting the mode of transportation used by a passenger .
Core concepts
- Predicting a qualitative response is formally termed a classification task .
- The statistical techniques used to perform classification are known as classifiers .
Classification tasks: Step-by-step process
- Step 1 involves specifying a model for the categorical response variable .
- Step 2 requires predicting the likelihood associated with each possible category .
- Step 3 is associating the calculated predicted likelihood with a specific category outcome .
- Step 4 entails evaluating the overall performance of the constructed model .
-
Tip: Classification tasks focus on assigning observations to predefined groups, unlike regression which estimates continuous numerical values
specification of the linear probability model
Core idea
- The Linear Probability Model (LPM) posits the conditional probability of the response is linear in predictors: E[yi∣xi=Pr[yi=1∣xi=xi′β .
- The response variable yi must be binary, meaning yi∈{0,1} .
- The LPM is estimated easily using Ordinary Least Squares (OLS) .
Key concepts
- The coefficient βj directly measures the change in Pr[yi=1∣xi] when xij increases by one unit, holding others constant .
- Predicted probabilities from the LPM can fall outside the unit interval 1 .
- The model is heteroskedastic because the outcome follows a multinomial distribution .
- The interpretation of the outcome becomes complicated when there are more than two categories .
Implications
- LPM coefficients offer direct interpretability in terms of probability changes .
- It is generally not advisable to use the LPM for classification tasks due to several shortcomings .
- The LPM does not constrain predicted probabilities to be between zero and one .
- It is unclear why certain categories should inherently possess a higher value than others in the LPM framework .
-
Tip: While the LPM is simple to estimate and interpret locally, its global constraints (probability bounds and heteroskedasticity) make it inferior to models like Logit for binary outcomes
Specification of the logit model
Core idea
- The Logit model assumes the conditional probability follows a logistic function: E[yi∣xi=Pr[yi=1∣xi=1+exi′βexi′β .
- The log odds ratio derived from the Logit model is a linear function of the predictors: log(1−Pr[yi=1∣xi]Pr[yi=1∣xi])=xi′β .
- The odds ratio is calculated as exi′β .
Key concepts
- Each βj in the Logit model measures the change in the log-odds of yi=1 when xij increases by one unit .
- Predicted values generated by the Logit model are guaranteed to lie within the unit interval 1 .
- The Logit function provides a flexible form that effectively captures non-linear effects of predictors on the probability .
Implications
- A major disadvantage is that Logit coefficients are not directly interpretable in terms of probability units .
- The model imposes a specific functional form (the logistic curve) linking predictors to the probability .
-
Example: If $\beta_1 = 0
- 5inaLogitmodel,aone−unitincreaseinx_1increasesthelog−oddsoftheeventoccurringby0
- 5$
associating the predicted likelihood to a category
Core idea
- Converting continuous predicted probabilities into categorical predictions requires a cutoff value, δ .
- This cutoff maps the predicted likelihoods, like bPr[yi=1∣xi], to specific response categories .
Key concepts
- For a binary response, the prediction y^i is 1 if the predicted probability exceeds δ .
- The decision rule for binary response prediction is formally defined as: y^i={1,0,bPr[yi=1∣xi>δbPr[yi=1∣xi≤δ .
- When using a cutoff δ=0.5, the resulting accuracy is maximized .
- Increasing the cutoff δ above 0.5 decreases the rate of false positives (y^i=1 but yi=0) .
- Increasing the cutoff δ increases the rate of false negatives (y^i=0 but yi=1) .
Implications
- The practical selection of the cutoff δ must rely on domain knowledge .
- The choice reflects the payoff associated with each potential response outcome .
- The payoff of the subsequent actions triggered by the prediction also influences δ selection .
- Domain considerations for choosing δ include:
- Criminal conviction decisions .
- Bailing out decisions .
- Allocating limited investigative resources .
- Sending messages to prevent minor offenses .
-
Tip: Setting δ is a trade-off; choose a lower δ if false positives are more costly than false negatives, and vice versa
-
Example: If failing to identify a threat (false negative) is extremely costly (e
- g
- , in security screening), one might select a smaller δ to ensure more instances are flagged as positive
evaluating performance metrics based on counts
Accuracy
- Accuracy is the proportion of all instances correctly predicted (both positive and negative) .
- Formula: Accuracy=TP+TN+FP+FNTP+TN .
- High accuracy indicates correct classification for most observations overall .
- It does not distinguish between false positives (FP) and false negatives (FN) .
Sensitivity (Recall)
- Sensitivity, or recall, measures the true positive rate .
- It is the proportion of actual positive instances predicted as positive by the model .
- Formula: Sensitivity=TP+FNTP .
- High sensitivity means the model rarely misses positive cases .
- Performance on negative instances is ignored by this metric .
Specificity
- Specificity measures the true negative rate .
- It is the proportion of actual negative instances predicted as negative by the model .
- Formula: Specificity=TN+FPTN .
- High specificity means the model identifies most negative cases with few false alarms .
- Performance on positive instances is ignored by this metric .
Precision
- Precision measures the positive predictive value .
- It is the proportion of instances predicted positive that are actually positive .
- Formula: Precision=TP+FPTP .
- High precision means the model generates few false alarms among its positive predictions .
- Performance on negative instances is ignored by this metric .
F1-Statistic
- The F1-Statistic combines precision and sensitivity into a single measure .
- It is the harmonic mean between precision and sensitivity .
- Formula: F1=2×Precision+SensitivityPrecision×Sensitivity .
- A high F1 indicates a good balance between false positives and false negatives .
- It is particularly useful when the dataset exhibits imbalance .
-
Tip: When evaluating models, relying solely on Accuracy can be misleading, especially with imbalanced data; metrics like Sensitivity, Precision, and F1 are crucial for specific error analysis
evaluating performance using the roc curve and auc-roc
Core idea
- The ROC curve visualizes model performance across all possible classification thresholds .
- The AUC-ROC quantifies the overall model performance summarizing across all thresholds .
- The diagonal line on the ROC plot signifies performance equivalent to random guessing .
Receiver operating characteristic (ROC) curve
- The y-axis of the ROC curve plots Sensitivity (True Positive Rate) .
- The x-axis of the ROC curve plots 1 - Specificity (False Positive Rate) .
- Performance improves as the curve moves farther away from the diagonal line .
- The top-left corner of the plot represents the ideal performance state (maximum sensitivity and specificity) .
-
Tip: A model closer to the top-left corner indicates superior discriminatory power across thresholds
Area under the receiver operating characteristic curve (AUC-ROC)
- AUC-ROC measures the probability that a randomly selected positive case is ranked higher than a randomly selected negative case .
- The AUC value is constrained within the range of 0.5 to 1 .
- The worst-case scenario, coinciding with the diagonal line, results in AUC=0.5 .
- The best-case scenario, tracing the top and left borders, results in AUC=1 .
-
Example: If $\text{AUC}=0
- 95$, the model is excellent, meaning a random positive instance is ranked higher 95 percent of the time
AUC-ROC performance benchmarks
- AUC=0.5 indicates performance is equivalent to random guessing .
- AUC between 0.7 and 0.8 is generally considered acceptable performance .
- AUC between 0.8 and 0.9 is classified as good performance .
- AUC greater than 0.9 signifies excellent model performance .
basic definitions and terminology in statistical learning
Core idea
- This section introduces foundational terminology used in statistical learning, contrasting it with econometrics terminology 2.
- Statistical learning focuses on approximating complex functions relating inputs to outputs, emphasizing prediction 3.
Terminology comparison
- In prediction contexts, y is the response and X represents the predictors or features 2.
- In econometrics, y is the outcome and X represents the covariates or regressors 2.
- Machine learning is defined as improving performance on tasks through experience 3.
Types of learning
- Supervised learning requires a dataset containing both predictors (X) and a response variable (y) 4.
- The objective of supervised learning is learning a mapping from predictors to the response 4.
- Unsupervised learning uses datasets with only predictors, aiming to find hidden structure or patterns 4.
- Unsupervised tasks include clustering, dimension reduction, and anomaly detection 4.
Prediction tasks
- A regression task occurs when the response y is a numerical and continuous variable 5.
- The goal in regression is to estimate the conditional expectation E[y∣x] 5.
- A classification task occurs when the response y is a categorical or binary variable 5.
- Classification aims to assign a category based on estimated class probabilities, Pr[y=k∣x] 5.
Model evaluation contexts
- In-sample prediction evaluates a model using the exact data used for its estimation 6.
- In-sample assessment often overstates the true predictive power of a model 6.
- Out-of-sample prediction evaluates the model on data unseen during the estimation process 6.
- Out-of-sample assessment offers a more realistic measure of how well the model generalizes 6.
-
Tip: Statistical learning views machine learning as approximating complex functions for prediction, contrasting with economics' view of it as an automated research assistant for data structure discovery 3
applications of out-of-sample prediction
Core idea
- Out-of-sample prediction evaluates a model using new data unseen during the estimation phase .
- This method provides a more realistic assessment of the model's true predictive accuracy and generalization capability compared to in-sample fitting .
- In-sample prediction only measures how well a model fits the known data, often overstating predictive power .
Academic applications
- Out-of-sample prediction is crucial for unlocking the potential of new, fine-grained data sources .
- A key academic application involves prediction used for robust causal inference methods .
- It enables the estimation of propensity scores using more flexible functional forms than otherwise possible .
- It is used for predicting treatment heterogeneity by estimating individualized treatment effects (ITEs) .
- ITE estimation allows for the precise targeting of specific interventions to those who benefit most .
Applications related to machine learning
- Machine learning applications leverage out-of-sample testing to validate predictive models on data they have not encountered .
- Machine learning's utility in causal inference heavily relies on out-of-sample prediction accuracy .
- Predictive modeling within causal inference helps estimate heterogeneous treatment effects accurately .
-
Tip: Always ensure evaluation data is independent of training data to avoid confirmation bias inherent in in-sample evaluation
-
Example: If a model predicts poverty levels at a geographic resolution finer than the training data, this demonstrates out-of-sample generalization
applications of machine learning
Prediction for causal inference
- Machine learning applications focus on prediction for causal inference .
Targeting interventions
- ML applications are used for targeting specific interventions .
Applications of out-of-sample prediction
- Out-of-sample prediction is a key application area .
- Business applications include:
- Predicting loan default .
- Predicting fraud incidents .
- Predicting on-lien purchases .
- Health applications include:
- Predicting diagnosis based on examination data .
- Public policy applications include:
- Predicting instances of tax evasion .
- Predicting corruption and collusion activities .
-
Tip: Causal inference often requires careful model design to distinguish correlation from true cause-and-effect in predictions
-
Example: In business, predicting loan default allows institutions to target stricter scrutiny (intervention) on high-risk applicants
statistical learning: measuring predictive accuracy and overfitting
Core idea
- Statistical learning estimates an unknown function f(x) relating response y to predictors x=(x1,…,xP): y=f(x)+ε .
- The goal is to minimize the expected squared prediction error, E[(y−f^(x))2] .
- This error decomposes into reducible error (f(x)−f^(x)2) and irreducible error (Var(ε)) .
- Statistical learning methods aim to reduce the reducible error .
Measuring predictive accuracy
- For regression tasks, Mean Squared Error (MSE) is the standard accuracy measure .
- In-sample prediction uses train MSE, calculated on the data used for model training .
- Out-of-sample prediction requires the test MSE, calculated on unseen data .
- Since true test data is often unavailable, test MSE is estimated using resampling methods .
Overfitting
- Overfitting occurs when a model has low train MSE but high test MSE .
- An overfit model captures random noise in training data that does not generalize .
- Less flexible models may yield lower test MSE when overfitting is present .
Model assessment and selection using resampling
- Resampling methods estimate a statistic's variability by repeatedly sampling the data .
- They are useful for: Model assessment (estimating test MSE) and Model selection (choosing flexibility) .
- Cross-validation is a primary resampling method, including validation set, LOOCV, and K-fold CV .
-
Tip: Model flexibility impacts the bias-variance tradeoff; overly flexible models risk overfitting, increasing test MSE
Regularization and interpretability
- Regularization methods improve prediction accuracy and interpretability, especially when P≈N or P>N .
- LASSO performs both shrinkage and variable selection by producing sparse models .
- LASSO minimizes penalized least squares objective: β^L,λ=argminβ{∑i=1N(yi−β0−xi′β)2+λ∑j=1P∣βj∣} .
- λ≥0 controls shrinkage strength; λ=0 equals OLS estimation .
- LASSO sets some coefficients exactly to zero, yielding simpler models than Ridge regression .
- LASSO is preferred when the true model is sparse (few predictors affect the response) .
- LASSO estimates are not scale invariant, and variable selection can be erratic with highly correlated predictors .
evaluating performance: the r2 statistic and active learning context
R2 statistic definition and components
- The R2 statistic is calculated as R2=1−y′ye′e .
- e′e represents the residual sum of squares (RSS) .
- y′y represents the total sum of squares (TSS) .
- The vector of residuals, e, is calculated as e=y−y^ .
Desirable features of R2
- R2 is bounded, meaning its values fall within the range of 0 to 1: R2∈ 1 .
- It is interpretable, measuring the proportion of variance in y explained by the model .
- A higher R2 value indicates greater explanatory power of the model .
Limitations of the R2 statistic
- R2 will either increase or stay constant as more predictors (P) are added to the model .
- There is no single, universally agreed-upon threshold defining a "high" R2 value .
- When the outcome variable is noisy, even an R2 value less than 0.2 might signify strong explanatory ability .
R2 in the active learning context
- Relying solely on R2 as an information criterion for model selection can lead to poor outcomes .
- A research assistant unintentionally using R2 maximized the number of predictors, P .
- Since R2 increases with P, this reliance selects the model with the maximum number of predictors .
- This behavior results in selecting models with an excessive number of predictors, leading to the problem known as overfitting .
-
Tip: Because R2 does not penalize complexity, it is unsuitable alone for model comparison, especially in active learning where model size might be iteratively maximized
univariate outliers motivation and detection
Motivation for studying univariate outliers
- Economists must consider univariate outliers because key economic measures are sensitive to them .
- Examples of sensitive measures include inequality and segregation metrics .
Univariate outliers detection methods overview
- Detection methods include visual inspection, descriptive statistics, and rules of thumb .
Univariate outliers: Visual inspection
- Box and Whisker Plot spots potential outliers using a fence interval .
- The plot involves the median, Med(x) .
- The Interquartile Range is defined as IQR(x)=Q3(x)−Q1(x) .
- The fence interval is [Q1(x)−1.5×IQR(x),Q3(x)+1.5×IQR(x)] .
- Points falling outside this fence interval are potential outliers .
- Kernel Density Plots nonparametrically show the density of x .
- Kernel plots highlight non-normal shapes such as skewness, fat tails, or multimodality .
-
Tip: Visual inspection methods are useful for initial assessment but do not definitively identify which specific observations are outliers
Univariate outliers: Descriptive statistics
- High Coefficient of Variation (CV(x)>1) indicates extreme data dispersion .
- CV(x) is calculated as xˉSD(x) .
- High Skewness suggests asymmetric distributions with long tails .
- Skewness threshold often considered is ∣Skew(x)∣≥1 .
- The formula for skewness is Skew(x)=N1∑i=1N(SD(x)xi−xˉ)3 .
- High Excess Kurtosis (Kurt(x)−3>1) suggests heavy tails or extreme values .
- The formula for kurtosis involves the fourth standardized moment .
Univariate outliers: Rule of thumb (Normality assumption)
- If xi∼N(μ,σ2) i.i.d., values where σxi−μ>3 lie in the region covered by only 0.1% of observations (one-sided) .
Univariate outliers: Feasible rule of thumb (Estimation)
- In practice, μ and σ must be estimated using sample statistics .
- The rule of thumb is that observation i is an outlier if its z-score (zi) is greater than 3 .
- The sample z-score is calculated as zi:=sxxi−xˉ>3 .
- The sample mean is xˉ=N1∑i=1Nxi .
- The sample standard deviation (sx) uses the N−1 divisor: sx=N−11∑i=1N(xi−xˉ)2 .
Common mistakes to avoid
- Review all topics thoroughly before exams
- Pay attention to formulas and key definitions
- Practice with examples provided in each section
- Don't memorize without understanding the underlying concepts