File size: 16,266 Bytes
dedc31d
8406363
 
4d73445
8406363
 
 
 
9f59116
7f76c44
597caf5
8406363
14d5b46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597caf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e9171f
597caf5
 
1e9171f
4d73445
8406363
1e9171f
4d73445
1e9171f
4d73445
 
597caf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e9171f
 
597caf5
 
1e9171f
597caf5
8c252bd
 
4d73445
597caf5
4d73445
 
 
597caf5
8fd4d4f
 
4d73445
9f59116
4d73445
1e9171f
597caf5
1e9171f
597caf5
1e9171f
 
 
 
7f76c44
597caf5
1e9171f
597caf5
1e9171f
597caf5
1e9171f
597caf5
1e9171f
 
597caf5
1e9171f
597caf5
1e9171f
74dc44a
597caf5
 
 
74dc44a
597caf5
1e9171f
 
 
 
 
 
 
 
 
7f76c44
 
 
1e9171f
 
 
 
74dc44a
8c252bd
4d73445
8c252bd
74dc44a
8c252bd
1e9171f
597caf5
 
1e9171f
597caf5
1e9171f
9f59116
 
597caf5
 
0bcf022
 
 
 
 
7f76c44
4d73445
1e9171f
597caf5
8c252bd
9f59116
597caf5
 
 
 
7f76c44
1e9171f
7f76c44
597caf5
 
 
7f76c44
 
597caf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e9171f
597caf5
 
 
1e9171f
597caf5
1e9171f
597caf5
 
 
 
 
 
 
 
1e9171f
597caf5
74dc44a
597caf5
 
 
 
 
1e9171f
 
597caf5
 
 
 
 
 
 
 
 
 
1e9171f
597caf5
 
 
 
 
 
 
1e9171f
597caf5
 
1e9171f
 
597caf5
 
 
1e9171f
597caf5
 
 
1e9171f
597caf5
1e9171f
597caf5
7f76c44
597caf5
 
 
 
 
 
 
 
1e9171f
 
597caf5
 
 
1e9171f
74dc44a
597caf5
 
 
 
 
 
 
 
 
0bcf022
597caf5
 
0bcf022
597caf5
 
 
74dc44a
597caf5
1e9171f
74dc44a
597caf5
 
 
0bcf022
597caf5
 
0bcf022
597caf5
 
 
 
1e9171f
 
 
74dc44a
597caf5
 
 
74dc44a
597caf5
74dc44a
1e9171f
 
 
 
 
8406363
597caf5
 
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321

import gradio as gr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import plotly.graph_objects as go
import plotly.express as px
import time

FEATURE_LABELS = {
    "age": "Leeftijd",
    "sex": "Geslacht",
    "bmi": "BMI (Body Mass Index)",
    "bp": "Bloeddruk",
    "s1": "Totale cholesterol",
    "s2": "LDL-cholesterol",
    "s3": "HDL-cholesterol",
    "s4": "Chol./HDL-verhouding",
    "s5": "Triglyceriden",
    "s6": "Bloedsuiker (glucose)",
    "target": "Doelscore (progressie)",
}
LABEL_TO_KEY = {v: k for k, v in FEATURE_LABELS.items()}

