SEN608 DATA ANALYTICS AND STATISTICS

Week 1: Statistics, Data Science, and the Python Environment

Assoc. Prof. Dr. Onur Polat
Hacettepe University • Graduate School of Informatics
M.Sc. (Thesis) in Systems Engineering • Fall 2026, Lecture 1 / 14

COURSE OVERVIEW

Course Goals and Scope

This course equips systems engineering graduate students with the statistical and computational tools needed to analyze data rigorously, make defensible inferences, and build reproducible analytical workflows.

What You Will Learn

  • Exploratory data analysis (EDA) and visualization
  • Sampling distributions and the bootstrap
  • Hypothesis testing (permutation, chi-square, ANOVA)
  • Simple and multiple linear regression
  • Reproducible analysis in Python/Colab

Why It Matters for Systems Engineers

  • Every empirical claim requires quantified uncertainty
  • Model validation depends on statistical diagnostics
  • Data-driven decision making is the industry standard
  • AI tools amplify — but do not replace — statistical literacy

COURSE INFORMATION

Academic Framework

ProgramM.Sc. (Thesis) — Systems Engineering, Graduate School of Informatics
Credits / ECTS3 Local Credits (3-0-3) • ECTS: 6
TypeCompulsory • In Person
LanguageEnglish
PrerequisitesFamiliarity with Python (the Python Fundamentals notebook on the course page provides a self-paced introduction); basic linear algebra
Learning Outcomes: Upon completion, you will be able to (1) systematically explore datasets, (2) select and apply appropriate statistical tests, (3) conduct analyses in Python/Colab, (4) report results reproducibly, and (5) critically evaluate statistical claims.

SYLLABUS

Weekly Topic Plan

WkTopicApplied Focus
1Statistics, Data Science, and Python SetupColab & Pandas Fundamentals
2Data Exploration & EDADistributions, Boxplots, Outliers
3Inference Basics: Permutation & p-valuesRandomization Tests in Python
4Random Numbers & SimulationMonte Carlo Simulation
5Probability & the Normal DistributionTheoretical Distributions & QQ-Plots
6Categorical Data & Chi-Square TestsContingency Tables & Goodness-of-Fit
7Midterm Review & ExaminationMidterm Assessment
8Sampling & Bootstrap Confidence IntervalsResampling & Empirical CIs
9ANOVA BasicsOne-way & Two-way ANOVA
10Correlation & AssociationPearson, Spearman, Collinearity
11Simple Linear RegressionOLS Diagnostics with Statsmodels
12Multiple RegressionMultivariate Model Diagnostics
13–14Research PresentationsStudent Term Presentations

ASSESSMENT

Grading Scheme

ComponentWeightDescription
Weekly Assignments26%Colab notebook submissions each week
Midterm Exam25%Conceptual + applied examination (Week 7)
Research Presentations15%End-of-term research presentation
Final Exam34%Comprehensive final examination
Academic Integrity: All work is individual unless explicitly stated otherwise. Copying code without understanding it is not acceptable. You may use AI tools (ChatGPT, Claude) as learning aids, but the analysis and interpretation must be your own. Submissions will be checked for similarity.

REFERENCES

Core and Supplementary Resources

Core Textbook

Bruce, P., Bruce, A. & Gedeck, P. (2026). AI-Assisted Statistics for Data Scientists: 50+ Essential Concepts Using R and Python, 3rd Edition. O'Reilly Media.

Code repository: github.com/gedeck/ai-assisted-statistics-for-data-scientists

Supplementary

  • McKinney, W. (2022). Python for Data Analysis, 3rd Ed. O'Reilly.
  • VanderPlas, J. (2023). Python Data Science Handbook, 2nd Ed. O'Reilly.

Online Resources

  • Course Colab notebooks (weekly)
  • Python Fundamentals notebook (self-paced)
  • Moodle quizzes and assignments

SOFTWARE ECOSYSTEM

Tools and Libraries

