File size: 4,714 Bytes
25dfeb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from pathlib import Path

import joblib
import pandas as pd
import sklearn

from datasets import load_dataset
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    accuracy_score,
    classification_report,
    confusion_matrix,
)
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder


DATASET_ID = "aigovdev/ai-governance-scenarios"

MODEL_PATH = Path("artifacts/model.joblib")
METRICS_PATH = Path("artifacts/metrics.json")


FEATURES = [
    "sector",
    "impact",
    "decision_autonomy",
    "human_oversight",
    "monitoring",
    "traceability",
    "technical_documentation",
]


def map_risk(label: str) -> str:
    if label in {"low", "limited"}:
        return "lower"
    if label == "high":
        return "high"
    if label == "unacceptable":
        return "unacceptable"

    raise ValueError(f"Unexpected governance_risk label: {label}")


def build_pipeline() -> Pipeline:
    preprocessor = ColumnTransformer(
        transformers=[
            (
                "categorical",
                OneHotEncoder(
                    handle_unknown="ignore",
                ),
                FEATURES,
            )
        ],
        remainder="drop",
    )

    classifier = LogisticRegression(
        max_iter=2000,
        class_weight="balanced",
        random_state=42,
    )

    return Pipeline(
        [
            ("preprocessor", preprocessor),
            ("classifier", classifier),
        ]
    )


def main():
    MODEL_PATH.parent.mkdir(parents=True, exist_ok=True)

    dataset = load_dataset(
        DATASET_ID,
        split="train",
    )

    df = dataset.to_pandas()

    df["risk_tier"] = df["governance_risk"].map(map_risk)

    X = df[FEATURES].copy()
    y = df["risk_tier"].copy()

    print("Dataset:", DATASET_ID)
    print("Examples:", len(df))
    print()
    print("Target distribution:")
    print(y.value_counts().sort_index())
    print()

    cv = StratifiedKFold(
        n_splits=3,
        shuffle=True,
        random_state=42,
    )

    pipeline = build_pipeline()

    predictions = cross_val_predict(
        pipeline,
        X,
        y,
        cv=cv,
    )

    labels = [
        "lower",
        "high",
        "unacceptable",
    ]

    accuracy = accuracy_score(
        y,
        predictions,
    )

    report = classification_report(
        y,
        predictions,
        labels=labels,
        output_dict=True,
        zero_division=0,
    )

    matrix = confusion_matrix(
        y,
        predictions,
        labels=labels,
    )

    print("Stratified 3-Fold Cross-Validation")
    print("=" * 42)

    print(
        classification_report(
            y,
            predictions,
            labels=labels,
            digits=3,
            zero_division=0,
        )
    )

    print("Confusion matrix")
    print("Labels:", labels)
    print(matrix)
    print()

    pipeline.fit(
        X,
        y,
    )

    joblib.dump(
        pipeline,
        MODEL_PATH,
    )

    metrics = {
        "dataset": DATASET_ID,
        "examples": int(len(df)),
        "target_distribution": {
            key: int(value)
            for key, value in y.value_counts().to_dict().items()
        },
        "evaluation": {
            "method": "stratified_3_fold_cross_validation",
            "accuracy": float(accuracy),
            "macro_precision": float(
                report["macro avg"]["precision"]
            ),
            "macro_recall": float(
                report["macro avg"]["recall"]
            ),
            "macro_f1": float(
                report["macro avg"]["f1-score"]
            ),
            "confusion_matrix_labels": labels,
            "confusion_matrix": matrix.tolist(),
        },
        "features": FEATURES,
        "risk_mapping": {
            "low": "lower",
            "limited": "lower",
            "high": "high",
            "unacceptable": "unacceptable",
        },
        "runtime": {
            "scikit_learn": sklearn.__version__,
        },
        "limitations": [
            "Dataset contains only 12 synthetic scenarios.",
            "Evaluation is illustrative and not a production benchmark.",
            "Risk tiers are engineering labels, not legal classifications.",
        ],
    }

    METRICS_PATH.write_text(
        json.dumps(
            metrics,
            indent=2,
        ),
        encoding="utf-8",
    )

    print("Saved model:", MODEL_PATH.resolve())
    print("Saved metrics:", METRICS_PATH.resolve())


if __name__ == "__main__":
    main()