File size: 9,535 Bytes
c4bc613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4b1c85
edf6c00
c4bc613
 
edf6c00
 
d4b1c85
 
 
3c53f52
c4bc613
d4b1c85
c4bc613
6408d4a
2967f48
d4b1c85
 
 
 
 
 
c4bc613
2967f48
c4bc613
d4b1c85
c4bc613
 
 
3c53f52
30f7c21
6408d4a
 
30f7c21
6408d4a
 
 
 
3c53f52
c4bc613
2967f48
 
 
 
 
 
 
 
30f7c21
c4bc613
 
d4b1c85
c4bc613
2967f48
c4bc613
2967f48
 
c4bc613
2967f48
 
edf6c00
2967f48
 
 
 
 
 
 
 
 
c4bc613
2967f48
 
 
 
 
 
 
 
 
 
 
6408d4a
3c53f52
93dc17b
2967f48
 
 
93dc17b
c4bc613
 
d4b1c85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4bc613
6408d4a
c4bc613
d4b1c85
 
c4bc613
6408d4a
4cf8172
edf6c00
c4bc613
6408d4a
 
c4bc613
6408d4a
 
c4bc613
2967f48
 
 
c4bc613
d4b1c85
 
 
 
edf6c00
 
 
 
 
 
d4b1c85
 
edf6c00
 
 
d4b1c85
 
 
edf6c00
 
 
 
 
 
 
d4b1c85
edf6c00
d4b1c85
 
 
 
edf6c00
 
d4b1c85
 
edf6c00
 
d4b1c85
edf6c00
d4b1c85
 
 
 
edf6c00
d4b1c85
 
 
 
 
 
edf6c00
 
 
 
d4b1c85
edf6c00
d4b1c85
 
 
 
edf6c00
 
d4b1c85
 
 
 
 
 
edf6c00
 
c4bc613
edf6c00
c4bc613
edf6c00
3c53f52
edf6c00
 
30f7c21
d4b1c85
edf6c00
d4b1c85
 
 
 
edf6c00
30f7c21
d4b1c85
 
 
 
 
 
 
 
edf6c00
d4b1c85
 
 
 
 
edf6c00
3c53f52
 
 
2967f48
3c53f52
2967f48
3c53f52
d4b1c85
3c53f52
2967f48
 
 
d4b1c85
 
2967f48
edf6c00
2967f48
 
 
 
 
 
3c53f52
 
 
 
 
d4b1c85
3c53f52
d4b1c85
3c53f52
edf6c00
d4b1c85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c53f52
d4b1c85
3c53f52
d4b1c85
 
 
3c53f52
d4b1c85
 
3c53f52
d4b1c85
 
 
 
 
3c53f52
edf6c00
c4bc613
2967f48
 
d4b1c85
2967f48
edf6c00
2967f48
d4b1c85
2967f48
d4b1c85
2967f48
 
c4bc613
93dc17b
c4bc613
93dc17b
c4bc613
d4b1c85
c4bc613
3c53f52
c4bc613
d4b1c85
c4bc613
6408d4a
 
c4bc613
d4b1c85
d886a54
edf6c00
c4bc613
6408d4a
c4bc613
d4b1c85
 
 
2967f48
d4b1c85
3c53f52
2967f48
 
3c53f52
d4b1c85
3c53f52
 
d4b1c85
 
c4bc613
d4b1c85
 
c4bc613
d4b1c85
3c53f52
d4b1c85
3c53f52
d886a54
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import gradio as gr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder

from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier

from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score,
    confusion_matrix
)

from imblearn.over_sampling import SMOTE

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet

# =========================
# GLOBALS
# =========================
df_global = None
best_model_name = None
best_model_obj = None

no_global = None
cw_global = None
smote_global = None
cm_global = None


# =========================
# UPLOAD
# =========================
def upload_and_clean(file):

    global df_global

    df = pd.read_csv(file.name)
    df = df.drop_duplicates()

    for col in df.columns:
        if pd.api.types.is_numeric_dtype(df[col]):
            df[col] = df[col].fillna(df[col].median())
        else:
            df[col] = df[col].fillna(df[col].mode()[0])

    df_global = df

    return (
        "Data Loaded Successfully",
        df.head(),
        gr.update(choices=list(df.columns)),
        gr.update(choices=list(df.columns))
    )