MEDICAL_MD = """
### Medisch nut  

**Wat zien we hier?**  
Ik heb een bestaande, anonieme gezondheidsdataset gebruikt die speciaal beschikbaar is gemaakt voor onderzoek en studie. In deze gegevens staan metingen van een grote groep patiënten, zoals **bloedwaarden, BMI, cholesterol en bloedsuiker**.  

Zo'n enorme berg cijfers is voor artsen en ziekenhuizen bijna niet in één keer te overzien. Het is gewoon te veel om met het blote oog patronen uit te halen.  

**Daar komt kunstmatige intelligentie om de hoek kijken.**  
Met deze techniek (PCA) kan de computer de data slim samenvatten en patronen zichtbaar maken. Dit programma dat ik heb ontworpen laat live zien hoe die samenvatting werkt.  

- Elke punt is één patiënt.  
- De kleur laat zien hoe hoog of laag een bepaalde meting is (standaard: BMI).  
- De pijlen (in de 2D-biplot) laten zien welke metingen het meeste invloed hebben.  
- Links bovenin kun je kiezen welke meting je als uitgangspunt wilt nemen.  

**En wat heb je hieraan?**  
In de praktijk gebruiken artsen en onderzoekers zo'n plot om patronen en verbanden te ontdekken. 👉 Het is dus niet alleen een mooi plaatje, maar echt een manier om grote hoeveelheden data sneller en slimmer te begrijpen.  

Met AI kunnen we patronen vinden die je met het blote oog nooit zou zien. Dat maakt dit niet alleen een mooie visualisatie, maar ook een knap stukje technologie met échte waarde voor onderzoek en zorg.  

**Speel zelf de onderzoeker!**  
Doe alsof je een arts bent en kies links bovenin een waarde, bijvoorbeeld **cholesterol**, **leeftijd** of **geslacht**. Klik daarna op **Update visualisaties** en ontdek je eigen patronen in de data.  
"""

# -------------------- Data helpers --------------------
def load_diabetes_df():
    d = datasets.load_diabetes()
    X = pd.DataFrame(d.data, columns=d.feature_names)  # gestandaardiseerd
    y = pd.Series(d.target, name="target")
    df = X.copy(); df["target"] = y
    return df

def compute_overview_table(df: pd.DataFrame):
    keys = ["bmi","bp","s1","s2","s3","s4","s5","s6"]
    rows = []
    for k in keys:
        vals = df[k].dropna().values
        mean = float(vals.mean())
        pct_above = float((vals > 0).mean() * 100.0)  # 0 ≈ globaal gemiddelde
        pct_below = float((vals < 0).mean() * 100.0)
        rows.append({
            "Meting": FEATURE_LABELS.get(k, k),
            "Gemiddelde (gestandaardiseerd)": round(mean, 3),
            "% boven gemiddelde": round(pct_above, 1),
            "% onder gemiddelde": round(pct_below, 1),
        })
    table = pd.DataFrame(rows)
    note = ("Let op: waarden in deze dataset zijn **gestandaardiseerd**. `0` ≈ algemeen gemiddelde. "
            "Positief = hoger dan gemiddeld, negatief = lager dan gemiddeld.")
    return table, note

# -------------------- PCA helpers --------------------
def compute_pca(df: pd.DataFrame, n_components: int, standardize: bool):
    feats = [c for c in df.columns if c != "target"]
    X = df[feats].values
    if standardize:
        scaler = StandardScaler(with_mean=True, with_std=True)
        Xs = scaler.fit_transform(X)
    else:
        Xs = X
    pca = PCA(n_components=min(int(n_components), Xs.shape[1]))
    Z = pca.fit_transform(Xs)
    loadings = pca.components_.T
    expl = pca.explained_variance_ratio_
    return feats, Xs, Z, loadings, expl

# -------------------- Plot builders --------------------
def build_biplot_plotly(df, Z, loadings, feats, color_key, arrow_scale=2.0):
    # Hover info
    fields = ["bmi","bp","s1","s2","s3","s4","s5","s6","age","sex","target"]
    hover_text = [
        "<br>".join(f"{FEATURE_LABELS.get(k,k)}: {df.iloc[i][k]:.3f}" for k in fields)
        for i in range(len(df))
    ]
    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=Z[:,0], y=Z[:,1], mode="markers",
        marker=dict(size=8, color=df[color_key].values),
        text=hover_text, hovertemplate="%{text}<extra></extra>"
    ))
    # loading pijlen
    for i, key in enumerate(feats):
        x = loadings[i,0]*arrow_scale; y = loadings[i,1]*arrow_scale
        fig.add_annotation(x=x, y=y, ax=0, ay=0, xref="x", yref="y", axref="x", ayref="y",
                           showarrow=True, arrowhead=3)
        fig.add_annotation(x=x*1.05, y=y*1.05, text=FEATURE_LABELS.get(key,key),
                           showarrow=False, font=dict(size=10))
    fig.update_layout(title="PCA-biplot (2D, hover)", xaxis_title="PC1", yaxis_title="PC2",
                      margin=dict(l=10, r=10, t=40, b=10))
    return fig

