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.
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 Type | Typical ML Use | Python Entry Point | Risk |
|---|---|---|---|
| Flat files (CSV, JSONL, Parquet) | Batch training, benchmarks | pd.read_csv, pd.read_parquet | Schema drift, encoding errors |
| SQL / warehouse | Feature tables, labels joined to events | pd.read_sql, SQLAlchemy | Query cost, stale snapshots |
| REST / GraphQL APIs | Embeddings, enrichment, live labels | requests, official SDKs | Rate limits, versioning |
| Event streams | Real-time ranking, fraud | Kafka consumers, webhooks | Ordering, duplicates |
| Web scraping | Niche corpora, price monitoring | requests + parsers, Playwright | Legal, fragile HTML |
| Synthetic / LLM-generated | Augmentation, distillation | API batch jobs | Hallucination, 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)
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.
| Hub | Strengths | Check Before Use |
|---|---|---|
| Hugging Face Datasets | NLP, vision, audio; streaming loaders | License tag, dataset card, known biases |
| Kaggle | Tabular competitions, notebooks | Competition rules vs commercial use |
| UCI / OpenML | Classic ML benchmarks | Small, often outdated distributions |
| Government open data | Policy, health, transport | Aggregation 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.
Reality: Visibility ≠ license. Copyright, platform ToS, and privacy law may restrict use. Document legal review for scraped or user-generated corpora.
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
- Task alignment — Does each row map to a prediction or generation objective?
- Temporal split — Can you hold out future data to simulate deployment?
- PII scan — Regex or dedicated tools before sharing notebooks.
- Idempotent jobs — Re-runs should not corrupt prior raw snapshots.
- Cost model — API tokens, warehouse scan bytes, storage growth.
Knowledge Check
- Short Answer: What is data provenance? Answer: Documented origin and history of data including source, time, and transformations.
- True/False: Raw landing zones should be immutable after write. Answer: True (append new batches; do not overwrite silently).
- 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).
- Short Answer: Why write Parquet instead of only CSV for raw archives? Answer: Typed columns, compression, faster reads at scale.
- True/False:
robots.txtalone grants legal permission to scrape. Answer: False. - Multiple Choice: Volume 03 tool for HTTP JSON APIs: (a) regex, (b) requests, (c) matplotlib, (d) asyncio only. Answer: (b).
- Short Answer: Name two risks of using Kaggle competition data in production. Answer: License restrictions; distribution unlike live traffic.
- True/False: Streaming dataset loaders help when data exceeds RAM. Answer: True.
- Multiple Choice: PII in a public dataset should be: (a) ignored, (b) redacted before sharing, (c) encrypted in notebooks only, (d) sold. Answer: (b).
- 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.
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.