# =========================
# ANALYSIS VISUALIZATION
# =========================
def analyze_data(target):

    df = df_global.copy()
    images = []

    cols = [c for c in df.columns if c != target]

    for col in cols[:6]:

        fig, axes = plt.subplots(1, 2, figsize=(12, 4))

        df[col].astype(str).value_counts().head(10).plot(
            kind="bar",
            ax=axes[0]
        )
        axes[0].set_title(f"Bar - {col}")
        axes[0].tick_params(axis='x', rotation=45)

        df[col].astype(str).value_counts().head(6).plot(
            kind="pie",
            ax=axes[1],
            autopct="%1.1f%%"
        )
        axes[1].set_title(f"Pie - {col}")
        axes[1].set_ylabel("")

        plt.tight_layout()

        path = f"/tmp/{col}.png"
        plt.savefig(path)
        plt.close()

        images.append(path)

    return images


# =========================
# CONFUSION MATRIX
# =========================
def plot_cm(y_true, y_pred, title):

    cm = confusion_matrix(y_true, y_pred)

    plt.figure(figsize=(4,4))
    plt.imshow(cm, cmap="Blues")

    plt.title(title)

    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            plt.text(j, i, cm[i, j], ha="center", va="center")

    path = f"/tmp/{title}.png"
    plt.savefig(path)
    plt.close()

    return path


# =========================
# ML (NO / CW / SMOTE)
# =========================
def run_ml(target):

    global df_global, best_model_name
    global no_global, cw_global, smote_global, cm_global

    df = df_global.copy()

    # encode
    for col in df.columns:
        if not pd.api.types.is_numeric_dtype(df[col]):
            df[col] = LabelEncoder().fit_transform(df[col].astype(str))

    X = df.drop(columns=[target])
    y = df[target]

    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=42
    )

    # imbalance check
    counts = np.bincount(y)
    imbalance = min(counts) / max(counts) < 0.5

    models = {
        "Decision Tree": DecisionTreeClassifier(),
        "Random Forest": RandomForestClassifier(),
        "XGBoost": XGBClassifier(eval_metric="logloss")
    }

    no_rows, cw_rows, smote_rows = [], [], []
    cm_images = {}

    best_score = 0

    # =========================
    # NO SAMPLING
    # =========================
    for name, model in models.items():

        model.fit(X_train, y_train)
        pred = model.predict(X_test)

        acc = accuracy_score(y_test, pred)

        no_rows.append({
            "Model": name,
            "Accuracy": acc,
            "Precision": precision_score(y_test, pred, average="weighted", zero_division=0),
            "Recall": recall_score(y_test, pred, average="weighted", zero_division=0),
            "F1": f1_score(y_test, pred, average="weighted", zero_division=0)
        })

        cm_images[f"{name}_no"] = plot_cm(y_test, pred, f"{name}_NO")

        if acc > best_score:
            best_score = acc
            best_model_name = name + " (No)"

    # =========================
    # CLASS WEIGHT
    # =========================
    for name in models.keys():

        if name == "Decision Tree":
            model = DecisionTreeClassifier(class_weight="balanced")
        elif name == "Random Forest":
            model = RandomForestClassifier(class_weight="balanced")
        else:
            model = XGBClassifier(eval_metric="logloss")

        model.fit(X_train, y_train)
        pred = model.predict(X_test)

        cw_rows.append({
            "Model": name,
            "Accuracy": accuracy_score(y_test, pred),
            "Precision": precision_score(y_test, pred, average="weighted", zero_division=0),
            "Recall": recall_score(y_test, pred, average="weighted", zero_division=0),
            "F1": f1_score(y_test, pred, average="weighted", zero_division=0)
        })

        cm_images[f"{name}_cw"] = plot_cm(y_test, pred, f"{name}_CW")

    # =========================
    # SMOTE
    # =========================
    if imbalance:
        sm = SMOTE(random_state=42)
        X_res, y_res = sm.fit_resample(X_train, y_train)
    else:
        X_res, y_res = X_train, y_train

    for name, model in models.items():

        model.fit(X_res, y_res)
        pred = model.predict(X_test)

        smote_rows.append({
            "Model": name,
            "Accuracy": accuracy_score(y_test, pred),
            "Precision": precision_score(y_test, pred, average="weighted", zero_division=0),
            "Recall": recall_score(y_test, pred, average="weighted", zero_division=0),
            "F1": f1_score(y_test, pred, average="weighted", zero_division=0)
        })

        cm_images[f"{name}_smote"] = plot_cm(y_test, pred, f"{name}_SMOTE")

    # store globally
    no_global = pd.DataFrame(no_rows)
    cw_global = pd.DataFrame(cw_rows)
    smote_global = pd.DataFrame(smote_rows)
    cm_global = cm_images

    return (
        f"Imbalance: {imbalance}",
        no_global,
        cw_global,
        smote_global,
        list(cm_images.values())
    )