def build_biplot_matplotlib(df, Z, loadings, feats, color_key, arrow_scale=2.0, point_size=32, alpha=0.85):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    sc = ax.scatter(Z[:,0], Z[:,1], c=df[color_key].values, s=point_size, alpha=alpha)
    cbar = plt.colorbar(sc, ax=ax, pad=0.02); cbar.set_label(f"Kleur: {FEATURE_LABELS.get(color_key,color_key)}")
    ax.set_xlabel("PC1"); ax.set_ylabel("PC2"); ax.set_title("PCA-biplot — PNG-export")
    for i,key in enumerate(feats):
        x=loadings[i,0]*arrow_scale; y=loadings[i,1]*arrow_scale
        ax.arrow(0,0,x,y, head_width=0.05, head_length=0.08, fc="k", ec="k", length_includes_head=True)
        ax.text(x*1.08, y*1.08, FEATURE_LABELS.get(key,key), fontsize=9, ha="center", va="center")
    ax.axhline(0,color="grey",linewidth=0.6,linestyle=":"); ax.axvline(0,color="grey",linewidth=0.6,linestyle=":")
    ax.grid(True,linestyle=":",linewidth=0.6); fig.tight_layout()
    return fig

def build_pca3d(Z3, color_vals):
    fig = go.Figure(data=[go.Scatter3d(x=Z3[:,0], y=Z3[:,1], z=Z3[:,2], mode="markers",
                                       marker=dict(size=4, color=color_vals, opacity=0.85))])
    fig.update_layout(title="PCA 3D — PC1·PC2·PC3 (sleep om te draaien)",
                      scene=dict(xaxis_title="PC1", yaxis_title="PC2", zaxis_title="PC3"),
                      margin=dict(l=10, r=10, t=40, b=10))
    return fig

def build_variance_plot(expl):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    xs = np.arange(1, len(expl)+1)
    ax.bar(xs, expl, width=0.8, align="center")
    ax.plot(xs, np.cumsum(expl), marker="o")
    ax.set_xticks(xs); ax.set_xlabel("Principal Component"); ax.set_ylabel("Explained variance ratio")
    ax.set_title("Uitlegvariantie per component (balken) + cumulatief (lijn)")
    ax.grid(True, linestyle=":", linewidth=0.6); fig.tight_layout()
    return fig

def build_hist_box(df: pd.DataFrame, color_key: str):
    series = df[color_key].dropna()
    label = FEATURE_LABELS.get(color_key, color_key)
    fig_hist = px.histogram(x=series, nbins=30, title=f"Histogram — {label}", labels={"x": label})
    fig_hist.update_layout(xaxis_title=label, yaxis_title="Aantal", margin=dict(l=10, r=10, t=40, b=10))
    fig_box = px.box(y=series, points="outliers", title=f"Boxplot — {label}", labels={"y": label})
    fig_box.update_layout(yaxis_title=label, margin=dict(l=10, r=10, t=40, b=10))
    return fig_hist, fig_box