Google Colab
Cloud-based Jupyter environment — no local installation required
NumPy
Numerical arrays and vectorized mathematical operations
pandas
DataFrames, time series, data wrangling and aggregation
matplotlib
Foundational plotting library for all chart types
seaborn
Statistical visualizations built on matplotlib
scipy / statsmodels
Hypothesis tests, regression, and statistical modeling
scikit-learn
Preprocessing, model evaluation, and cross-validation
Preparation: If your Python experience is limited, complete the Python Fundamentals Colab notebook from the course page before Week 2. It covers variables, lists, loops, functions, NumPy, pandas, and matplotlib with systems engineering examples.

PART I

The Role of Statistics in Data Science — Methodological Foundations

Slides 9 – 24

DATA SCIENCE FRAMEWORK

What is Data Science?

Data science sits at the intersection of statistics, computer science, and domain expertise. It transforms raw data into actionable knowledge through systematic analysis.

John Tukey's Legacy (1962)

In his seminal paper "The Future of Data Analysis", Tukey proposed a new discipline where statistical inference is just one component of a broader data analysis practice. He coined the terms "bit" and "software," and his 1977 book Exploratory Data Analysis established the field we build on today.

Key Insight: Classical statistics focused almost exclusively on inference from small samples. Modern data science adds exploration, computation, and prediction — but the statistical foundations remain essential.

DATA SCIENCE FRAMEWORK

Statistics vs. Data Science vs. Machine Learning

AspectStatisticsData ScienceMachine Learning
Primary GoalInference about populations from samplesExtract actionable insights from dataOptimize predictive accuracy
EmphasisUncertainty quantification, assumptionsEnd-to-end pipeline: collect → analyze → communicateAlgorithms, scalability, generalization
Typical OutputConfidence intervals, p-values, effect sizesDashboards, reports, data productsTrained models, predictions
Data ScaleSmall to moderate samplesAny scale — small surveys to petabytesTypically large datasets
InterpretabilityHigh — parametric models with clear meaningVaries by applicationOften low (black box models)
This course's position: We focus on the statistical foundations that underpin both data science and ML. Without these, you can run algorithms but cannot evaluate whether the results are meaningful.

DATA SCIENCE FRAMEWORK

The Data Analytics Lifecycle

#StageDescriptionKey Question
1Problem FormulationTranslate the business/research question into a statistical questionWhat are we trying to learn?
2Data CollectionIdentify sources, sampling strategy, and measurement protocolsIs the data representative?
3Data CleaningHandle missing values, outliers, type errors, and inconsistenciesCan we trust this data?
4Exploratory AnalysisSummarize distributions, detect patterns, generate hypothesesWhat does the data look like?
5Modeling & InferenceApply statistical tests, fit models, quantify uncertaintyWhat can we conclude?
6CommunicationReport findings reproducibly with appropriate visualizationsCan others verify this?
Non-linear process: EDA often sends you back to data cleaning; modeling may reveal the need for additional data. Expect iteration, not a one-pass pipeline.

STATISTICAL FOUNDATIONS

Problem Taxonomy

Problem TypeQuestionExampleMethod
DescriptiveWhat happened?Average response time last monthSummary statistics, EDA
InferentialCan we generalize?Is the mean response time different from the SLA target?Hypothesis tests, CIs
PredictiveWhat will happen?Forecast next quarter's server loadRegression, ML models
CausalWhy did it happen?Did the new caching policy reduce latency?Experiments, A/B tests
Common mistake: Treating a causal question as if it were merely predictive. Prediction does not require understanding the mechanism; causal inference does. This distinction matters when making policy recommendations.

STATISTICAL FOUNDATIONS

Variable Types and Measurement Scales

Numeric (Quantitative)

  • Continuous: temperature, voltage, duration — can take any value in an interval
  • Discrete: failure count, error count — integer values only

Categorical (Qualitative)

  • Binary: yes/no, pass/fail — two mutually exclusive categories
  • Ordinal: low < medium < high — categories with a meaningful order
  • Nominal: city, sensor ID, department — categories without order
