On this page
Data Science & Machine Learning
Prev: Web Development & APIs | Up: Popular Application Domains | Next: Desktop GUI Development
Rel: statistics, csv, math, random, collections, array
Ref: docs.python.org — statistics | docs.python.org — csv
Tags: #public #python3 #tutorials #domains #data-science #ml #stdlib
Contents
- > Tabular Data Pipelines (`csv` & `collections`)
- > Descriptive Statistics & Probability (`statistics`)
- > Linear Regression (`statistics.linear_regression`)
- > Pure-Stdlib k-Nearest Neighbors (k-NN) Classifier
Tabular Data Pipelines (csv & collections)
[[stdlib_module/csv|csv.DictReader]] and [[stdlib_module/collections|collections.defaultdict]] provide clean, streaming tabular ingestion and group-by aggregations without loading third-party DataFrame libraries.
import csv
import io
from collections import defaultdict
import statistics
raw_csv = """region,revenue
west,120.5
east,95.0
west,140.0
east,110.5
west,130.0
"""
by_region: dict[str, list[float]] = defaultdict(list)
for row in csv.DictReader(io.StringIO(raw_csv)):
by_region[row["region"]].append(float(row["revenue"]))
summary = {
region: {"count": len(vals), "mean": round(statistics.mean(vals), 2)}
for region, vals in by_region.items()
}
print(summary) # {'west': {'count': 3, 'mean': 130.17}, 'east': {'count': 2, 'mean': 102.75}}
Descriptive Statistics & Probability (statistics)
[[stdlib_module/statistics|statistics]] includes central tendency, dispersion, quantiles, correlation, covariance, and NormalDist for analytical normal distributions.
import statistics
from statistics import NormalDist
samples = [12, 15, 14, 10, 18, 21, 14, 16]
print("mean:", statistics.mean(samples))
print("median:", statistics.median(samples))
print("stdev:", round(statistics.stdev(samples), 3))
print("quantiles:", statistics.quantiles(samples, n=4))
dist = NormalDist(mu=100, sigma=15)
print("P(X <= 115):", round(dist.cdf(115), 4)) # 0.8413
Linear Regression (statistics.linear_regression)
Python 3.10+ includes ordinary least-squares linear regression directly in statistics:
import statistics
hours_studied = [1, 2, 3, 4, 5, 6]
exam_scores = [52, 58, 65, 71, 79, 86]
model = statistics.linear_regression(hours_studied, exam_scores)
r = statistics.correlation(hours_studied, exam_scores)
predicted = model.slope * 7 + model.intercept
print(f"y = {model.slope:.2f}x + {model.intercept:.2f} (r={r:.4f}) -> 7h predicts {predicted:.1f}")
Pure-Stdlib k-Nearest Neighbors (k-NN) Classifier
Using [[stdlib_module/math|math.dist()]] (Euclidean distance) and [[stdlib_module/collections|collections.Counter]], a working k-NN classifier takes only a few lines of standard library code:
from collections import Counter
import math
def knn_predict(
train_data: list[tuple[tuple[float, ...], str]],
query: tuple[float, ...],
k: int = 3,
) -> str:
neighbors = sorted(train_data, key=lambda item: math.dist(item[0], query))[:k]
votes = Counter(label for _, label in neighbors)
return votes.most_common(1)[0][0]
dataset = [
((1.0, 1.1), "A"),
((1.2, 0.9), "A"),
((5.0, 5.2), "B"),
((4.8, 5.1), "B"),
]
print("Predicted class:", knn_predict(dataset, (1.1, 1.0), k=3)) # 'A'
Linked from
- tuts/python3/tutorials
- tuts/python3/tutorials/popular_application_domains
- tuts/python3/tutorials/popular_application_domains/data_science_and_machine_learning
- tuts/python3/tutorials/popular_application_domains/desktop_gui_development
- tuts/python3/tutorials/popular_application_domains/web_development_and_apis
Related notes
- tuts/python3/tutorials/popular_application_domains/desktop_gui_development Linked here; links to this page; shared tags: #domains, #stdlib, #tutorials
- tuts/python3/tutorials/popular_application_domains/web_development_and_apis Linked here; links to this page; shared tags: #domains, #stdlib, #tutorials
- tuts/python3/tutorials/popular_application_domains Linked here; links to this page; shared tags: #domains, #tutorials
- tuts/python3/stdlib_module/array Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/collections Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/csv Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/math Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/random Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/statistics Linked here; shared tags: #stdlib
- tuts/python3/tutorials links to this page; shared tags: #tutorials