File size: 11,276 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | import csv
import html
import math
from collections import defaultdict
def quantile(values, fraction):
values = sorted(values)
pos = (len(values) - 1) * fraction
lo, hi = math.floor(pos), math.ceil(pos)
return values[lo] + (values[hi] - values[lo]) * (pos - lo)
def pearson(xs, ys):
ax, ay = sum(xs) / len(xs), sum(ys) / len(ys)
num = sum((x - ax) * (y - ay) for x, y in zip(xs, ys))
den = math.sqrt(sum((x - ax) ** 2 for x in xs) * sum((y - ay) ** 2 for y in ys))
return num / den if den else 0.0
def write_csv(path, rows):
with open(path, "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print("1/4 Read Boston data and detect IQR outliers")
lines = [line.split() for line in open("BostonHousing.txt", encoding="utf-8-sig") if line.strip()]
header = lines[0]
boston = [dict(zip(header, values)) for values in lines[1:] if len(values) == len(header)]
prices = [float(row["medv"]) for row in boston]
q1, q3 = quantile(prices, .25), quantile(prices, .75)
low, high = q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1)
outliers = [row for row in boston if not low <= float(row["medv"]) <= high]
clean = [row.copy() for row in boston if low <= float(row["medv"]) <= high]
for row in clean:
row["rm_rounded"] = str(math.floor(float(row["rm"]) + 0.5))
write_csv("boston_clean.csv", clean)
print(f"Boston rows={len(boston)}, outliers={len(outliers)}, retained={len(clean)}")
print("2/4 Compute Pearson correlations and room-group means")
correlations = {
name: pearson([float(row[name]) for row in boston], prices)
for name in header if name != "medv"
}
top = sorted(correlations, key=lambda name: (-abs(correlations[name]), name))[:3]
rooms = defaultdict(list)
for row in clean:
rooms[int(row["rm_rounded"])].append(float(row["medv"]))
means = {room: sum(values) / len(values) for room, values in rooms.items()}
print("3/4 Clean Titanic and group survival outcomes")
with open("titanic.csv", newline="", encoding="utf-8-sig") as handle:
titanic = list(csv.DictReader(handle))
ages = [float(row["age"]) for row in titanic if row.get("age", "").strip()]
age_fill = quantile(ages, .5)
for row in titanic:
row["age"] = row.get("age") or str(age_fill)
row["deck"] = row.get("deck") or "Unknown"
row["is_alone"] = str(int(float(row["sibsp"]) + float(row["parch"]) == 0)).lower()
write_csv("titanic_clean.csv", titanic)
groups = defaultdict(list)
for row in titanic:
groups[(row["sex"], row["class"])].append(int(row["survived"]))
rates = {key: sum(values) / len(values) for key, values in groups.items()}
print("4/4 Render report with offline SVG charts")
def table(identifier, columns, rows):
headings = "".join(f"<th scope='col'>{html.escape(str(value))}</th>" for value in columns)
body = "".join(
"<tr>" + "".join(f"<td>{html.escape(str(value))}</td>" for value in row) + "</tr>"
for row in rows
)
return f'<table id="{identifier}"><thead><tr>{headings}</tr></thead><tbody>{body}</tbody></table>'
def svg_text(x, y, label, anchor="middle", extra=""):
return (f'<text x="{x:.2f}" y="{y:.2f}" text-anchor="{anchor}" {extra}>'
f'{html.escape(str(label))}</text>')
def scatter_chart(rows):
xs = [float(row["rm"]) for row in rows]
ys = [float(row["medv"]) for row in rows]
xmean, ymean = sum(xs) / len(xs), sum(ys) / len(ys)
denominator = sum((x - xmean) ** 2 for x in xs)
slope = sum((x - xmean) * (y - ymean) for x, y in zip(xs, ys)) / denominator if denominator else 0
intercept = ymean - slope * xmean
xmin, xmax = min(xs), max(xs)
xlow, xhigh = (xmin, xmax) if xmin != xmax else (xmin - .5, xmax + .5)
# Include the complete fitted segment in the linear y scale, with marker clearance.
ylow = min(min(ys), slope * xmin + intercept, slope * xmax + intercept)
yhigh = max(max(ys), slope * xmin + intercept, slope * xmax + intercept)
padding = max((yhigh - ylow) * .08, .5)
ylow, yhigh = ylow - padding, yhigh + padding
left, right, top_edge, bottom = 68, 494, 22, 238
def xpx(value):
return left + (right - left) * (value - xlow) / (xhigh - xlow)
def ypx(value):
return bottom - (bottom - top_edge) * (value - ylow) / (yhigh - ylow)
parts = ['<svg id="boston-scatter" width="520" height="300" viewBox="0 0 520 300" '
'role="img" aria-label="Cleaned Boston rm versus medv with least-squares line" '
'xmlns="http://www.w3.org/2000/svg">']
for index in range(5):
xvalue = xlow + (xhigh - xlow) * index / 4
yvalue = ylow + (yhigh - ylow) * index / 4
x, y = xpx(xvalue), ypx(yvalue)
parts.append(f'<line class="gridline" x1="{left}" y1="{y:.2f}" x2="{right}" y2="{y:.2f}"/>')
parts.append(f'<line class="axis" x1="{x:.2f}" y1="{bottom}" x2="{x:.2f}" y2="{bottom + 5}"/>')
parts.append(svg_text(x, bottom + 22, f"{xvalue:.2f}"))
parts.append(svg_text(left - 10, y + 4, f"{yvalue:.2f}", "end"))
parts.append(f'<path class="axis" d="M {left} {top_edge} V {bottom} H {right}"/>')
parts.append(svg_text((left + right) / 2, 287, "rm", extra='class="axis-title"'))
parts.append(svg_text(18, 130, "medv", extra='class="axis-title" transform="rotate(-90 18 130)"'))
parts.append(f'<line id="trend-line" data-slope="{slope:.8f}" data-intercept="{intercept:.8f}" '
f'x1="{xpx(xmin):.2f}" y1="{ypx(slope * xmin + intercept):.2f}" '
f'x2="{xpx(xmax):.2f}" y2="{ypx(slope * xmax + intercept):.2f}" '
'stroke="#c64e32" stroke-width="2.5"/>')
for x, y in zip(xs, ys):
parts.append(f'<circle class="housing-point" data-rm="{x:.6f}" data-medv="{y:.6f}" '
f'cx="{xpx(x):.2f}" cy="{ypx(y):.2f}" r="4" fill="#2869ac"/>')
parts.append('</svg>')
return "".join(parts)
def survival_chart(group_rates):
groups = sorted(group_rates.items())
left, right, top_edge, bottom = 68, 500, 22, 212
slot = (right - left) / len(groups)
bar_width = min(40, slot * .58)
parts = ['<svg id="survival-bars" width="520" height="300" viewBox="0 0 520 300" '
'role="img" aria-label="Titanic survival rate by sex and class" '
'xmlns="http://www.w3.org/2000/svg">']
for rate in (0, .25, .5, .75, 1):
y = bottom - (bottom - top_edge) * rate
parts.append(f'<line class="gridline" x1="{left}" y1="{y:.2f}" x2="{right}" y2="{y:.2f}"/>')
parts.append(svg_text(left - 10, y + 4, f"{rate:.0%}", "end"))
parts.append(f'<path class="axis" d="M {left} {top_edge} V {bottom} H {right}"/>')
parts.append(svg_text(18, 118, "Survival rate", extra='class="axis-title" transform="rotate(-90 18 118)"'))
for index, ((sex, category), rate) in enumerate(groups):
center = left + slot * (index + .5)
height = (bottom - top_edge) * rate
parts.append(f'<rect class="survival-bar" data-sex="{html.escape(sex)}" '
f'data-class="{html.escape(category)}" data-rate="{rate:.6f}" '
f'x="{center - bar_width / 2:.2f}" y="{bottom - height:.2f}" '
f'width="{bar_width:.2f}" height="{height:.2f}" fill="#27806f"/>')
parts.append(svg_text(center, bottom - height - 7, f"{rate:.0%}"))
# Labels exist independently of bar height, including zero-survival groups.
parts.append(f'<text class="group-label" x="{center:.2f}" y="{bottom + 22}" text-anchor="middle">'
f'<tspan x="{center:.2f}">{html.escape(sex)}</tspan> '
f'<tspan x="{center:.2f}" dy="16">{html.escape(category)}</tspan></text>')
parts.append(svg_text((left + right) / 2, 287, "Passenger group (sex × class)", extra='class="axis-title"'))
parts.append('</svg>')
return "".join(parts)
style = """
* { box-sizing: border-box; }
body { margin: 0; padding: 24px; background: #f3f6fa; color: #1e3044;
font-family: system-ui, -apple-system, sans-serif; font-size: 13px; }
main { max-width: 1120px; margin: auto; }
h1 { margin: 0 0 6px; font-size: 26px; letter-spacing: -.5px; }
h2 { margin: 0 0 12px; font-size: 16px; }
p { line-height: 1.5; }
.subtitle { margin: 0 0 18px; color: #586a7f; }
.summaries, .charts { display: grid; gap: 16px; margin-bottom: 16px; }
.summaries { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.charts { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; }
section { background: white; padding: 16px; border: 1px solid #dbe3ec; border-radius: 12px; }
table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
th, td { text-align: left; padding: 5px 9px; border-bottom: 1px solid #e8edf3; }
th { color: #53677c; font-size: 12px; background: #f5f8fc; }
td:last-child, th:last-child { text-align: right; }
tbody tr:last-child td { border-bottom: 0; }
svg { display: block; width: 100%; height: auto; overflow: visible; }
svg text { font: 11px system-ui, sans-serif; fill: #40546b; }
svg .axis-title { font-size: 12px; font-weight: 600; }
.gridline { stroke: #e5ebf2; stroke-width: 1; }
.axis { fill: none; stroke: #8b9bad; stroke-width: 1; }
.caption { margin: 8px 0 0; color: #586a7f; font-size: 12px; }
@media (max-width: 760px) { body { padding: 12px; } .summaries, .charts { grid-template-columns: 1fr; } }
"""
parts = [
'<!doctype html><html lang="en"><head><meta charset="utf-8">',
'<meta name="viewport" content="width=device-width, initial-scale=1">',
'<title>Boston and Titanic analysis</title>', f'<style>{style}</style></head><body><main>',
'<h1>Boston Housing & Titanic</h1>',
f'<p class="subtitle">Reproducible data cleaning and group analysis · Boston: {len(clean)} retained / {len(boston)} rows · Titanic: {len(titanic)} rows</p>',
'<div class="summaries"><section><h2>Boston · IQR screening</h2>',
table('iqr-summary', ['Metric', 'Value'], [('Q1', f'{q1:.3f}'), ('Q3', f'{q3:.3f}'),
('lower', f'{low:.3f}'), ('upper', f'{high:.3f}'), ('outliers', str(len(outliers)))]),
'</section><section><h2>Top correlations with medv</h2>',
table('correlations', ['Feature', 'Pearson r'], [(name, f'{correlations[name]:.5f}') for name in top]),
'<p class="caption">Pearson coefficients on the original Boston rows; ranked by absolute value.</p>',
'</section><section><h2>Mean medv by room group</h2>',
table('room-means', ['rm_rounded', 'Mean medv'], [(room, f'{mean:.3f}') for room, mean in sorted(means.items())]),
'</section></div><div class="charts"><section><h2>Boston · rooms and home value</h2>',
scatter_chart(clean),
f'<p class="caption">Blue: all {len(clean)} cleaned observations. Red: ordinary least-squares trend. Both axes use linear scales.</p>',
'</section><section><h2>Titanic · survival by passenger group</h2>',
survival_chart(rates),
table('survival-rates', ['Sex', 'Class', 'Survival rate'],
[(sex, category, f'{rate:.2%}') for (sex, category), rate in sorted(rates.items())]),
'</section></div></main></body></html>',
]
with open("report.html", "w", encoding="utf-8") as handle:
handle.write("".join(parts))
|