Model Evaluation
Model Evaluation
A process that systematically evaluates an AI model's performance, safety, bias, and more.
Model Evaluation
A process that systematically evaluates an AI model's performance, safety, bias, and more.
Model Evaluation is the process of systematically measuring and verifying an AI model's performance, safety, bias, robustness, and more. Article 9 of the EU AI Act requires testing and evaluation for high-risk AI systems as part of the risk management system, and Article 15 specifies requirements for accuracy, robustness, and cybersecurity.
Traditional ML model evaluation focused on performance metrics such as accuracy, precision, recall, and F1 score. In the era of AI regulation, however, fairness metrics, explainability, and robustness against adversarial attacks are essential parts of the evaluation.
An evaluation framework for EU AI Act compliance includes the following: technical performance testing, fairness analysis by protected group, safety verification through Red Team Testing, robustness testing under diverse conditions, and interpretability verification. These results are included in the technical documentation and serve as the basis for conformity assessment.
Evaluation is more complex for generative AI. It is difficult to quantify the quality of outputs, and new evaluation dimensions are needed, such as the potential to generate harmful content, the frequency of misinformation (hallucination), and the risk of copyright infringement. Benchmarks such as HELM, MMLU, and TruthfulQA are used.
# EU AI Act 준수를 위한 종합 모델 평가 프레임워크
from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, List, Callable
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
import numpy as np
@dataclass
class EvaluationResult:
"""평가 결과"""
metric_name: str
value: float
threshold: float
passed: bool
details: Dict = field(default_factory=dict)
class AIActModelEvaluator:
"""EU AI Act 준수를 위한 모델 평가 프레임워크"""
def __init__(self, model_name: str, model_version: str):
self.model_name = model_name
self.model_version = model_version
self.results: List[EvaluationResult] = []
def evaluate_performance(self, y_true: np.ndarray, y_pred: np.ndarray,
accuracy_threshold: float = 0.85) -> EvaluationResult:
"""제15조: 정확성 평가"""
accuracy = accuracy_score(y_true, y_pred)
precision, recall, f1, _ = precision_recall_fscore_support(
y_true, y_pred, average='weighted'
)
result = EvaluationResult(
metric_name="performance",
value=accuracy,
threshold=accuracy_threshold,
passed=accuracy >= accuracy_threshold,
details={
"accuracy": round(accuracy, 4),
"precision": round(precision, 4),
"recall": round(recall, 4),
"f1_score": round(f1, 4)
}
)
self.results.append(result)
return result
def evaluate_fairness(self, y_true: np.ndarray, y_pred: np.ndarray,
protected_attribute: np.ndarray,
disparity_threshold: float = 0.2) -> EvaluationResult:
"""공정성 평가 (보호 그룹 간 성능 격차)"""
groups = np.unique(protected_attribute)
group_metrics = {}
for group in groups:
mask = protected_attribute == group
if mask.sum() > 0:
group_acc = accuracy_score(y_true[mask], y_pred[mask])
group_metrics[str(group)] = round(group_acc, 4)
# 그룹 간 최대 격차
if len(group_metrics) >= 2:
max_disparity = max(group_metrics.values()) - min(group_metrics.values())
else:
max_disparity = 0
result = EvaluationResult(
metric_name="fairness",
value=max_disparity,
threshold=disparity_threshold,
passed=max_disparity <= disparity_threshold,
details={
"group_accuracy": group_metrics,
"max_disparity": round(max_disparity, 4),
"disparate_impact_ratio": round(
min(group_metrics.values()) / max(group_metrics.values()), 4
) if max(group_metrics.values()) > 0 else 1.0
}
)
self.results.append(result)
return result
def evaluate_robustness(self, model_fn: Callable,
test_inputs: np.ndarray,
noise_level: float = 0.1,
stability_threshold: float = 0.9) -> EvaluationResult:
"""제15조: 견고성 평가 (노이즈에 대한 안정성)"""
original_outputs = model_fn(test_inputs)
# 노이즈 추가
noise = np.random.normal(0, noise_level, test_inputs.shape)
noisy_inputs = test_inputs + noise
noisy_outputs = model_fn(noisy_inputs)
# 출력 일관성 측정
if hasattr(original_outputs, 'shape') and len(original_outputs.shape) > 1:
# 분류 모델: 예측 클래스 일치율
stability = np.mean(
np.argmax(original_outputs, axis=1) == np.argmax(noisy_outputs, axis=1)
)
else:
# 회귀 모델: 출력 변화율
stability = 1 - np.mean(np.abs(original_outputs - noisy_outputs) /
(np.abs(original_outputs) + 1e-10))
result = EvaluationResult(
metric_name="robustness",
value=stability,
threshold=stability_threshold,
passed=stability >= stability_threshold,
details={
"noise_level": noise_level,
"prediction_stability": round(stability, 4)
}
)
self.results.append(result)
return result
def evaluate_explainability(self, model_has_explanations: bool,
explanation_coverage: float) -> EvaluationResult:
"""설명 가능성 평가"""
result = EvaluationResult(
metric_name="explainability",
value=explanation_coverage if model_has_explanations else 0,
threshold=0.8,
passed=model_has_explanations and explanation_coverage >= 0.8,
details={
"has_explanation_capability": model_has_explanations,
"explanation_coverage": explanation_coverage,
"methods_available": ["SHAP", "LIME", "Feature Importance"]
}
)
self.results.append(result)
return result
def generate_technical_documentation(self) -> Dict:
"""EU AI Act 기술 문서용 평가 보고서"""
passed_all = all(r.passed for r in self.results)
return {
"document_type": "EU_AI_Act_Technical_Documentation_Annex_IV",
"model_info": {
"name": self.model_name,
"version": self.model_version,
"evaluation_date": datetime.now().isoformat()
},
"evaluation_summary": {
"total_tests": len(self.results),
"passed": sum(1 for r in self.results if r.passed),
"failed": sum(1 for r in self.results if not r.passed),
"overall_compliance": passed_all
},
"detailed_results": [
{
"metric": r.metric_name,
"value": r.value,
"threshold": r.threshold,
"passed": r.passed,
"details": r.details
} for r in self.results
],
"recommendations": self._generate_recommendations()
}
def _generate_recommendations(self) -> List[str]:
"""개선 권고사항"""
recommendations = []
for r in self.results:
if not r.passed:
if r.metric_name == "fairness":
recommendations.append(
"공정성 기준 미달: 보호 그룹별 재학습 또는 편향 완화 기법 적용 필요"
)
elif r.metric_name == "robustness":
recommendations.append(
"견고성 기준 미달: 적대적 학습 또는 데이터 증강 검토"
)
return recommendations
# 사용 예시
evaluator = AIActModelEvaluator("CreditScoreModel", "v2.1.0")
# 가상 데이터
y_true = np.array([1, 0, 1, 1, 0, 1, 0, 0, 1, 1])
y_pred = np.array([1, 0, 1, 0, 0, 1, 1, 0, 1, 1])
protected = np.array(['M', 'F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'F'])
evaluator.evaluate_performance(y_true, y_pred)
evaluator.evaluate_fairness(y_true, y_pred, protected)
evaluator.evaluate_explainability(True, 0.85)
report = evaluator.generate_technical_documentation()
print(f"전체 준수 여부: {report['evaluation_summary']['overall_compliance']}")
PM: We need to upgrade our model evaluation framework to meet the EU AI Act. What are we currently missing?
ML Engineer: We only evaluate based on accuracy. We don't do any fairness or robustness evaluation.
Senior: Article 15 requires accuracy, robustness, and cybersecurity all together. Fairness evaluation is also essential under the principle of non-discrimination. The evaluation framework needs a complete overhaul.
Interviewer: What is the most important element in model evaluation for EU AI Act compliance?
Candidate: You need to evaluate comprehensively, not just performance but also fairness, robustness, and explainability. In particular, you should measure model performance gaps across protected attributes (gender, race, age, etc.) and test stability against adversarial inputs. Since evaluation results must be included in the technical documentation, it is also important to record them in a reproducible and auditable form.
Senior: The model evaluation code only measures accuracy.
Junior: Do we need to add other metrics too?
Senior: Yes, add a fairness_metrics function to measure performance gaps across protected groups. We also need robustness_test. Save the results as JSON so they can be included in the technical documentation.
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free