# -------------------- Controllers --------------------
def controller(color_label="BMI (Body Mass Index)", n_components=10, standardize=True, arrow_scale=2.0):
    df = load_diabetes_df()
    feats, Xs, Z, loadings, expl = compute_pca(df, n_components, standardize)
    color_key = LABEL_TO_KEY.get(color_label, "bmi")
    color_vals = df[color_key].values

    fig_biplot = build_biplot_plotly(df, Z, loadings, feats, color_key, arrow_scale=arrow_scale)
    if Z.shape[1] < 3:
        pca3 = PCA(n_components=3); Z3 = pca3.fit_transform(Xs)
    else:
        Z3 = Z[:, :3]
    fig3d = build_pca3d(Z3, color_vals)
    fig_variance = build_variance_plot(expl)
    fig_hist, fig_box = build_hist_box(df, color_key)

    load_df = pd.DataFrame({
        "feature_key": feats,
        "PC1_loading": loadings[:, 0],
        "PC2_loading": loadings[:, 1],
        "PC1_abs": np.abs(loadings[:, 0]),
        "PC2_abs": np.abs(loadings[:, 1]),
    })
    load_df["Feature (PC1)"] = load_df["feature_key"].map(lambda k: FEATURE_LABELS.get(k, k))
    load_df["Feature (PC2)"] = load_df["feature_key"].map(lambda k: FEATURE_LABELS.get(k, k))
    top_pc1 = load_df.sort_values("PC1_abs", ascending=False)[["Feature (PC1)", "PC1_loading"]].head(6).reset_index(drop=True)
    top_pc2 = load_df.sort_values("PC2_abs", ascending=False)[["Feature (PC2)", "PC2_loading"]].head(6).reset_index(drop=True)
    max_len = max(len(top_pc1), len(top_pc2))
    top_pc1 = top_pc1.reindex(range(max_len)); top_pc2 = top_pc2.reindex(range(max_len))
    table = pd.concat([top_pc1, top_pc2], axis=1)

    overview_df, overview_note = compute_overview_table(df)

    summary_md = f"""
### Wat zie je hier?
- **Klik op _Update visualisaties_** om alles te verversen met jouw keuze.
- **Hover** over punten voor exacte waarden (BMI, bloeddruk, cholesterol, glucose, leeftijd, geslacht, etc.).
- **2D-biplot** met pijlen (belangrijkste metingen) en **3D-view** voor extra diepte.
- **Uitlegvariantieplot**: laat zien hoeveel variatie elke component uitlegt.
- **Histogram + boxplot**: verdeling en spreiding van de gekozen meting ({FEATURE_LABELS.get(color_key,color_key)}).
"""
    return fig_biplot, fig3d, fig_variance, table, overview_df, overview_note, summary_md

def animate_pca(color_label="BMI (Body Mass Index)", point_size=32, alpha=0.85, n_components=10, standardize=True, frames=40, pause=0.0):
    df = load_diabetes_df()
    feats, Xs, Z, loadings, expl = compute_pca(df, n_components, standardize)
    color_key = LABEL_TO_KEY.get(color_label, "bmi")
    color_vals = df[color_key].values
    for i in range(frames):
        t = i / max(1, frames-1)
        w1 = min(1.0, t * 2.0); w2 = max(0.0, (t - 0.5) * 2.0)
        coords = np.column_stack([Z[:, 0] * w1, Z[:, 1] * w2])
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.scatter(coords[:, 0], coords[:, 1], c=color_vals, s=point_size, alpha=alpha)
        ax.set_xlabel("PC1 (opbouw)"); ax.set_ylabel("PC2 (opbouw)")
        title = "PCA-projectie (animatie) — " + ("PC1 →" if w2 == 0 else "PC1 + PC2")
        ax.set_title(f"{title} — frame {i+1}/{frames}")
        ax.axhline(0, color="grey", linewidth=0.6, linestyle=":"); ax.axvline(0, color="grey", linewidth=0.6, linestyle=":")
        ax.grid(True, linestyle=":", linewidth=0.6); fig.tight_layout()
        yield fig
        if pause > 0:
            time.sleep(pause)

def export_biplot_png(color_label="BMI (Body Mass Index)", arrow_scale=2.0, point_size=32, alpha=0.85, n_components=10, standardize=True):
    df = load_diabetes_df()
    feats, Xs, Z, loadings, expl = compute_pca(df, n_components, standardize)
    color_key = LABEL_TO_KEY.get(color_label, "bmi")
    fig = build_biplot_matplotlib(df, Z, loadings, feats, color_key, arrow_scale=arrow_scale, point_size=point_size, alpha=alpha)
    path = f"/mnt/data/biplot_{int(time.time())}.png"
    fig.savefig(path, dpi=150, bbox_inches="tight"); plt.close(fig)
    return path

def export_variance_png(n_components=10, standardize=True):
    df = load_diabetes_df()
    feats, Xs, Z, loadings, expl = compute_pca(df, n_components, standardize)
    fig = build_variance_plot(expl)
    path = f"/mnt/data/variance_{int(time.time())}.png"
    fig.savefig(path, dpi=150, bbox_inches="tight"); plt.close(fig)
    return path