Why does this matter? The variable type determines which summary statistics are valid (mean is meaningless for nominal data), which visualization to use (histogram vs. bar chart), and which statistical test to apply (t-test vs. chi-square). Getting this wrong invalidates the entire analysis.

STATISTICAL FOUNDATIONS

Tabular (Rectangular) Data

The standard format for statistical analysis: rows = observations, columns = variables/features.

sensor_idtimestamptemperaturepressurestatus
T-2042024-03-15 08:001018.33.21normal
T-2042024-03-15 08:151025.13.35normal
T-2052024-03-15 08:001032.73.48warning
Key Terms: Each row is a record (observation, instance). Each column is a feature (variable, predictor). The outcome (target, response) is the variable we want to predict or explain.
DataFrame: The programmatic representation in R and Python. A DataFrame preserves column types, supports labeled indexing, and enables vectorized operations — it is your primary data structure throughout this course.

DATA MANAGEMENT

Data Dictionaries and Data Catalogs

Data Dictionary

A structured document that records each variable's name, type, description, and valid range.

  • Why needed? Raw data alone is meaningless — a SqFtTotLiving column cannot be interpreted without context.
  • Must include: Variable name, type (continuous/categorical), unit, source, missing data encoding.

Creating Data Dictionaries with AI

3rd Edition feature: LLMs (ChatGPT, Claude) can analyze a DataFrame's structure and generate draft data dictionaries automatically.

  • Extract variable descriptions from column names
  • Auto-detect data types and valid ranges
  • Caution: AI output must always be validated — it cannot replace domain expertise.
Data Catalog: A structured inventory of an organization's data assets — which data is where, in what format, used by whom. Unlike a dictionary (which describes one dataset), a catalog spans the entire organization.

STATISTICAL FOUNDATIONS

Population and Sample

Population (N)

The complete set of all units of interest. We describe it with parameters (e.g., population mean μ, population std σ).

Example: All HTTP requests to a server in a year.

Sample (n)

A subset selected from the population. We compute statistics (e.g., sample mean x̄, sample std s) to estimate parameters.

Example: 10,000 randomly selected requests for analysis.

The fundamental challenge: We almost never observe the full population. Statistical inference is the art of drawing valid conclusions about the population from the sample — and quantifying the uncertainty in those conclusions.

SAMPLING AND BIAS

Random Sampling

Random sampling means every individual in the population has an equal (or known) probability of being selected. This ensures sample statistics are unbiased estimators of population parameters.

Common Sampling Designs

DesignHow It WorksWhen to Use
Simple RandomEvery unit has equal probabilityHomogeneous populations
StratifiedDivide into strata, sample within eachKnown subgroup structure
ClusterRandomly select clusters, sample all withinGeographically dispersed populations
SystematicEvery k-th unit from an ordered listWhen random access is impractical

SAMPLING AND BIAS

Types of Selection Bias

Bias TypeDescription
Survivorship BiasOnly surviving/successful systems are studied while failed ones are ignored — e.g., analyzing only companies that are still in business to understand "success factors."
Convenience BiasCollecting feedback only from active users in user research, excluding the experience of passive and churned users.
Non-Response BiasUsers who do not respond to surveys are generally not neutral — satisfied or disengaged extreme groups are systematically underrepresented (the MCAR assumption is rarely valid).
Algorithmic BiasDemographic imbalances in training data propagating to model predictions — systematic biases observed in credit scoring and hiring systems.
Key takeaway: Bias is not random error — it is systematic. Increasing sample size does not fix bias; it only produces a more precise wrong answer.

REPRODUCIBILITY

Reproducibility Principles

Reproducibility means that given the same data and code, anyone should be able to arrive at the same results.

Practices

  • Code versioning: Git/GitHub for tracking changes
  • Random seed fixing: np.random.seed(42)
  • Environment documentation: requirements.txt or conda env export
  • Data provenance: Record data source, download date, transformations