# =========================
# FEATURE IMPORTANCE
# =========================
def feature_importance():

    global best_model_obj

    if hasattr(best_model_obj, "feature_importances_"):

        plt.figure(figsize=(6,4))
        plt.barh(range(len(best_model_obj.feature_importances_)),
                 best_model_obj.feature_importances_)

        path = "/tmp/feat.png"
        plt.savefig(path)
        plt.close()

        return path

    return None


# =========================
# PDF REPORT
# =========================
def generate_pdf():

    global no_global, cw_global, smote_global, cm_global, best_model_name

    path = "/tmp/report.pdf"
    doc = SimpleDocTemplate(path)
    styles = getSampleStyleSheet()
    elements = []

    elements.append(Paragraph("AutoML Full Report", styles["Title"]))
    elements.append(Spacer(1, 10))
    elements.append(Paragraph(f"Best Model: {best_model_name}", styles["Heading2"]))

    def add_table(df, title):
        elements.append(Spacer(1, 10))
        elements.append(Paragraph(title, styles["Heading3"]))

        data = [df.columns.tolist()] + df.values.tolist()

        table = Table(data)
        table.setStyle(TableStyle([
            ("BACKGROUND", (0,0), (-1,0), colors.grey),
            ("TEXTCOLOR", (0,0), (-1,0), colors.white),
            ("GRID", (0,0), (-1,-1), 0.5, colors.black)
        ]))

        elements.append(table)

    add_table(no_global, "No Sampling")
    add_table(cw_global, "Class Weight")
    add_table(smote_global, "SMOTE")

    elements.append(Spacer(1, 10))
    elements.append(Paragraph("Confusion Matrices", styles["Heading2"]))

    for name, img in cm_global.items():
        elements.append(Paragraph(name, styles["Normal"]))
        elements.append(Image(img, width=200, height=200))

    doc.build(elements)

    return path


# =========================
# ANALYSIS
# =========================
def full_analysis(target):

    ml_status, no_df, cw_df, smote_df, imgs = run_ml(target)

    return ml_status, no_df, cw_df, smote_df, imgs


# =========================
# UI
# =========================
with gr.Blocks() as demo:

    gr.Markdown("# 🚀 Advanced AutoML System")

    file = gr.File()

    upload_btn = gr.Button("Upload")

    status = gr.Textbox()
    preview = gr.Dataframe()

    target = gr.Dropdown(label="Target")

    run_btn = gr.Button("Run Full Analysis")

    ml_status = gr.Textbox()

    no_table = gr.Dataframe()
    cw_table = gr.Dataframe()
    smote_table = gr.Dataframe()

    gallery = gr.Gallery(columns=2)

    feat_btn = gr.Button("Feature Importance")
    feat_img = gr.Image()

    pdf_btn = gr.Button("Download PDF")
    pdf_file = gr.File()

    upload_btn.click(upload_and_clean, file,
                      [status, preview, target, target])

    run_btn.click(full_analysis, target,
                  [ml_status, no_table, cw_table, smote_table, gallery])

    feat_btn.click(feature_importance, None, feat_img)

    pdf_btn.click(generate_pdf, None, pdf_file)

demo.launch(share=True)