# -------------------- UI --------------------
with gr.Blocks(title="PCA Dashboard — Diabetes (netjes & compleet)") as demo:
    gr.HTML("""
    <style>
      .callout {padding:12px 14px; border-left:4px solid #2563eb; background:#f1f5f9; border-radius:8px; margin: 8px 0 18px;}
      .cta {padding:10px 12px; border:1px dashed #2563eb; background:#eff6ff; border-radius:8px; margin-top:6px;}
    </style>
    """)

    gr.Markdown("# PCA Dashboard — Diabetes (netjes & compleet)")
    gr.Markdown(MEDICAL_MD)
    gr.HTML('<div class="callout"><b>Belangrijk:</b> kies links je instellingen en klik daarna op <b>Update visualisaties</b>.     Wil je de stap-voor-stap projectie zien? Klik op <b>▶ Animate PCA</b>.</div>')

    with gr.Row():
        with gr.Column(scale=1):
            with gr.Group():
                gr.Markdown("### Instellingen")
                color_choices = [FEATURE_LABELS[k] for k in ["bmi","bp","s1","s2","s3","s4","s5","s6","age","sex","target"]]
                color_feat = gr.Dropdown(choices=color_choices, value=FEATURE_LABELS["bmi"], label="Kleur op meting")
                n_components = gr.Slider(3, 10, value=10, step=1, label="Aantal PCA-componenten")
                standardize = gr.Checkbox(value=True, label="Standaardiseer metingen (aanbevolen)")
                arrow_scale = gr.Slider(0.5, 5.0, value=2.0, step=0.1, label="Pijl-schaal (2D-biplot)")
                run_btn = gr.Button("🔄 Update visualisaties")
                gr.HTML('<div class="cta"><b>Klik hierna op: "🔄 Update visualisaties"</b> om alle grafieken te verversen.</div>')
            with gr.Group():
                gr.Markdown("### Animatie")
                animate_btn = gr.Button("▶ Animate PCA (PC1 → PC2)")
                gr.HTML('<div class="cta"><b>Klik op: "▶ Animate PCA"</b> om de projectie stap-voor-stap te zien.</div>')
                anim_plot = gr.Plot(label="Animatie van projectie")
            with gr.Group():
                gr.Markdown("### Downloads")
                dl_biplot = gr.DownloadButton("Download biplot (PNG)")
                dl_var = gr.DownloadButton("Download variatieplot (PNG)")

        with gr.Column(scale=2):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Biplot (2D, hover)")
                    plot_biplot = gr.Plotly()
                with gr.Column():
                    gr.Markdown("### 3D PCA (PC1–PC3)")
                    plot3d = gr.Plotly()
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Uitlegvariantie")
                    plot_expl = gr.Plot()
                with gr.Column():
                    gr.Markdown("### Top-features (PC1 / PC2)")
                    table = gr.Dataframe(headers=["Feature (PC1)", "Loading PC1", "Feature (PC2)", "Loading PC2"], row_count=6)
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Histogram")
                    plot_hist = gr.Plotly()
                with gr.Column():
                    gr.Markdown("### Boxplot")
                    plot_box = gr.Plotly()
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Overzicht (gemiddelden & verdeling)")
                    overview_tbl = gr.Dataframe(interactive=False)
                with gr.Column():
                    gr.Markdown("### Samenvatting")
                    summary = gr.Markdown()
                    overview_note_md = gr.Markdown()

    inputs = [color_feat, n_components, standardize, arrow_scale]
    run_btn.click(fn=controller, inputs=inputs,
                  outputs=[plot_biplot, plot3d, plot_expl, table, overview_tbl, overview_note_md, summary])
    demo.load(fn=controller, inputs=inputs,
              outputs=[plot_biplot, plot3d, plot_expl, table, overview_tbl, overview_note_md, summary])

    animate_btn.click(fn=animate_pca, inputs=[color_feat], outputs=anim_plot)

    dl_biplot.click(fn=export_biplot_png, inputs=[color_feat, arrow_scale], outputs=[dl_biplot])
    dl_var.click(fn=export_variance_png, inputs=[], outputs=[dl_var])

if __name__ == "__main__":
    demo.queue().launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False, show_api=False)