Why Jupyter/Colab?

  • Code, output, and narrative in one document
  • Cell execution order = analysis pipeline
  • Shareable via link — anyone can re-run
  • Natural support for literate programming
Reproducibility ≠ Replicability. Reproducibility uses the same data/code; replicability collects new data and checks whether findings hold. Both matter, but this course focuses on reproducibility as the minimum standard.

DATA ETHICS

Ethics and Privacy in Data Analytics

Research Ethics

  • Informed Consent: Data subjects must know how their data will be used and provide explicit consent.
  • Anonymization: Data masking and generalization techniques that prevent individual identification.
  • Honest Reporting: Findings that contradict the hypothesis must not be suppressed; negative results carry scientific value.

Legal Framework

  • KVKK (Law 6698): Türkiye's data protection law — explicit consent, data minimization, retention limits.
  • GDPR: EU regulation; applicable in international collaborations.
  • Algorithmic Fairness: Risk of training-data biases propagating to model outputs; fairness metrics and auditing.
Core Principle: "Data is accessible" does not mean "data is usable." The ethical suitability of the data source must be questioned before every analysis.

STATISTICAL THINKING

Three Principles of Statistical Thinking

1. Process Thinking

Every outcome is the output of a process. You cannot improve the outcome without understanding the process that generated it. In systems engineering: understand the data-generating mechanism before modeling it.

2. Variability Awareness

There is natural variation in every measurement. Distinguishing systematic components (signal) from random components (noise) is the foundation of all statistical analysis.

3. Data-Driven Decision Making

Evidence-based inference instead of intuition. Decisions should be supported by quantified uncertainty — confidence intervals, not point estimates alone.

APPLICATIONS

Statistical Problems Across Engineering and Informatics

DomainStatistical Problems
Information SystemsUser behavior segmentation, conversion rate A/B tests, churn prediction, ERP data quality measurement.
Software EngineeringDefect density prediction, test coverage adequacy, process metric distributions (code churn, cyclomatic complexity).
Health InformaticsClassification accuracy in clinical decision support, patient flow queueing models, biomedical signal anomaly detection.
CybersecurityNetwork traffic anomaly detection, attack classification models, statistical pattern analysis in log data.
AI & Data ScienceModel performance comparisons (McNemar test), hyperparameter optimization, cross-validation reliability.
Common Ground: Regardless of your subdiscipline, defending an empirical claim requires measuring sampling uncertainty, applying hypothesis tests correctly, and reporting results reproducibly.

CRITICAL ERRORS

Six Common Errors in Data Analytics

#ErrorWhy It's Dangerous
1Ignoring sample sizeSmall samples produce unstable estimates; large samples detect trivially small effects
2Interpreting correlation as causationTwo variables can co-move due to a confound, not a causal link
3Failing to apply multiple comparison correctionsTesting 20 hypotheses at α=0.05 guarantees ≈1 false positive
4Reading p-value as effect sizep=0.001 does not mean the effect is large — it means it's unlikely under H₀
5Applying models without checking assumptionsOLS regression on heteroscedastic data produces invalid standard errors
6Deleting outliers without investigationOutliers may be the most informative data points — or errors. Investigate first.

TOOL COMPARISON

Python vs. Alternative Analysis Environments

CriterionPythonRExcelSPSS / Stata
AutomationFully programmable; end-to-end pipelineProgrammable; statistics-focusedLimited (VBA)Menu-based; limited scripting
ScalabilityMillions of rows; distributed systemsMedium scale; memory-limited~1M row limitMedium scale
ML Integrationscikit-learn, PyTorch, TensorFlowcaret, tidymodelsNoneLimited
ReproducibilityFull with Jupyter/Colab notebooksHigh with R MarkdownLowMedium (do-file/syntax)
CostOpen sourceOpen sourceLicensedLicensed
Pragmatic Note: This course uses Python; however, statistical concepts are tool-agnostic. Students familiar with R or Stata can directly transfer the conceptual foundation to their own tools.

PART II

Computational Environment — Colab, NumPy, pandas

