← Master Index
Vol. 04 Module 4.1 Lecture

Data Collection

Data Preparation

How This Lesson Fits the Module — Opening Lecture

Volume 03 taught you to read data with file I/O, Pandas, and regex, and to fetch remote data with REST APIs. Module 4.1 begins where those skills land in production: data collection—deciding what to gather, from where, under what legal and ethical constraints, and how to land it in a reproducible raw layer.

Garbage in, garbage out is not a slogan—it is the default outcome when collection is ad hoc. AI engineers own the first mile of the pipeline: sources, contracts, provenance, and storage format before cleaning or labeling.

Learning Objectives

By the end of this lesson, students should be able to:

  • Compare primary data sources: files, databases, APIs, streams, and web scraping.
  • Design a minimal ingestion script that lands raw data with timestamps and source metadata.
  • Apply API pagination, rate limits, and authentication patterns from Volume 03.
  • Evaluate public datasets (Hugging Face, Kaggle, UCI) for license fit and bias risk.
  • Explain scraping ethics: robots.txt, terms of service, PII, and consent.
  • Document a data collection plan that downstream cleaning and ETL can execute.

Introduction: The First Mile of ML

Every model is trained on observations someone chose to record. Collection defines the population your model will generalize to—and the biases it will inherit. Before you call pd.read_csv, answer: who created this data, for what purpose, and is it legal to use for your task?

Production AI teams separate raw (immutable landing zone) from curated (cleaned, labeled, feature-ready). This lecture focuses on getting data into raw storage reliably and traceably.

Definition — Data Provenance

Provenance is the documented history of a dataset: source system, extraction time, transformation version, and license. Without provenance you cannot debug model drift, reproduce experiments, or defend compliance audits.

Minimum provenance fields for each ingest batch: source_id, collected_at, collector_version, license, row_count, checksum.

Data Source Landscape

Source TypeTypical ML UsePython Entry PointRisk
Flat files (CSV, JSONL, Parquet)Batch training, benchmarkspd.read_csv, pd.read_parquetSchema drift, encoding errors
SQL / warehouseFeature tables, labels joined to eventspd.read_sql, SQLAlchemyQuery cost, stale snapshots
REST / GraphQL APIsEmbeddings, enrichment, live labelsrequests, official SDKsRate limits, versioning
Event streamsReal-time ranking, fraudKafka consumers, webhooksOrdering, duplicates
Web scrapingNiche corpora, price monitoringrequests + parsers, PlaywrightLegal, fragile HTML
Synthetic / LLM-generatedAugmentation, distillationAPI batch jobsHallucination, license of outputs

Collecting from Files and APIs

Bridge Volume 03 skills into a repeatable ingest pattern: fetch or copy, validate shape, write to a dated raw path, log metadata.

from datetime import datetime, timezone
from pathlib import Path
import hashlib
import json
import os

import pandas as pd
import requests

RAW = Path("data/raw/support_tickets")
RAW.mkdir(parents=True, exist_ok=True)

def ingest_csv_export(src: Path, source_id: str) -> dict:
    df = pd.read_csv(src, encoding="utf-8")
    ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    out = RAW / f"{source_id}_{ts}.parquet"
    df.to_parquet(out, index=False)
    digest = hashlib.sha256(out.read_bytes()).hexdigest()
    meta = {
        "source_id": source_id,
        "collected_at": ts,
        "rows": len(df),
        "columns": list(df.columns),
        "path": str(out),
        "sha256": digest,
    }
    with open(RAW / f"{source_id}_{ts}.meta.json", "w") as f:
        json.dump(meta, f, indent=2)
    return meta

def fetch_paginated_api(base_url: str, headers: dict, page_param: str = "page"):
    page = 1
    rows = []
    while True:
        resp = requests.get(
            base_url,
            headers=headers,
            params={page_param: page, "per_page": 100},
            timeout=30,
        )
        resp.raise_for_status()
        batch = resp.json()["data"]
        if not batch:
            break
        rows.extend(batch)
        page += 1
    return pd.DataFrame(rows)