Slides 25 – 47

PYTHON ECOSYSTEM

Why Python for Data Analytics?

Strengths

  • Extensive library ecosystem (NumPy, pandas, scikit-learn, statsmodels)
  • Industry standard across data science, ML, and AI
  • Readable syntax — close to pseudocode
  • Active community with abundant documentation
  • Seamless integration with deep learning frameworks

In This Course

  • All labs use Google Colab — zero setup
  • Weekly notebooks with pre-loaded datasets
  • Focus on pandas + statsmodels for statistical analysis
  • matplotlib + seaborn for visualization
  • AI tools (ChatGPT, Claude) as coding assistants — not replacements

COLAB ENVIRONMENT

Google Colab — Features and Session Management

Key Features

  • Cloud-based Jupyter environment — runs in your browser
  • Free GPU/TPU access for computation-heavy tasks
  • Pre-installed: NumPy, pandas, matplotlib, scikit-learn
  • Google Drive integration for persistent storage
  • Share notebooks via link — ideal for collaboration

Session Limitations

  • Timeout: ~90 min of inactivity disconnects the runtime
  • Maximum: ~12 hours per session (free tier)
  • No persistent storage: installed packages and variables are lost on disconnect
  • Solution: Mount Google Drive: drive.mount('/content/drive')
First thing every session: File → Save a copy in Drive. The shared course notebook is read-only — you need your own copy.

PYTHON ECOSYSTEM

Standard Library Import Template

# Standard imports — copy this block into every notebook
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import statsmodels.api as sm
import warnings
warnings.filterwarnings('ignore')

# Reproducibility
np.random.seed(42)

# Plot settings
plt.rcParams['figure.dpi'] = 100
plt.rcParams['figure.figsize'] = (8, 4)
sns.set_style('whitegrid')

print('Environment ready.')
Convention: np = NumPy, pd = pandas, plt = matplotlib.pyplot, sns = seaborn, sm = statsmodels. These abbreviations are universal — every tutorial and Stack Overflow answer uses them.

NUMPY FUNDAMENTALS

NumPy — Array Creation and Basic Operations

# Array creation
a = np.array([10, 20, 30, 40, 50])
b = np.arange(0, 1, 0.1)        # [0.0, 0.1, ..., 0.9]
c = np.linspace(0, 1, 11)       # 11 evenly spaced points
d = np.zeros(5)                  # [0, 0, 0, 0, 0]

# Element-wise operations (no loops!)
print(a * 2)                     # [20, 40, 60, 80, 100]
print(a + b[:5])                 # Element-wise addition

# Descriptive statistics
print(f"Mean: {a.mean()}, Std: {a.std(ddof=1)}")
print(f"Min: {a.min()}, Max: {a.max()}")

# Boolean indexing
above_25 = a[a > 25]            # array([30, 40, 50])
Key concept: NumPy operations are vectorized — they operate on entire arrays without explicit loops. This is both faster (100x+) and more readable than looping through elements.

NUMPY FUNDAMENTALS

NumPy — Random Number Generation

np.random.seed(42)

# Normal distribution: 1000 samples, mean=100, std=15
samples = np.random.normal(loc=100, scale=15, size=1000)
print(f"Mean: {samples.mean():.2f}, Std: {samples.std():.2f}")

# Uniform distribution
uniform = np.random.uniform(low=0, high=1, size=500)

# Exponential (inter-arrival times, λ=15/hr)
arrivals = np.random.exponential(scale=1/15, size=1000)

# 2D arrays (matrices)
X = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
print(X.shape)        # (3, 3)
print(X[:, 1])        # Column 1: [2, 5, 8]
print(X.mean(axis=0)) # Column means: [4, 5, 6]
Preview: Random number generation is the foundation for Monte Carlo simulation (Week 4), bootstrap resampling (Week 8), and permutation tests (Week 3).

PANDAS ARCHITECTURE

pandas — Series and DataFrame

Series

A one-dimensional labeled array — like a single column with an index.

s = pd.Series([10, 20, 30], 
              index=['a', 'b', 'c'])
print(s['b'])   # 20
print(s.mean()) # 20.0

DataFrame

A two-dimensional labeled table — the core data structure for all analyses.

df = pd.DataFrame({
    'name': ['Alice', 'Bob'],
    'score': [92, 85]
})
print(df.shape) # (2, 2)
Mental model: A DataFrame is a dictionary of Series that share the same index. Each column is a Series; the DataFrame adds structure, alignment, and powerful operations on top.

DATA CREATION

Creating DataFrames

# From a dictionary
data = {'Machine': ['CNC-01', 'CNC-02', 'OVEN-01'],
        'MTBF': [720, 540, 1200],
        'Utilization': [0.82, 0.91, 0.65]}
df = pd.DataFrame(data)

# From a CSV file (local or URL)
url = 'https://raw.githubusercontent.com/gedeck/practical-statistics-for-data-scientists/master/data/state.csv'
state = pd.read_csv(url)

# From a NumPy array
arr = np.random.randn(100, 3)
df_arr = pd.DataFrame(arr, columns=['feature_1', 'feature_2', 'feature_3'])
Most common: pd.read_csv() handles local files, URLs, compressed files (.csv.gz), and custom delimiters. Additional readers: read_excel(), read_json(), read_sql().

DATA INSPECTION

First Steps After Loading Data

df.head()              # First 5 rows
df.tail(3)             # Last 3 rows
df.shape               # (rows, columns)
df.dtypes              # Data type of each column
df.info()              # Types + non-null counts + memory
df.describe()          # Summary stats (count, mean, std, quartiles)
df.isnull().sum()      # Missing value count per column
df.nunique()           # Unique value count per column
df.columns.tolist()    # Column names as a list
EDA checklist (Week 2 preview): (1) How many rows and columns? (2) What are the data types? (3) Any missing values? (4) What do the distributions look like? (5) Any obvious outliers? Run these commands on every new dataset before doing anything else.

INDEXING

Selecting Data: .loc and .iloc

# .loc — label-based indexing
df.loc[0:2, 'Machine']             # Rows 0-2, column 'Machine'
df.loc[df['MTBF'] > 600, :]        # Filter + all columns

# .iloc — position-based indexing
df.iloc[0:2, 1:3]                  # Rows 0-1, columns at index 1-2
df.iloc[-1, :]                     # Last row

# Single column
df['MTBF']                         # Returns a Series
df[['Machine', 'MTBF']]            # Returns a DataFrame

# Boolean masking (filtering)
high_util = df[df['Utilization'] > 0.80]
combined = df[(df['MTBF'] > 500) & (df['Utilization'] < 0.90)]
Common pitfall: .loc includes the end label; .iloc excludes the end position. df.loc[0:2] returns 3 rows (0, 1, 2); df.iloc[0:2] returns 2 rows (0, 1).

FEATURE ENGINEERING

Creating New Columns

# Arithmetic on existing columns
df['Availability'] = df['MTBF'] / (df['MTBF'] + 24)

# Conditional column with np.where
df['Risk'] = np.where(df['Utilization'] > 0.85, 'High', 'Normal')

# Apply a custom function
df['MTBF_Category'] = df['MTBF'].apply(
    lambda x: 'Excellent' if x > 1000 else 'Good' if x > 500 else 'Poor'
)

# Binning continuous variables
df['Util_Bin'] = pd.cut(df['Utilization'], bins=[0, 0.5, 0.8, 1.0],
                         labels=['Low', 'Medium', 'High'])
Feature engineering is the process of creating informative variables from raw data. In statistical modeling, the quality of your features often matters more than the choice of model.

MISSING DATA

Handling Missing Values

# Detection
df.isnull().sum()                  # Count per column
df.isnull().mean() * 100           # Percentage per column

# Deletion
df_clean = df.dropna()             # Drop rows with any NaN
df_clean = df.dropna(subset=['MTBF'])  # Drop only if MTBF is NaN