Volume 03 Bridge You already know requests.post(..., json=...) and resp.raise_for_status(). Collection adds persistence: never mutate the API response in place—write immutable raw snapshots first, then transform in Data Cleaning or ETL.

Public Datasets and Hubs

Benchmark datasets accelerate prototyping, but production models often need proprietary or domain-specific data. When using public hubs, verify license, documentation, and demographic coverage.

HubStrengthsCheck Before Use
Hugging Face DatasetsNLP, vision, audio; streaming loadersLicense tag, dataset card, known biases
KaggleTabular competitions, notebooksCompetition rules vs commercial use
UCI / OpenMLClassic ML benchmarksSmall, often outdated distributions
Government open dataPolicy, health, transportAggregation suppression, refresh cadence
# Hugging Face — stream large splits without loading all RAM
from datasets import load_dataset

ds = load_dataset("imdb", split="train", streaming=True)
sample = next(iter(ds))
print(sample.keys(), sample["text"][:80])

Web Scraping: Capability and Responsibility

When Scraping Is Reasonable

  • Public pages with explicit permission or open license
  • Your own product’s rendered HTML for testing
  • Official APIs unavailable but data is clearly public domain
  • Low volume, respectful rate limiting, identifiable user-agent

When to Stop

  • Terms of service prohibit automated access
  • Personal data without lawful basis (GDPR, CCPA)
  • Paywalled or login-gated content without contract
  • Anti-bot measures signal provider intent to block

Use robots.txt as a signal, not legal advice. Prefer official APIs and licensed datasets for production ML. Regex from Module 3.4 helps extract fields from semi-structured HTML only when parsing is permitted.

Common Misconception: “If data is on the public web, I can train a commercial model on it.”

Reality: Visibility ≠ license. Copyright, platform ToS, and privacy law may restrict use. Document legal review for scraped or user-generated corpora.

Common Misconception: “More data always beats better collection design.”

Reality: Duplicated, mislabeled, or out-of-distribution bulk data increases training cost without improving generalization. A smaller, representative, well-documented sample often wins.

Collection Checklist for AI Engineers

Knowledge Check

  1. Short Answer: What is data provenance? Answer: Documented origin and history of data including source, time, and transformations.
  2. True/False: Raw landing zones should be immutable after write. Answer: True (append new batches; do not overwrite silently).
  3. Multiple Choice: Best first step for a REST catalog with pages: (a) one giant GET, (b) pagination loop, (c) scrape HTML, (d) manual CSV. Answer: (b).
  4. Short Answer: Why write Parquet instead of only CSV for raw archives? Answer: Typed columns, compression, faster reads at scale.
  5. True/False: robots.txt alone grants legal permission to scrape. Answer: False.
  6. Multiple Choice: Volume 03 tool for HTTP JSON APIs: (a) regex, (b) requests, (c) matplotlib, (d) asyncio only. Answer: (b).
  7. Short Answer: Name two risks of using Kaggle competition data in production. Answer: License restrictions; distribution unlike live traffic.
  8. True/False: Streaming dataset loaders help when data exceeds RAM. Answer: True.
  9. Multiple Choice: PII in a public dataset should be: (a) ignored, (b) redacted before sharing, (c) encrypted in notebooks only, (d) sold. Answer: (b).
  10. Short Answer: What metadata field lets you verify file integrity after copy? Answer: Checksum (e.g., SHA-256).

Key Takeaways

  • Data collection defines the population and biases your model will inherit.
  • Land immutable raw snapshots with provenance before any cleaning.
  • Reuse Pandas, file I/O, regex, and requests from Volume 03 in structured ingest jobs.
  • Evaluate licenses and ethics for APIs, public hubs, and scraping.
  • Next: Data Cleaning to make raw data trustworthy.
Trainer’s Guide

Lab: Students ingest the same dataset two ways—local CSV via Pandas and paginated JSON via requests—then write matching .meta.json sidecars. Compare row counts and checksums.

Ethics debate: Present a scenario (scraping product reviews vs buying a licensed feed). Teams argue go/no-go using ToS, PII, and reproducibility criteria.

What’s Next Open Data Cleaning to handle duplicates, types, and normalization on the raw layer you just built.