# Imputation
df['MTBF'].fillna(df['MTBF'].median(), inplace=True)  # Median fill
df['Risk'].fillna('Unknown', inplace=True)              # Category fill
Statistical warning: Missing data is rarely random (MCAR). Deleting incomplete rows can introduce bias if the missingness is related to the outcome. Always examine why data is missing before choosing a strategy. We will revisit this formally when we cover sampling (Week 8).

GROUPBY

Split-Apply-Combine with groupby

# Basic groupby
df.groupby('Type')['MTBF'].mean()

# Multiple aggregations
summary = df.groupby('Type').agg(
    Avg_MTBF=('MTBF', 'mean'),
    Std_MTBF=('MTBF', 'std'),
    Count=('Machine', 'count')
).round(1)

# Groupby + filter
reliable = df.groupby('Type').filter(lambda g: g['MTBF'].mean() > 600)

# Groupby + transform (broadcast back to original shape)
df['MTBF_zscore'] = df.groupby('Type')['MTBF'].transform(
    lambda x: (x - x.mean()) / x.std()
)
Paradigm: Split data into groups → Apply a function to each group → Combine results. This maps directly to ANOVA (Week 9): are group means significantly different?

VISUALIZATION

Essential Chart Types with matplotlib

fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# Histogram — distribution shape
axes[0,0].hist(data, bins=30, edgecolor='white')
axes[0,0].set_title('Histogram')

# Boxplot — quartiles and outliers
axes[0,1].boxplot(data)
axes[0,1].set_title('Boxplot')

# Scatter — bivariate relationship
axes[1,0].scatter(x, y, alpha=0.5)
axes[1,0].set_title('Scatter Plot')

# Bar — categorical comparison
axes[1,1].bar(categories, values)
axes[1,1].set_title('Bar Chart')

plt.tight_layout()
plt.show()

VISUALIZATION

Statistical Plots with seaborn

# Distribution plot with KDE
sns.histplot(data=df, x='MTBF', kde=True)

# Boxplot by category
sns.boxplot(data=df, x='Type', y='MTBF')

# Violin plot — richer than boxplot
sns.violinplot(data=df, x='Type', y='MTBF', inner='quartile')

# Pairwise scatter matrix
sns.pairplot(df[['MTBF', 'Utilization', 'Defect_Rate']])

# Correlation heatmap
sns.heatmap(df.corr(), annot=True, cmap='coolwarm', vmin=-1, vmax=1)

# FacetGrid — same plot across categories
g = sns.FacetGrid(df, col='Type', col_wrap=2)
g.map(plt.hist, 'MTBF')
seaborn vs. matplotlib: seaborn builds on matplotlib with statistical awareness — it automatically computes KDE, adds confidence intervals, and supports faceting. Use seaborn for statistical plots, matplotlib for custom layouts.

END-TO-END EXAMPLE

EDA Workflow — Putting It All Together

# 1. Load
url = 'https://raw.githubusercontent.com/.../state.csv'
state = pd.read_csv(url)

# 2. Inspect
print(state.shape, state.dtypes)
print(state.describe())

# 3. Clean
state = state.dropna()

# 4. Engineer
state['Pop_Density'] = state['Population'] / state['Area']

# 5. Summarize by group
state.groupby('Region')['Murder.Rate'].agg(['mean','std','count'])

# 6. Visualize
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
state['Murder.Rate'].hist(bins=15, ax=ax[0])
state.boxplot(column='Murder.Rate', by='Region', ax=ax[1])
plt.tight_layout()
plt.show()
This 6-step pattern — Load → Inspect → Clean → Engineer → Summarize → Visualize — is the workflow you will follow in every weekly lab.

AI-ASSISTED ANALYSIS

Interpreting Visualization Results with AI

Multimodal AI tools (ChatGPT, Claude, Gemini) can help interpret complex statistical visualizations.

Workflow

  1. Create the chart — hexbin, scatter, boxplot, or any statistical plot.
  2. Paste into AI — prompt: "Interpret this figure in one paragraph."
  3. Ask follow-ups — "What do the clusters above the main band mean?"
  4. Suggest conditioning — "What if we stratify by location?" → AI may suggest FacetGrid.
  5. Request summary — "Summarize the findings concisely" → usable draft for your report.
Critical Warning: AI interpretations are a starting point, not the final analysis. Every AI output must be validated with your domain knowledge. The "hallucination" risk applies to visuals too — AI may "see" patterns that do not exist.

IN-CLASS EXERCISE

Hands-On: First EDA Pipeline

Open the Week 1 Colab notebook and complete the following steps:

  1. Load the state.csv dataset from the textbook repository.
  2. Inspect: shape, dtypes, head(), describe().
  3. Check for missing values with isnull().sum().
  4. Compute mean, median, and trimmed mean (10%) of Population.
  5. Create a histogram of Murder.Rate.
  6. Create a boxplot of Population.
  7. Write 2–3 sentences interpreting what the plots reveal about the distribution.

Save your notebook to Drive: /SEN608/W1/. Submit the sharing link via Moodle → SEN608 → Week 1 → Assignment.

WEEKLY HOMEWORK

Assignment 1

Complete the following tasks in your Colab notebook:

  1. Load the airline_stats.csv dataset. Compute descriptive statistics for pct_carrier_delay.
  2. Create a boxplot of pct_carrier_delay grouped by airline. Which airline has the most variable delay pattern?
  3. Load kc_tax.csv.gz. Filter to reasonable ranges. Create a hexbin plot of SqFtTotLiving vs. TaxAssessedValue.
  4. Write a 1-paragraph interpretation of each visualization. Use AI (ChatGPT/Claude) to generate an initial interpretation, then critically evaluate and improve it.

AI-Assisted Exploration (3rd Edition)

  1. Use an AI tool to learn about robust estimates of location. Explore implementations in Python.
  2. Improve the data dictionary of a public dataset (e.g., UCI ML Repository) using AI. Compare with the original.
  3. Have AI interpret one of your visualizations. Deepen with follow-up questions. Critically evaluate the output.

Deadline: before Week 2 class. Submission: Moodle Assignment module. Late penalty: -20% per day (max 3 days).

COMMON MISTAKES

Frequent Errors in Week 1

#MistakeSolution
1Forgetting to save a copy of the shared notebookFile → Save a copy in Drive — always first
2Running cells out of orderRuntime → Run all to verify full-notebook execution
3Confusing .loc (label) with .iloc (position)Use .loc by default; switch to .iloc only for positional needs
4Applying mean() to categorical columnsCheck df.dtypes before computing statistics
5Ignoring warnings from pandasWarnings often indicate type coercion or chained assignment issues
6Not checking for missing values before analysisdf.isnull().sum() should be a reflex

LEARNING OUTCOMES

What You Should Know After This Week

Conceptual

  • Distinguish descriptive, inferential, predictive, and causal problems
  • Identify variable types (continuous, discrete, ordinal, nominal, binary)
  • Explain why random sampling matters and name four types of selection bias
  • State the three principles of statistical thinking
  • Describe what reproducibility means and why it's the minimum standard

Practical

  • Set up and navigate a Google Colab notebook
  • Create NumPy arrays and perform vectorized operations
  • Build, inspect, filter, and group pandas DataFrames
  • Create histograms, boxplots, scatter plots, and bar charts
  • Follow the Load → Inspect → Clean → Engineer → Summarize → Visualize workflow

NEXT WEEK

Preparation for Week 2

Preparation:

Week 2 Preview: Data Exploration & EDA

We will formalize the EDA process: estimates of location (mean, median, trimmed mean), estimates of variability (std, IQR, MAD), distribution visualization (histograms, KDE, boxplots), and correlation analysis. Bring your laptop — it's a hands-on lab.

Academic Contact: onurpolat@hacettepe.edu.tr • Office Hours: To be announced at the beginning of the semester.