validmind 2.5.1__py3-none-any.whl → 2.5.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- validmind/__version__.py +1 -1
- validmind/client.py +6 -0
- validmind/tests/__types__.py +0 -1
- validmind/tests/model_validation/ragas/AnswerCorrectness.py +1 -1
- validmind/tests/model_validation/ragas/AnswerRelevance.py +1 -1
- validmind/tests/model_validation/ragas/AnswerSimilarity.py +1 -1
- validmind/tests/model_validation/ragas/AspectCritique.py +1 -1
- validmind/tests/model_validation/ragas/ContextEntityRecall.py +1 -1
- validmind/tests/model_validation/ragas/ContextPrecision.py +1 -1
- validmind/tests/model_validation/ragas/ContextRecall.py +1 -1
- validmind/tests/model_validation/ragas/Faithfulness.py +1 -1
- validmind/tests/model_validation/sklearn/OverfitDiagnosis.py +17 -36
- validmind/tests/model_validation/sklearn/RobustnessDiagnosis.py +312 -261
- validmind/tests/run.py +1 -1
- validmind/vm_models/dataset/utils.py +9 -2
- validmind/vm_models/model.py +12 -1
- {validmind-2.5.1.dist-info → validmind-2.5.6.dist-info}/METADATA +2 -2
- {validmind-2.5.1.dist-info → validmind-2.5.6.dist-info}/RECORD +21 -22
- validmind/tests/model_validation/ragas/ContextRelevancy.py +0 -119
- {validmind-2.5.1.dist-info → validmind-2.5.6.dist-info}/LICENSE +0 -0
- {validmind-2.5.1.dist-info → validmind-2.5.6.dist-info}/WHEEL +0 -0
- {validmind-2.5.1.dist-info → validmind-2.5.6.dist-info}/entry_points.txt +0 -0
validmind/__version__.py
CHANGED
@@ -1 +1 @@
|
|
1
|
-
__version__ = "2.5.
|
1
|
+
__version__ = "2.5.6"
|
validmind/client.py
CHANGED
@@ -240,6 +240,11 @@ def init_model(
|
|
240
240
|
vm_model = class_obj(
|
241
241
|
pipeline=model,
|
242
242
|
input_id=input_id,
|
243
|
+
attributes=(
|
244
|
+
ModelAttributes.from_dict(attributes)
|
245
|
+
if attributes
|
246
|
+
else ModelAttributes()
|
247
|
+
),
|
243
248
|
)
|
244
249
|
# TODO: Add metadata for pipeline model
|
245
250
|
metadata = get_model_info(vm_model)
|
@@ -248,6 +253,7 @@ def init_model(
|
|
248
253
|
input_id=input_id,
|
249
254
|
model=model, # Trained model instance
|
250
255
|
predict_fn=predict_fn,
|
256
|
+
attributes=ModelAttributes.from_dict(attributes) if attributes else None,
|
251
257
|
**kwargs,
|
252
258
|
)
|
253
259
|
metadata = get_model_info(vm_model)
|
validmind/tests/__types__.py
CHANGED
@@ -56,7 +56,6 @@ TestID = Literal[
|
|
56
56
|
"validmind.model_validation.ragas.AnswerSimilarity",
|
57
57
|
"validmind.model_validation.ragas.AnswerCorrectness",
|
58
58
|
"validmind.model_validation.ragas.ContextRecall",
|
59
|
-
"validmind.model_validation.ragas.ContextRelevancy",
|
60
59
|
"validmind.model_validation.ragas.ContextPrecision",
|
61
60
|
"validmind.model_validation.ragas.AnswerRelevance",
|
62
61
|
"validmind.model_validation.sklearn.RegressionModelsPerformanceComparison",
|
@@ -105,7 +105,7 @@ def AnswerCorrectness(
|
|
105
105
|
"ground_truth": ground_truth_column,
|
106
106
|
}
|
107
107
|
|
108
|
-
df = get_renamed_columns(dataset.
|
108
|
+
df = get_renamed_columns(dataset._df, required_columns)
|
109
109
|
|
110
110
|
result_df = evaluate(
|
111
111
|
Dataset.from_pandas(df), metrics=[answer_correctness], **get_ragas_config()
|
@@ -109,7 +109,7 @@ def AnswerRelevance(
|
|
109
109
|
"contexts": contexts_column,
|
110
110
|
}
|
111
111
|
|
112
|
-
df = get_renamed_columns(dataset.
|
112
|
+
df = get_renamed_columns(dataset._df, required_columns)
|
113
113
|
|
114
114
|
result_df = evaluate(
|
115
115
|
Dataset.from_pandas(df), metrics=[answer_relevancy], **get_ragas_config()
|
@@ -94,7 +94,7 @@ def AnswerSimilarity(
|
|
94
94
|
"ground_truth": ground_truth_column,
|
95
95
|
}
|
96
96
|
|
97
|
-
df = get_renamed_columns(dataset.
|
97
|
+
df = get_renamed_columns(dataset._df, required_columns)
|
98
98
|
|
99
99
|
result_df = evaluate(
|
100
100
|
Dataset.from_pandas(df), metrics=[answer_similarity], **get_ragas_config()
|
@@ -132,7 +132,7 @@ def AspectCritique(
|
|
132
132
|
"contexts": contexts_column,
|
133
133
|
}
|
134
134
|
|
135
|
-
df = get_renamed_columns(dataset.
|
135
|
+
df = get_renamed_columns(dataset._df, required_columns)
|
136
136
|
|
137
137
|
built_in_aspects = [aspect_map[aspect] for aspect in aspects]
|
138
138
|
custom_aspects = (
|
@@ -100,7 +100,7 @@ def ContextEntityRecall(
|
|
100
100
|
"contexts": contexts_column,
|
101
101
|
}
|
102
102
|
|
103
|
-
df = get_renamed_columns(dataset.
|
103
|
+
df = get_renamed_columns(dataset._df, required_columns)
|
104
104
|
|
105
105
|
result_df = evaluate(
|
106
106
|
Dataset.from_pandas(df), metrics=[context_entity_recall], **get_ragas_config()
|
@@ -96,7 +96,7 @@ def ContextPrecision(
|
|
96
96
|
"ground_truth": ground_truth_column,
|
97
97
|
}
|
98
98
|
|
99
|
-
df = get_renamed_columns(dataset.
|
99
|
+
df = get_renamed_columns(dataset._df, required_columns)
|
100
100
|
|
101
101
|
result_df = evaluate(
|
102
102
|
Dataset.from_pandas(df), metrics=[context_precision], **get_ragas_config()
|
@@ -96,7 +96,7 @@ def ContextRecall(
|
|
96
96
|
"ground_truth": ground_truth_column,
|
97
97
|
}
|
98
98
|
|
99
|
-
df = get_renamed_columns(dataset.
|
99
|
+
df = get_renamed_columns(dataset._df, required_columns)
|
100
100
|
|
101
101
|
result_df = evaluate(
|
102
102
|
Dataset.from_pandas(df), metrics=[context_recall], **get_ragas_config()
|
@@ -94,7 +94,7 @@ def Faithfulness(
|
|
94
94
|
"contexts": contexts_column,
|
95
95
|
}
|
96
96
|
|
97
|
-
df = get_renamed_columns(dataset.
|
97
|
+
df = get_renamed_columns(dataset._df, required_columns)
|
98
98
|
|
99
99
|
result_df = evaluate(
|
100
100
|
Dataset.from_pandas(df), metrics=[faithfulness], **get_ragas_config()
|
@@ -25,51 +25,48 @@ from validmind.vm_models import (
|
|
25
25
|
|
26
26
|
logger = get_logger(__name__)
|
27
27
|
|
28
|
+
# TODO: A couple of improvements here could be to:
|
29
|
+
# 1. Allow the test to use multiple metrics at once
|
30
|
+
# 2. Allow custom functions for computing performance
|
31
|
+
|
28
32
|
DEFAULT_THRESHOLD = 0.04
|
33
|
+
DEFAULT_CLASSIFICATION_METRIC = "auc"
|
34
|
+
DEFAULT_REGRESSION_METRIC = "mse"
|
29
35
|
PERFORMANCE_METRICS = {
|
30
36
|
"accuracy": {
|
31
37
|
"function": metrics.accuracy_score,
|
32
|
-
"is_classification": True,
|
33
38
|
"is_lower_better": False,
|
34
39
|
},
|
35
40
|
"auc": {
|
36
41
|
"function": metrics.roc_auc_score,
|
37
|
-
"is_classification": True,
|
38
42
|
"is_lower_better": False,
|
39
43
|
},
|
40
44
|
"f1": {
|
41
45
|
"function": metrics.f1_score,
|
42
|
-
"is_classification": True,
|
43
46
|
"is_lower_better": False,
|
44
47
|
},
|
45
48
|
"precision": {
|
46
49
|
"function": metrics.precision_score,
|
47
|
-
"is_classification": True,
|
48
50
|
"is_lower_better": False,
|
49
51
|
},
|
50
52
|
"recall": {
|
51
53
|
"function": metrics.recall_score,
|
52
|
-
"is_classification": True,
|
53
54
|
"is_lower_better": False,
|
54
55
|
},
|
55
56
|
"mse": {
|
56
57
|
"function": metrics.mean_squared_error,
|
57
|
-
"is_classification": False,
|
58
58
|
"is_lower_better": True,
|
59
59
|
},
|
60
60
|
"mae": {
|
61
61
|
"function": metrics.mean_absolute_error,
|
62
|
-
"is_classification": False,
|
63
62
|
"is_lower_better": True,
|
64
63
|
},
|
65
64
|
"r2": {
|
66
65
|
"function": metrics.r2_score,
|
67
|
-
"is_classification": False,
|
68
66
|
"is_lower_better": False,
|
69
67
|
},
|
70
68
|
"mape": {
|
71
69
|
"function": metrics.mean_absolute_percentage_error,
|
72
|
-
"is_classification": False,
|
73
70
|
"is_lower_better": True,
|
74
71
|
},
|
75
72
|
}
|
@@ -123,20 +120,13 @@ def _compute_metrics(
|
|
123
120
|
if is_classification and metric == "auc":
|
124
121
|
# if only one class is present in the data, return 0
|
125
122
|
if len(np.unique(y_true)) == 1:
|
126
|
-
results[metric].append(0)
|
127
|
-
return
|
128
|
-
|
129
|
-
score = metric_func(y_true, df_region[prob_column].values)
|
130
|
-
|
131
|
-
# All other classification metrics
|
132
|
-
elif is_classification:
|
133
|
-
score = metric_func(y_true, df_region[pred_column].values)
|
123
|
+
return results[metric].append(0)
|
134
124
|
|
135
|
-
|
136
|
-
|
137
|
-
|
125
|
+
return results[metric].append(
|
126
|
+
metric_func(y_true, df_region[prob_column].values)
|
127
|
+
)
|
138
128
|
|
139
|
-
results[metric].append(
|
129
|
+
return results[metric].append(metric_func(y_true, df_region[pred_column].values))
|
140
130
|
|
141
131
|
|
142
132
|
def _plot_overfit_regions(
|
@@ -219,8 +209,12 @@ def overfit_diagnosis( # noqa: C901
|
|
219
209
|
is_classification = bool(datasets[0].probability_column(model))
|
220
210
|
|
221
211
|
# Set default metric if not provided
|
222
|
-
if metric
|
223
|
-
metric =
|
212
|
+
if not metric:
|
213
|
+
metric = (
|
214
|
+
DEFAULT_CLASSIFICATION_METRIC
|
215
|
+
if is_classification
|
216
|
+
else DEFAULT_REGRESSION_METRIC
|
217
|
+
)
|
224
218
|
logger.info(
|
225
219
|
f"Using default {'classification' if is_classification else 'regression'} metric: {metric}"
|
226
220
|
)
|
@@ -228,19 +222,6 @@ def overfit_diagnosis( # noqa: C901
|
|
228
222
|
if id(cut_off_threshold) == id(DEFAULT_THRESHOLD):
|
229
223
|
logger.info("Using default cut-off threshold of 0.04")
|
230
224
|
|
231
|
-
metric = metric.lower()
|
232
|
-
try:
|
233
|
-
_metric = PERFORMANCE_METRICS[metric.lower()]
|
234
|
-
except KeyError:
|
235
|
-
raise ValueError(
|
236
|
-
f"Invalid metric. Choose from: {', '.join(PERFORMANCE_METRICS.keys())}"
|
237
|
-
)
|
238
|
-
|
239
|
-
if is_classification and not _metric["is_classification"]:
|
240
|
-
raise ValueError(f"Cannot use regression metric ({metric}) for classification.")
|
241
|
-
elif not is_classification and _metric["is_classification"]:
|
242
|
-
raise ValueError(f"Cannot use classification metric ({metric}) for regression.")
|
243
|
-
|
244
225
|
train_df = datasets[0].df
|
245
226
|
test_df = datasets[1].df
|
246
227
|
|
@@ -2,6 +2,7 @@
|
|
2
2
|
# See the LICENSE file in the root of this repository for details.
|
3
3
|
# SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial
|
4
4
|
|
5
|
+
from collections import defaultdict
|
5
6
|
from dataclasses import dataclass
|
6
7
|
from operator import add
|
7
8
|
from typing import List, Tuple
|
@@ -13,6 +14,7 @@ import seaborn as sns
|
|
13
14
|
from sklearn import metrics
|
14
15
|
|
15
16
|
from validmind.errors import MissingOrInvalidModelPredictFnError
|
17
|
+
from validmind.logging import get_logger
|
16
18
|
from validmind.vm_models import (
|
17
19
|
Figure,
|
18
20
|
ResultSummary,
|
@@ -20,291 +22,348 @@ from validmind.vm_models import (
|
|
20
22
|
ResultTableMetadata,
|
21
23
|
ThresholdTest,
|
22
24
|
ThresholdTestResult,
|
25
|
+
VMDataset,
|
26
|
+
VMModel,
|
23
27
|
)
|
24
28
|
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
+
logger = get_logger(__name__)
|
30
|
+
|
31
|
+
DEFAULT_DECAY_THRESHOLD = 0.05
|
32
|
+
DEFAULT_STD_DEV_LIST = [0.1, 0.2, 0.3, 0.4, 0.5]
|
33
|
+
DEFAULT_CLASSIFICATION_METRIC = "auc"
|
34
|
+
DEFAULT_REGRESSION_METRIC = "mse"
|
35
|
+
PERFORMANCE_METRICS = {
|
36
|
+
"accuracy": {
|
37
|
+
"function": metrics.accuracy_score,
|
38
|
+
"is_lower_better": False,
|
39
|
+
},
|
40
|
+
"auc": {
|
41
|
+
"function": metrics.roc_auc_score,
|
42
|
+
"is_lower_better": False,
|
43
|
+
},
|
44
|
+
"f1": {
|
45
|
+
"function": metrics.f1_score,
|
46
|
+
"is_lower_better": False,
|
47
|
+
},
|
48
|
+
"precision": {
|
49
|
+
"function": metrics.precision_score,
|
50
|
+
"is_lower_better": False,
|
51
|
+
},
|
52
|
+
"recall": {
|
53
|
+
"function": metrics.recall_score,
|
54
|
+
"is_lower_better": False,
|
55
|
+
},
|
56
|
+
"mse": {
|
57
|
+
"function": metrics.mean_squared_error,
|
58
|
+
"is_lower_better": True,
|
59
|
+
},
|
60
|
+
"mae": {
|
61
|
+
"function": metrics.mean_absolute_error,
|
62
|
+
"is_lower_better": True,
|
63
|
+
},
|
64
|
+
"r2": {
|
65
|
+
"function": metrics.r2_score,
|
66
|
+
"is_lower_better": False,
|
67
|
+
},
|
68
|
+
"mape": {
|
69
|
+
"function": metrics.mean_absolute_percentage_error,
|
70
|
+
"is_lower_better": True,
|
71
|
+
},
|
72
|
+
}
|
73
|
+
|
74
|
+
|
75
|
+
def _add_noise_std_dev(
|
76
|
+
values: List[float], x_std_dev: float
|
77
|
+
) -> Tuple[List[float], float]:
|
29
78
|
"""
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
**Test Mechanism**:
|
41
|
-
|
42
|
-
This test is conducted by adding Gaussian noise, proportional to a particular standard deviation scale, to numeric
|
43
|
-
input features of both the training and testing datasets. The model performance in the face of these perturbed
|
44
|
-
features is then evaluated using the ROC_AUC score. This process is iterated over a range of scale
|
45
|
-
factors. The resulting auc trend against the amount of noise introduced is illustrated with a line chart. A
|
46
|
-
predetermined threshold determines what level of auc decay due to perturbation is considered acceptable.
|
47
|
-
|
48
|
-
**Signs of High Risk**:
|
49
|
-
- Substantial decreases in auc when noise is introduced to feature inputs.
|
50
|
-
- The decay in auc surpasses the configured threshold, indicating that the model is not robust against input
|
51
|
-
noise.
|
52
|
-
- Instances where one or more elements provided in the features list don't match with the training dataset's
|
53
|
-
numerical feature columns.
|
54
|
-
|
55
|
-
**Strengths**:
|
56
|
-
- Provides an empirical measure of the model's performance in tackling noise or data perturbations, revealing
|
57
|
-
insights into the model's stability.
|
58
|
-
- Offers flexibility with the ability to choose specific features to perturb and control the level of noise applied.
|
59
|
-
- Detailed results visualization helps in interpreting the outcome of robustness testing.
|
60
|
-
|
61
|
-
**Limitations**:
|
62
|
-
- The default threshold for auc decay is set to 0.05, which is unlikely to be optimal for most use cases and
|
63
|
-
should be adjusted based on domain expertise to suit the needs of the specific model.
|
64
|
-
- Only numerical features are perturbed, leaving out non-numerical features, which can lead to an incomplete
|
65
|
-
analysis of robustness.
|
66
|
-
- The test is contingent on the assumption that the added Gaussian noise sufficiently represents potential data
|
67
|
-
corruption or incompleteness in real-world scenarios.
|
79
|
+
Adds Gaussian noise to a list of values.
|
80
|
+
Args:
|
81
|
+
values (list[float]): A list of numerical values to which noise is added.
|
82
|
+
x_std_dev (float): A scaling factor for the standard deviation of the noise.
|
83
|
+
Returns:
|
84
|
+
tuple[list[float], float]: A tuple containing:
|
85
|
+
- A list of noisy values, where each value is the sum of the corresponding value
|
86
|
+
in the input list and a randomly generated value sampled from a Gaussian distribution
|
87
|
+
with mean 0 and standard deviation x_std_dev times the standard deviation of the input list.
|
88
|
+
- The standard deviation of the input list of values.
|
68
89
|
"""
|
90
|
+
std_dev = np.std(values)
|
91
|
+
noise_list = np.random.normal(0, x_std_dev * std_dev, size=len(values))
|
92
|
+
noisy_values = list(map(add, noise_list, values))
|
69
93
|
|
70
|
-
|
71
|
-
required_inputs = ["model", "datasets"]
|
72
|
-
default_params = {
|
73
|
-
"features_columns": None,
|
74
|
-
"scaling_factor_std_dev_list": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5],
|
75
|
-
"auc_decay_threshold": 0.05,
|
76
|
-
}
|
77
|
-
tasks = ["classification"]
|
78
|
-
tags = [
|
79
|
-
"sklearn",
|
80
|
-
"binary_classification",
|
81
|
-
"multiclass_classification",
|
82
|
-
"model_diagnosis",
|
83
|
-
"visualization",
|
84
|
-
]
|
94
|
+
return noisy_values
|
85
95
|
|
86
|
-
def run(self):
|
87
|
-
# Validate X std deviation parameter
|
88
|
-
if "scaling_factor_std_dev_list" not in self.params:
|
89
|
-
raise ValueError("scaling_factor_std_dev_list must be provided in params")
|
90
|
-
x_std_dev_list = self.params["scaling_factor_std_dev_list"]
|
91
96
|
|
92
|
-
|
93
|
-
|
94
|
-
|
97
|
+
def _compute_metric(
|
98
|
+
dataset: VMDataset, model: VMModel, X: pd.DataFrame, metric: str
|
99
|
+
) -> float:
|
100
|
+
if metric not in PERFORMANCE_METRICS:
|
101
|
+
raise ValueError(
|
102
|
+
f"Invalid metric: {metric}, expected one of {PERFORMANCE_METRICS.keys()}"
|
103
|
+
)
|
95
104
|
|
96
|
-
|
97
|
-
|
105
|
+
if metric == "auc":
|
106
|
+
try:
|
107
|
+
y_proba = model.predict_proba(X)
|
108
|
+
except MissingOrInvalidModelPredictFnError:
|
109
|
+
y_proba = model.predict(X)
|
110
|
+
return metrics.roc_auc_score(dataset.y, y_proba)
|
111
|
+
|
112
|
+
return PERFORMANCE_METRICS[metric]["function"](dataset.y, model.predict(X))
|
113
|
+
|
114
|
+
|
115
|
+
def _compute_gap(result: dict, metric: str) -> float:
|
116
|
+
if PERFORMANCE_METRICS[metric]["is_lower_better"]:
|
117
|
+
return result[metric.upper()][-1] - result[metric.upper()][0]
|
118
|
+
|
119
|
+
return result[metric.upper()][0] - result[metric.upper()][-1]
|
120
|
+
|
121
|
+
|
122
|
+
def _combine_results(results: List[dict]):
|
123
|
+
final_results = defaultdict(list)
|
124
|
+
|
125
|
+
# Interleave rows from each dictionary
|
126
|
+
for i in range(len(results[0]["Perturbation Size"])):
|
127
|
+
for result in results:
|
128
|
+
for key in result.keys():
|
129
|
+
final_results[key].append(result[key][i])
|
130
|
+
|
131
|
+
return pd.DataFrame(final_results)
|
132
|
+
|
133
|
+
|
134
|
+
def _plot_robustness(
|
135
|
+
results: pd.DataFrame, metric: str, threshold: float, columns: List[str]
|
136
|
+
):
|
137
|
+
fig, ax = plt.subplots()
|
138
|
+
|
139
|
+
pallete = sns.color_palette("muted", len(results["Dataset"].unique()))
|
140
|
+
sns.lineplot(
|
141
|
+
data=results,
|
142
|
+
x="Perturbation Size",
|
143
|
+
y=metric.upper(),
|
144
|
+
hue="Dataset",
|
145
|
+
style="Dataset",
|
146
|
+
linewidth=3,
|
147
|
+
markers=True,
|
148
|
+
markersize=10,
|
149
|
+
dashes=False,
|
150
|
+
palette=pallete,
|
151
|
+
ax=ax,
|
152
|
+
)
|
153
|
+
|
154
|
+
if PERFORMANCE_METRICS[metric]["is_lower_better"]:
|
155
|
+
y_label = f"{metric.upper()} (lower is better)"
|
156
|
+
else:
|
157
|
+
threshold = -threshold
|
158
|
+
y_label = f"{metric.upper()} (higher is better)"
|
159
|
+
|
160
|
+
# add dotted threshold line
|
161
|
+
for i in range(len(results["Dataset"].unique())):
|
162
|
+
baseline = results[results["Dataset"] == results["Dataset"].unique()[i]][
|
163
|
+
metric.upper()
|
164
|
+
].iloc[0]
|
165
|
+
ax.axhline(
|
166
|
+
y=baseline + threshold,
|
167
|
+
color=pallete[i],
|
168
|
+
linestyle="dotted",
|
169
|
+
)
|
98
170
|
|
99
|
-
|
100
|
-
|
101
|
-
|
171
|
+
ax.tick_params(axis="x")
|
172
|
+
ax.set_ylabel(y_label, weight="bold", fontsize=18)
|
173
|
+
ax.legend(fontsize=18)
|
174
|
+
ax.set_xlabel(
|
175
|
+
"Perturbation Size (X * Standard Deviation)", weight="bold", fontsize=18
|
176
|
+
)
|
177
|
+
ax.set_title(
|
178
|
+
f"Perturbed Features: {', '.join(columns)}",
|
179
|
+
weight="bold",
|
180
|
+
fontsize=20,
|
181
|
+
wrap=True,
|
182
|
+
)
|
183
|
+
|
184
|
+
# prevent the figure from being displayed
|
185
|
+
plt.close("all")
|
186
|
+
|
187
|
+
return fig
|
188
|
+
|
189
|
+
|
190
|
+
# TODO: make this a functional test instead of class-based when appropriate
|
191
|
+
# simply have to remove the class and rename this func to OverfitDiagnosis
|
192
|
+
def robustness_diagnosis(
|
193
|
+
model: VMModel,
|
194
|
+
datasets: List[VMDataset],
|
195
|
+
metric: str = None,
|
196
|
+
scaling_factor_std_dev_list: List[float] = DEFAULT_STD_DEV_LIST,
|
197
|
+
performance_decay_threshold: float = DEFAULT_DECAY_THRESHOLD,
|
198
|
+
):
|
199
|
+
if not metric:
|
200
|
+
metric = (
|
201
|
+
DEFAULT_CLASSIFICATION_METRIC
|
202
|
+
if datasets[0].probability_column(model)
|
203
|
+
else DEFAULT_REGRESSION_METRIC
|
204
|
+
)
|
205
|
+
logger.info(f"Using default metric ({metric.upper()}) for robustness diagnosis")
|
102
206
|
|
103
|
-
|
104
|
-
|
105
|
-
|
207
|
+
if id(scaling_factor_std_dev_list) == id(DEFAULT_STD_DEV_LIST):
|
208
|
+
logger.info(
|
209
|
+
f"Using default scaling factors for the standard deviation of the noise: {DEFAULT_STD_DEV_LIST}"
|
210
|
+
)
|
106
211
|
|
107
|
-
|
108
|
-
|
109
|
-
|
212
|
+
if id(performance_decay_threshold) == id(DEFAULT_DECAY_THRESHOLD):
|
213
|
+
logger.info(
|
214
|
+
f"Using default performance decay threshold of {DEFAULT_DECAY_THRESHOLD}"
|
110
215
|
)
|
111
|
-
|
112
|
-
|
113
|
-
|
114
|
-
|
216
|
+
|
217
|
+
results = [{} for _ in range(len(datasets))]
|
218
|
+
|
219
|
+
# add baseline results (no perturbation)
|
220
|
+
for dataset, result in zip(datasets, results):
|
221
|
+
result["Perturbation Size"] = [0.0]
|
222
|
+
result["Dataset"] = [f"{dataset.input_id}"]
|
223
|
+
result["Row Count"] = [dataset._df.shape[0]]
|
224
|
+
|
225
|
+
result[metric.upper()] = [
|
226
|
+
_compute_metric(
|
227
|
+
dataset=dataset,
|
228
|
+
model=model,
|
229
|
+
X=dataset.x_df(),
|
230
|
+
metric=metric,
|
115
231
|
)
|
232
|
+
]
|
233
|
+
result["Performance Decay"] = [0.0]
|
234
|
+
result["Passed"] = [True]
|
235
|
+
|
236
|
+
# Iterate scaling factor for the standard deviation list
|
237
|
+
for x_std_dev in scaling_factor_std_dev_list:
|
238
|
+
for dataset, result in zip(datasets, results):
|
239
|
+
|
240
|
+
result["Perturbation Size"].append(x_std_dev)
|
241
|
+
result["Dataset"].append(result["Dataset"][0])
|
242
|
+
result["Row Count"].append(result["Row Count"][0])
|
243
|
+
|
244
|
+
temp_df = dataset.x_df().copy()
|
245
|
+
for feature in dataset.feature_columns_numeric:
|
246
|
+
temp_df[feature] = _add_noise_std_dev(
|
247
|
+
values=temp_df[feature].to_list(),
|
248
|
+
x_std_dev=x_std_dev,
|
249
|
+
)
|
116
250
|
|
117
|
-
|
118
|
-
|
119
|
-
|
251
|
+
result[metric.upper()].append(
|
252
|
+
_compute_metric(
|
253
|
+
dataset=dataset,
|
254
|
+
model=model,
|
255
|
+
X=temp_df,
|
256
|
+
metric=metric,
|
257
|
+
)
|
258
|
+
)
|
259
|
+
result["Performance Decay"].append(_compute_gap(result, metric))
|
260
|
+
result["Passed"].append(
|
261
|
+
result["Performance Decay"][-1] < performance_decay_threshold
|
120
262
|
)
|
121
263
|
|
122
|
-
|
123
|
-
|
264
|
+
results_df = _combine_results(results)
|
265
|
+
fig = _plot_robustness(
|
266
|
+
results=results_df,
|
267
|
+
metric=metric,
|
268
|
+
threshold=performance_decay_threshold,
|
269
|
+
columns=datasets[0].feature_columns_numeric,
|
270
|
+
)
|
124
271
|
|
125
|
-
|
126
|
-
|
272
|
+
# rename perturbation size for baseline
|
273
|
+
results_df["Perturbation Size"][
|
274
|
+
results_df["Perturbation Size"] == 0.0
|
275
|
+
] = "Baseline (0.0)"
|
127
276
|
|
128
|
-
|
129
|
-
test_figures = []
|
277
|
+
return results_df, fig
|
130
278
|
|
131
|
-
results_headers = ["Perturbation Size", "Dataset Type", "Records", "AUC"]
|
132
|
-
results = {k: [] for k in results_headers}
|
133
|
-
# Iterate scaling factor for the standard deviation list
|
134
|
-
for x_std_dev in x_std_dev_list:
|
135
|
-
temp_train_df = train_df.copy()
|
136
|
-
temp_test_df = test_df.copy()
|
137
279
|
|
138
|
-
|
139
|
-
|
140
|
-
|
141
|
-
|
142
|
-
|
143
|
-
|
144
|
-
|
145
|
-
|
280
|
+
@dataclass
|
281
|
+
class RobustnessDiagnosis(ThresholdTest):
|
282
|
+
"""Evaluate the robustness of a machine learning model to noise
|
283
|
+
|
284
|
+
Robustness refers to a model's ability to maintain a high level of performance in
|
285
|
+
the face of perturbations or changes (particularly noise) added to its input data.
|
286
|
+
This test is designed to help gauge how well the model can handle potential real-
|
287
|
+
world scenarios where the input data might be incomplete or corrupted.
|
288
|
+
|
289
|
+
## Test Methodology
|
290
|
+
This test is conducted by adding Gaussian noise, proportional to a particular standard
|
291
|
+
deviation scale, to numeric input features of the input datasets. The model's
|
292
|
+
performance on the perturbed data is then evaluated using a user-defined metric or the
|
293
|
+
default metric of AUC for classification tasks and MSE for regression tasks. The results
|
294
|
+
are then plotted to visualize the model's performance decay as the perturbation size
|
295
|
+
increases.
|
296
|
+
|
297
|
+
When using this test, it is highly recommended to tailor the performance metric, list
|
298
|
+
of scaling factors for the standard deviation of the noise, and the performance decay
|
299
|
+
threshold to the specific use case of the model being evaluated.
|
300
|
+
|
301
|
+
**Inputs**:
|
302
|
+
- model (VMModel): The trained model to be evaluated.
|
303
|
+
- datasets (List[VMDataset]): A list of datasets to evaluate the model against.
|
304
|
+
|
305
|
+
## Parameters
|
306
|
+
- metric (str, optional): The performance metric to be used for evaluation. If not
|
307
|
+
provided, the default metric is used based on the task of the model. Default values
|
308
|
+
are "auc" for classification tasks and "mse" for regression tasks.
|
309
|
+
- scaling_factor_std_dev_list (List[float], optional): A list of scaling factors for
|
310
|
+
the standard deviation of the noise to be added to the input features. The default
|
311
|
+
values are [0.1, 0.2, 0.3, 0.4, 0.5].
|
312
|
+
- performance_decay_threshold (float, optional): The threshold for the performance
|
313
|
+
decay of the model. The default value is 0.05.
|
314
|
+
"""
|
146
315
|
|
147
|
-
|
148
|
-
|
149
|
-
|
150
|
-
|
151
|
-
|
152
|
-
|
153
|
-
|
154
|
-
|
155
|
-
|
156
|
-
|
157
|
-
|
158
|
-
|
159
|
-
|
160
|
-
"metric": "AUC",
|
161
|
-
"features_list": features_list,
|
162
|
-
},
|
163
|
-
)
|
164
|
-
)
|
316
|
+
name = "robustness"
|
317
|
+
required_inputs = ["model", "datasets"]
|
318
|
+
default_params = {
|
319
|
+
"metric": None,
|
320
|
+
"scaling_factor_std_dev_list": DEFAULT_STD_DEV_LIST,
|
321
|
+
"performance_decay_threshold": DEFAULT_DECAY_THRESHOLD,
|
322
|
+
}
|
323
|
+
tasks = ["classification", "regression"]
|
324
|
+
tags = [
|
325
|
+
"sklearn",
|
326
|
+
"model_diagnosis",
|
327
|
+
"visualization",
|
328
|
+
]
|
165
329
|
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
np.where(
|
174
|
-
(df["Dataset Type"] == "Test")
|
175
|
-
& (df["AUC"] >= (test_auc - auc_threshold)),
|
176
|
-
True,
|
177
|
-
False,
|
178
|
-
),
|
179
|
-
)
|
180
|
-
test_results.append(
|
181
|
-
ThresholdTestResult(
|
182
|
-
test_name="AUC",
|
183
|
-
column=features_list,
|
184
|
-
passed=True,
|
185
|
-
values={"records": df.to_dict("records")},
|
186
|
-
)
|
330
|
+
def run(self):
|
331
|
+
results, fig = robustness_diagnosis(
|
332
|
+
model=self.inputs.model,
|
333
|
+
datasets=self.inputs.datasets,
|
334
|
+
metric=self.params["metric"],
|
335
|
+
scaling_factor_std_dev_list=self.params["scaling_factor_std_dev_list"],
|
336
|
+
performance_decay_threshold=self.params["performance_decay_threshold"],
|
187
337
|
)
|
338
|
+
|
188
339
|
return self.cache_results(
|
189
|
-
|
340
|
+
passed=results["Passed"].all(),
|
341
|
+
test_results_list=[
|
342
|
+
ThresholdTestResult(
|
343
|
+
test_name=self.params["metric"],
|
344
|
+
passed=results["Passed"].all(),
|
345
|
+
values=results.to_dict(orient="records"),
|
346
|
+
)
|
347
|
+
],
|
348
|
+
figures=[
|
349
|
+
Figure(
|
350
|
+
for_object=self,
|
351
|
+
key=f"{self.name}:{self.params['metric']}",
|
352
|
+
figure=fig,
|
353
|
+
)
|
354
|
+
],
|
190
355
|
)
|
191
356
|
|
192
357
|
def summary(self, results: List[ThresholdTestResult], _):
|
193
|
-
results_table = [
|
194
|
-
record for result in results for record in result.values["records"]
|
195
|
-
]
|
196
358
|
return ResultSummary(
|
197
359
|
results=[
|
198
360
|
ResultTable(
|
199
|
-
data=
|
200
|
-
metadata=ResultTableMetadata(title="Robustness
|
361
|
+
data=results[0].values,
|
362
|
+
metadata=ResultTableMetadata(title="Robustness Diagnosis Results"),
|
201
363
|
)
|
202
364
|
]
|
203
365
|
)
|
204
366
|
|
205
|
-
def _compute_metrics(
|
206
|
-
self,
|
207
|
-
results: dict,
|
208
|
-
df: pd.DataFrame,
|
209
|
-
y_true: str,
|
210
|
-
x_std_dev: float,
|
211
|
-
dataset_type: str,
|
212
|
-
):
|
213
|
-
"""
|
214
|
-
Compute evaluation metrics for a given perturbed dataset.
|
215
|
-
Args:
|
216
|
-
results (dict): A dictionary to store the results of the computation.
|
217
|
-
df (pd.DataFrame): A Pandas dataframe containing the dataset to evaluate.
|
218
|
-
y_true (str): A string representing the name of the column containing the true target values.
|
219
|
-
x_std_dev (float): A float representing the standard deviation of the perturbation applied to the dataset.
|
220
|
-
dataset_type (str): A string representing the type of dataset (e.g. "training", "validation", "test").
|
221
|
-
Returns:
|
222
|
-
None
|
223
|
-
"""
|
224
|
-
results["Dataset Type"].append(dataset_type)
|
225
|
-
results["Perturbation Size"].append(x_std_dev)
|
226
|
-
results["Records"].append(df.shape[0])
|
227
|
-
|
228
|
-
try:
|
229
|
-
y_proba = self.inputs.model.predict_proba(df)
|
230
|
-
except MissingOrInvalidModelPredictFnError:
|
231
|
-
y_proba = self.inputs.model.predict(df)
|
232
|
-
|
233
|
-
results["AUC"].append(metrics.roc_auc_score(y_true, y_proba))
|
234
|
-
|
235
|
-
def _add_noise_std_dev(
|
236
|
-
self, values: List[float], x_std_dev: float
|
237
|
-
) -> Tuple[List[float], float]:
|
238
|
-
"""
|
239
|
-
Adds Gaussian noise to a list of values.
|
240
|
-
Args:
|
241
|
-
values (list[float]): A list of numerical values to which noise is added.
|
242
|
-
x_std_dev (float): A scaling factor for the standard deviation of the noise.
|
243
|
-
Returns:
|
244
|
-
tuple[list[float], float]: A tuple containing:
|
245
|
-
- A list of noisy values, where each value is the sum of the corresponding value
|
246
|
-
in the input list and a randomly generated value sampled from a Gaussian distribution
|
247
|
-
with mean 0 and standard deviation x_std_dev times the standard deviation of the input list.
|
248
|
-
- The standard deviation of the input list of values.
|
249
|
-
"""
|
250
|
-
std_dev = np.std(values)
|
251
|
-
noise_list = np.random.normal(0, x_std_dev * std_dev, size=len(values))
|
252
|
-
noisy_values = list(map(add, noise_list, values))
|
253
|
-
|
254
|
-
return noisy_values
|
255
|
-
|
256
|
-
def _plot_robustness(self, results: dict, features_columns: List[str]):
|
257
|
-
"""
|
258
|
-
Plots the model's auc under feature perturbations.
|
259
|
-
Args:
|
260
|
-
results (dict): A dictionary containing the results of the evaluation.
|
261
|
-
It has the following keys:
|
262
|
-
- 'Dataset Type': the type of dataset evaluated, e.g. 'Training' or 'Test'.
|
263
|
-
- 'Perturbation Size': the size of the perturbation applied to the features.
|
264
|
-
- 'Records': the number of records evaluated.
|
265
|
-
- 'auc': the ROC AUC score obtained for the evaluation.
|
266
|
-
The values of each key are lists containing the results for each evaluation.
|
267
|
-
features_columns (list[str]): A list containing the names of the features perturbed.
|
268
|
-
Returns:
|
269
|
-
tuple[matplotlib.figure.Figure, pd.DataFrame]: A tuple containing the matplotlib Figure object
|
270
|
-
and a DataFrame containing the results used to generate the plot.
|
271
|
-
"""
|
272
|
-
df = pd.DataFrame(results)
|
273
|
-
|
274
|
-
# Create a bar plot using seaborn library
|
275
|
-
fig, ax = plt.subplots()
|
276
|
-
sns.lineplot(
|
277
|
-
data=df,
|
278
|
-
x="Perturbation Size",
|
279
|
-
y="AUC",
|
280
|
-
hue="Dataset Type",
|
281
|
-
style="Dataset Type",
|
282
|
-
linewidth=3,
|
283
|
-
markers=True,
|
284
|
-
markersize=10,
|
285
|
-
dashes=False,
|
286
|
-
palette=["red", "blue"],
|
287
|
-
ax=ax,
|
288
|
-
)
|
289
|
-
ax.tick_params(axis="x")
|
290
|
-
ax.set_ylabel("AUC", weight="bold", fontsize=18)
|
291
|
-
ax.legend(fontsize=18)
|
292
|
-
ax.set_xlabel(
|
293
|
-
"Perturbation Size (X * Standard Deviation)", weight="bold", fontsize=18
|
294
|
-
)
|
295
|
-
ax.set_title(
|
296
|
-
f"Perturbed Features: {', '.join(features_columns)}",
|
297
|
-
weight="bold",
|
298
|
-
fontsize=20,
|
299
|
-
wrap=True,
|
300
|
-
)
|
301
|
-
|
302
|
-
# Do this if you want to prevent the figure from being displayed
|
303
|
-
plt.close("all")
|
304
|
-
|
305
|
-
# fig, ax = plt.subplots()
|
306
|
-
return fig, df
|
307
|
-
|
308
367
|
def test(self):
|
309
368
|
"""Unit Test for Robustness Diagnosis Threshold Test"""
|
310
369
|
# Verify the result object is present
|
@@ -313,16 +372,8 @@ class RobustnessDiagnosis(ThresholdTest):
|
|
313
372
|
# Verify test results and their type
|
314
373
|
assert isinstance(self.result.test_results.results, list)
|
315
374
|
|
316
|
-
# Check for presence and validity of 'values'
|
375
|
+
# Check for presence and validity of 'values' and 'passed' flag in each result
|
317
376
|
for test_result in self.result.test_results.results:
|
318
377
|
assert "values" in test_result.__dict__
|
319
378
|
assert "passed" in test_result.__dict__
|
320
|
-
assert isinstance(test_result.values,
|
321
|
-
assert "records" in test_result.values
|
322
|
-
|
323
|
-
# For unperturbed training dataset, auc should be present
|
324
|
-
if (
|
325
|
-
test_result.column == self.params["features_columns"]
|
326
|
-
and 0.0 in test_result.values["records"][0]["Perturbation Size"]
|
327
|
-
):
|
328
|
-
assert "AUC" in test_result.values["records"][0]
|
379
|
+
assert isinstance(test_result.values, list)
|
validmind/tests/run.py
CHANGED
@@ -405,7 +405,7 @@ def run_test(
|
|
405
405
|
|
406
406
|
if unit_metrics:
|
407
407
|
metric_id_name = "".join(word[0].upper() + word[1:] for word in name.split())
|
408
|
-
test_id = f"validmind.
|
408
|
+
test_id = f"validmind.composite_metric.{metric_id_name}"
|
409
409
|
|
410
410
|
error, TestClass = load_composite_metric(
|
411
411
|
unit_metrics=unit_metrics, metric_name=metric_id_name
|
@@ -10,6 +10,7 @@ import pandas as pd
|
|
10
10
|
|
11
11
|
from validmind.errors import MissingOrInvalidModelPredictFnError
|
12
12
|
from validmind.logging import get_logger
|
13
|
+
from validmind.vm_models.model import ModelTask
|
13
14
|
|
14
15
|
logger = get_logger(__name__)
|
15
16
|
|
@@ -118,8 +119,14 @@ def compute_predictions(model, X, **kwargs) -> tuple:
|
|
118
119
|
"You can pass `prediction_values` or `prediction_columns` to use precomputed predictions"
|
119
120
|
)
|
120
121
|
|
121
|
-
|
122
|
-
|
122
|
+
if model.attributes.task is ModelTask.REGRESSION:
|
123
|
+
logger.info("Model is configured for regression.")
|
124
|
+
return probability_values, prediction_values
|
125
|
+
|
126
|
+
if probability_values is None and (
|
127
|
+
model.attributes.task is ModelTask.CLASSIFICATION
|
128
|
+
or _is_probabilties(prediction_values)
|
129
|
+
):
|
123
130
|
logger.info(
|
124
131
|
"Predict method returned probabilities instead of direct labels or regression values. "
|
125
132
|
"This implies the model is likely configured for a classification task with probability output."
|
validmind/vm_models/model.py
CHANGED
@@ -9,6 +9,7 @@ import importlib
|
|
9
9
|
import inspect
|
10
10
|
from abc import abstractmethod
|
11
11
|
from dataclasses import dataclass
|
12
|
+
from enum import Enum
|
12
13
|
|
13
14
|
from validmind.errors import MissingOrInvalidModelPredictFnError
|
14
15
|
|
@@ -38,6 +39,14 @@ R_MODEL_METHODS = [
|
|
38
39
|
]
|
39
40
|
|
40
41
|
|
42
|
+
class ModelTask(Enum):
|
43
|
+
"""Model task enums"""
|
44
|
+
|
45
|
+
# TODO: add more tasks
|
46
|
+
CLASSIFICATION = "classification"
|
47
|
+
REGRESSION = "regression"
|
48
|
+
|
49
|
+
|
41
50
|
class ModelPipeline:
|
42
51
|
"""Helper class for chaining models together
|
43
52
|
|
@@ -65,6 +74,7 @@ class ModelAttributes:
|
|
65
74
|
framework: str = None
|
66
75
|
framework_version: str = None
|
67
76
|
language: str = None
|
77
|
+
task: ModelTask = None
|
68
78
|
|
69
79
|
@classmethod
|
70
80
|
def from_dict(cls, data):
|
@@ -76,6 +86,7 @@ class ModelAttributes:
|
|
76
86
|
framework=data.get("framework"),
|
77
87
|
framework_version=data.get("framework_version"),
|
78
88
|
language=data.get("language"),
|
89
|
+
task=ModelTask(data.get("task")) if data.get("task") else None,
|
79
90
|
)
|
80
91
|
|
81
92
|
|
@@ -108,7 +119,7 @@ class VMModel(VMInput):
|
|
108
119
|
|
109
120
|
self.name = name or self.__class__.__name__
|
110
121
|
|
111
|
-
self.attributes = attributes
|
122
|
+
self.attributes = attributes or ModelAttributes()
|
112
123
|
|
113
124
|
# set any additional attributes passed in (likely for subclasses)
|
114
125
|
for key, value in kwargs.items():
|
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.1
|
2
2
|
Name: validmind
|
3
|
-
Version: 2.5.
|
3
|
+
Version: 2.5.6
|
4
4
|
Summary: ValidMind Developer Framework
|
5
5
|
License: Commercial License
|
6
6
|
Author: Andres Rodriguez
|
@@ -49,7 +49,7 @@ Requires-Dist: scorecardpy (>=0.1.9.6,<0.2.0.0)
|
|
49
49
|
Requires-Dist: seaborn
|
50
50
|
Requires-Dist: sentencepiece (>=0.2.0,<0.3.0) ; extra == "all" or extra == "huggingface" or extra == "llm"
|
51
51
|
Requires-Dist: sentry-sdk (>=1.24.0,<2.0.0)
|
52
|
-
Requires-Dist: shap (
|
52
|
+
Requires-Dist: shap (==0.44.1)
|
53
53
|
Requires-Dist: statsmodels
|
54
54
|
Requires-Dist: tabulate (>=0.8.9,<0.9.0)
|
55
55
|
Requires-Dist: textblob (>=0.18.0.post0,<0.19.0)
|
@@ -1,9 +1,9 @@
|
|
1
1
|
validmind/__init__.py,sha256=UfmzPwUCdUWbWq3zPqqmq4jw0_kfl3hX4U72p_seE4I,3700
|
2
|
-
validmind/__version__.py,sha256=
|
2
|
+
validmind/__version__.py,sha256=1X5kk-wx4BPu-LJgtjkfia2ZtDoOHOAsSyEsLKKQCY0,22
|
3
3
|
validmind/ai/test_descriptions.py,sha256=Q1Ftus4x5eiVLKWJu7hqPLukBQZzhy-dARqq_6_JWtk,9464
|
4
4
|
validmind/ai/utils.py,sha256=TEXII_S5CpkpczzSyHwTlqLcPMLnPBJWEBR6QFMKh1U,3421
|
5
5
|
validmind/api_client.py,sha256=JZIJWuYtvl-VEVi_AK4c839Fn7cGa40J2d4_4FUZcno,17483
|
6
|
-
validmind/client.py,sha256=
|
6
|
+
validmind/client.py,sha256=tFqjbTbJ5AVOythRMn5vcoBm3uCKFbV2yPmk-XqForE,18902
|
7
7
|
validmind/client_config.py,sha256=58L6s6-9vFWC9vkSs_98CjV1YWmlksdhblJtPQxQsAk,1611
|
8
8
|
validmind/datasets/__init__.py,sha256=oYfcvW7BAyUgpghBOnTeGbQF6tpFAWg38rRirdLr8m8,262
|
9
9
|
validmind/datasets/classification/__init__.py,sha256=HlTOBLyb6IorRYmAhP3AIyX-l-NyemyDjV8BBOdrCrY,1787
|
@@ -86,7 +86,7 @@ validmind/test_suites/tabular_datasets.py,sha256=WE4eLzRCfiqAxRqXnZFRR3Lo_u-TI6K
|
|
86
86
|
validmind/test_suites/text_data.py,sha256=YGVGBB05356jN9Gzcy5CHShRzo1fm5mKsZY7YBq0cYU,739
|
87
87
|
validmind/test_suites/time_series.py,sha256=msUyYySAe5VHJJp6z0k0cNt2ekMB8-XkxGER75Zs1hs,6724
|
88
88
|
validmind/tests/__init__.py,sha256=niYvgTHmjS5E42mJMCrzq1vP8PTKCWxVsqSkAaw2wsE,1036
|
89
|
-
validmind/tests/__types__.py,sha256=
|
89
|
+
validmind/tests/__types__.py,sha256=Kgxiyf2djYcKl3ZMg3ND1_f1Hd7Z9VeRTEUnePDDf0U,10085
|
90
90
|
validmind/tests/_store.py,sha256=G604L9g-XIJz8u7BLbHVVVcbx96tDYjAAciaF7wJoiM,2743
|
91
91
|
validmind/tests/data_validation/ACFandPACFPlot.py,sha256=NLoLe-9Z6_41RBee-gRYe4u3kaGojF7ujlyyIk4o3BU,4900
|
92
92
|
validmind/tests/data_validation/ADF.py,sha256=36ZdB8L-hgN0EnYlcxeSsQ3luWip8Qfz_nrYV-1lr74,5113
|
@@ -190,15 +190,14 @@ validmind/tests/model_validation/embeddings/StabilityAnalysisRandomNoise.py,sha2
|
|
190
190
|
validmind/tests/model_validation/embeddings/StabilityAnalysisSynonyms.py,sha256=npnOPAoXb5FoiwQEwp_gDcbGa5xk4rYnXChTJnuGX64,4405
|
191
191
|
validmind/tests/model_validation/embeddings/StabilityAnalysisTranslation.py,sha256=qLydyTQ6mzHOYQzqysjPPe_ltiTsRfPEhZDEDm5XxX8,4825
|
192
192
|
validmind/tests/model_validation/embeddings/TSNEComponentsPairwisePlots.py,sha256=ereo_dGf19xqvOGz7zcGwhDRU_UqvjFRi5n4KmGDKl8,4511
|
193
|
-
validmind/tests/model_validation/ragas/AnswerCorrectness.py,sha256=
|
194
|
-
validmind/tests/model_validation/ragas/AnswerRelevance.py,sha256=
|
195
|
-
validmind/tests/model_validation/ragas/AnswerSimilarity.py,sha256=
|
196
|
-
validmind/tests/model_validation/ragas/AspectCritique.py,sha256=
|
197
|
-
validmind/tests/model_validation/ragas/ContextEntityRecall.py,sha256=
|
198
|
-
validmind/tests/model_validation/ragas/ContextPrecision.py,sha256
|
199
|
-
validmind/tests/model_validation/ragas/ContextRecall.py,sha256=
|
200
|
-
validmind/tests/model_validation/ragas/
|
201
|
-
validmind/tests/model_validation/ragas/Faithfulness.py,sha256=89EeM0lrUq5MAhKYhOO9cnp32WCap6eG2n28SjZH9c4,4525
|
193
|
+
validmind/tests/model_validation/ragas/AnswerCorrectness.py,sha256=UhspG4nY901ZhAmgEzABWiYQPx0rKEJqQnrFCunwnN8,5139
|
194
|
+
validmind/tests/model_validation/ragas/AnswerRelevance.py,sha256=_hD24Ecs1TZQl-lEoFtdgNGg3hXL-VyfmimiJaovnvY,4998
|
195
|
+
validmind/tests/model_validation/ragas/AnswerSimilarity.py,sha256=c1xc4F4gwrrJKn1eEhZQbw1nc39Q2zS75AS9G3XUMAI,4458
|
196
|
+
validmind/tests/model_validation/ragas/AspectCritique.py,sha256=2hGGVMb0_va9Gjqyu1OUI-CSpD6k7ICMnwEYEtRGadk,6264
|
197
|
+
validmind/tests/model_validation/ragas/ContextEntityRecall.py,sha256=zZGenHhWZQRm9CxAl-ZgbHva6vUlbI_jsFkuY4B2LS8,4905
|
198
|
+
validmind/tests/model_validation/ragas/ContextPrecision.py,sha256=FdXTL8KXv6q5lR1BItkCAt105qikYmd89KgvLOqkatE,4631
|
199
|
+
validmind/tests/model_validation/ragas/ContextRecall.py,sha256=fNawcRi5M8773mh-QcuUaJsdoLrkCDPza-qvOBMApKk,4568
|
200
|
+
validmind/tests/model_validation/ragas/Faithfulness.py,sha256=Jg9SK9NPSbLG9nmM1tu55FGSFpqbb3P4e7kPg20OD_8,4526
|
202
201
|
validmind/tests/model_validation/ragas/utils.py,sha256=zh9_pGitutGBS4Tvk3Bw1D-QVnDueggNErAhAvMPUOA,3130
|
203
202
|
validmind/tests/model_validation/sklearn/AdjustedMutualInformation.py,sha256=KhQroHKDG4gpRAoD9Clw65qNslwGS93rTETdZTOqoTk,2840
|
204
203
|
validmind/tests/model_validation/sklearn/AdjustedRandIndex.py,sha256=nSs1BGC8MSWWp7T6M0FZR5kNPraiZwRJF7U6LNCoMMM,2715
|
@@ -217,7 +216,7 @@ validmind/tests/model_validation/sklearn/MinimumAccuracy.py,sha256=5KSAd29dbKs3n
|
|
217
216
|
validmind/tests/model_validation/sklearn/MinimumF1Score.py,sha256=TaLHk98CwQigyt17L1uBBLC25D5J_IKb6a_IFJFO7AE,4618
|
218
217
|
validmind/tests/model_validation/sklearn/MinimumROCAUCScore.py,sha256=Z5JZ4edtzuyneI8qSmGv-OKL2PVq5dg44CwSmePz3OU,5102
|
219
218
|
validmind/tests/model_validation/sklearn/ModelsPerformanceComparison.py,sha256=-fGgddsc_0832zTl_gRRsLx2sZWBPB0FdS5YmbluN8s,6132
|
220
|
-
validmind/tests/model_validation/sklearn/OverfitDiagnosis.py,sha256=
|
219
|
+
validmind/tests/model_validation/sklearn/OverfitDiagnosis.py,sha256=kB392ZQYqsPCgVDbqZ-056PliVJ_3Txogf-5iF37qgI,12750
|
221
220
|
validmind/tests/model_validation/sklearn/PermutationFeatureImportance.py,sha256=CqMuBuNWzzTtzVcmhAlJHPmtyDO5YuaoXk5hhIXmRuY,4926
|
222
221
|
validmind/tests/model_validation/sklearn/PopulationStabilityIndex.py,sha256=chYVS4OcvSG3YA91N7VDJ4Lh7EDgNEcUM8_k72s13IM,10072
|
223
222
|
validmind/tests/model_validation/sklearn/PrecisionRecallCurve.py,sha256=V0SS06u8DsyaJpL0S14HBPAQwJJYXnvP3fNp2P4CT84,4363
|
@@ -227,7 +226,7 @@ validmind/tests/model_validation/sklearn/RegressionErrorsComparison.py,sha256=CH
|
|
227
226
|
validmind/tests/model_validation/sklearn/RegressionModelsPerformanceComparison.py,sha256=ELYhY_My1YqS4_i2fnHgL5Dg7vKUIa0wska0bkAFkuU,5737
|
228
227
|
validmind/tests/model_validation/sklearn/RegressionR2Square.py,sha256=Ojm5sz3re4rk17u7xiezn1P_rp7wcA3etKgzdhGYH-s,4906
|
229
228
|
validmind/tests/model_validation/sklearn/RegressionR2SquareComparison.py,sha256=tGJKpfeTvU2xBxsYbQSC5GPDcCS2_j0FcT3uceXZduI,2761
|
230
|
-
validmind/tests/model_validation/sklearn/RobustnessDiagnosis.py,sha256=
|
229
|
+
validmind/tests/model_validation/sklearn/RobustnessDiagnosis.py,sha256=KXBQ5-3ZDLil3WBZR-zWySelN_zb5Ob4Uvuoi1qfFaI,12821
|
231
230
|
validmind/tests/model_validation/sklearn/SHAPGlobalImportance.py,sha256=ECYjHHIz5kfnLi2XlzWOKquRf23_77kdcPK8Xw2qwQk,8887
|
232
231
|
validmind/tests/model_validation/sklearn/SilhouettePlot.py,sha256=6PZ_sqiPBpL4_fyRE_sg0bSWWrDkryh_v-88KK4i3RQ,6185
|
233
232
|
validmind/tests/model_validation/sklearn/TrainingTestDegradation.py,sha256=K3F8Ev7nIaIjwLHC9ljnMp07YwZeqo4RLui5C6IDuR8,7209
|
@@ -270,7 +269,7 @@ validmind/tests/prompt_validation/Robustness.py,sha256=fBdkYnO9yoBazz4wD-l62tT8D
|
|
270
269
|
validmind/tests/prompt_validation/Specificity.py,sha256=h3gKRTTi2rfnGWmGC1YnSt2s_VbZU4KX0iY7LciZ3PU,6068
|
271
270
|
validmind/tests/prompt_validation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
272
271
|
validmind/tests/prompt_validation/ai_powered_test.py,sha256=7TTeIR5GotQosm7oVT8Y3KnwPB3XkVT1Fzhckpr-SgE,1963
|
273
|
-
validmind/tests/run.py,sha256=
|
272
|
+
validmind/tests/run.py,sha256=K_EiaquuSv7rVnr-wl2uO1HUDypWGIEXA8JIjw5xsKw,15876
|
274
273
|
validmind/tests/test_providers.py,sha256=47xe5eb5ufvj1jmhdRsbSvDQTXSDpFDFNeXg3xtXwhw,5320
|
275
274
|
validmind/tests/utils.py,sha256=kNrxfUYbj4DwmkZtpp_1rG4GMUGxYEhvqnYR_A7qAKM,471
|
276
275
|
validmind/unit_metrics/__init__.py,sha256=mFk52eU7bOQKTpruKSrPyzjmxFUpIi5RZuwIE5BVFHU,7345
|
@@ -295,10 +294,10 @@ validmind/utils.py,sha256=DYUB3nig6MJwct5dymhy7Gt9apwzPVipKAWxSrm0-tg,15849
|
|
295
294
|
validmind/vm_models/__init__.py,sha256=V5DH-E1Rkvl-HQEkilppVCHBag9MQXkzyoORLW3LSGQ,1210
|
296
295
|
validmind/vm_models/dataset/__init__.py,sha256=U4CxZjdoc0dd9u2AqBl5PJh1UVbzXWNrmundmjLF-qE,346
|
297
296
|
validmind/vm_models/dataset/dataset.py,sha256=hBaczQjo-Jb1u6Ma5yX86m6JzT16XndAlq32WbHqVx8,25645
|
298
|
-
validmind/vm_models/dataset/utils.py,sha256=
|
297
|
+
validmind/vm_models/dataset/utils.py,sha256=VMcPEgwW9oW5D0MCa_MqXCq_sEzzsLLRmS4RaYrsif0,5530
|
299
298
|
validmind/vm_models/figure.py,sha256=iSrvPcCG5sQrMkX1Fh6c5utRzaroh3bc6IlnGDOK_Eg,6651
|
300
299
|
validmind/vm_models/input.py,sha256=qLdqz_bktr4v0YcPha2vFdDvmkC-btT1pH9zBIkt1OY,1046
|
301
|
-
validmind/vm_models/model.py,sha256=
|
300
|
+
validmind/vm_models/model.py,sha256=Dewux_jTgUAXPgHW6ZtJTa8WvH0WkWsryO43DI9HkMU,6409
|
302
301
|
validmind/vm_models/test/metric.py,sha256=DvXMju36JzxArXNWimq3SSrSUoIHkyvDbuhbgBOKxkk,3357
|
303
302
|
validmind/vm_models/test/metric_result.py,sha256=Bak4GDrMlNq5NtgP5exwlPsKZgz3tWgtC6jZqtHjvqM,1987
|
304
303
|
validmind/vm_models/test/output_template.py,sha256=njqCAMyLxwadkCWhACVskyL9-psTgmUysaeeirTVAX4,1500
|
@@ -312,8 +311,8 @@ validmind/vm_models/test_suite/runner.py,sha256=aewxadRfoOPH48jes2Gtb3Ju_FWFfVM_
|
|
312
311
|
validmind/vm_models/test_suite/summary.py,sha256=GQRNe2ZvvqjQN0yKmaN7ohAUjRFQIN4YYUYxfOuWN6M,4682
|
313
312
|
validmind/vm_models/test_suite/test.py,sha256=_GfbK36l98SjzgVcucmp0OKBJKqMW3neO7SqJ3EWeps,5049
|
314
313
|
validmind/vm_models/test_suite/test_suite.py,sha256=Cns2wL54v0T5Mv5_HJb3kMeaa4rtycdqT8KxK9_rWEU,6279
|
315
|
-
validmind-2.5.
|
316
|
-
validmind-2.5.
|
317
|
-
validmind-2.5.
|
318
|
-
validmind-2.5.
|
319
|
-
validmind-2.5.
|
314
|
+
validmind-2.5.6.dist-info/LICENSE,sha256=XonPUfwjvrC5Ombl3y-ko0Wubb1xdG_7nzvIbkZRKHw,35772
|
315
|
+
validmind-2.5.6.dist-info/METADATA,sha256=cPAO_Hlc8esuZm1W96GFv09amk1VNxn7Oh33iUPUfbI,4242
|
316
|
+
validmind-2.5.6.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
|
317
|
+
validmind-2.5.6.dist-info/entry_points.txt,sha256=HuW7YyOv9u_OEWpViQXtv0nfoI67uieJHawKWA4Hv9A,76
|
318
|
+
validmind-2.5.6.dist-info/RECORD,,
|
@@ -1,119 +0,0 @@
|
|
1
|
-
# Copyright © 2023-2024 ValidMind Inc. All rights reserved.
|
2
|
-
# See the LICENSE file in the root of this repository for details.
|
3
|
-
# SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial
|
4
|
-
|
5
|
-
import warnings
|
6
|
-
|
7
|
-
import plotly.express as px
|
8
|
-
from datasets import Dataset
|
9
|
-
|
10
|
-
from validmind import tags, tasks
|
11
|
-
|
12
|
-
from .utils import get_ragas_config, get_renamed_columns
|
13
|
-
|
14
|
-
|
15
|
-
@tags("ragas", "llm", "retrieval_performance")
|
16
|
-
@tasks("text_qa", "text_generation", "text_summarization", "text_classification")
|
17
|
-
def ContextRelevancy(
|
18
|
-
dataset,
|
19
|
-
question_column: str = "question",
|
20
|
-
contexts_column: str = "contexts",
|
21
|
-
):
|
22
|
-
"""
|
23
|
-
Evaluates the context relevancy metric for entries in a dataset and visualizes the
|
24
|
-
results.
|
25
|
-
|
26
|
-
This metric gauges the relevancy of the retrieved context, calculated based on both
|
27
|
-
the `question` and `contexts`. The values fall within the range of (0, 1), with
|
28
|
-
higher values indicating better relevancy.
|
29
|
-
|
30
|
-
Ideally, the retrieved context should exclusively contain essential information to
|
31
|
-
address the provided query. To compute this, we initially estimate the value of by
|
32
|
-
identifying sentences within the retrieved context that are relevant for answering
|
33
|
-
the given question. The final score is determined by the following formula:
|
34
|
-
|
35
|
-
$$
|
36
|
-
\\text{context relevancy} = {|S| \\over |\\text{Total number of sentences in retrieved context}|}
|
37
|
-
$$
|
38
|
-
|
39
|
-
### Configuring Columns
|
40
|
-
|
41
|
-
This metric requires the following columns in your dataset:
|
42
|
-
- `question` (str): The text query that was input into the model.
|
43
|
-
- `contexts` (List[str]): A list of text contexts which are retrieved and which
|
44
|
-
will be evaluated to make sure they are relevant to the question.
|
45
|
-
|
46
|
-
If the above data is not in the appropriate column, you can specify different column
|
47
|
-
names for these fields using the parameters `question_column` and `contexts_column`.
|
48
|
-
|
49
|
-
For example, if your dataset has this data stored in different columns, you can
|
50
|
-
pass the following parameters:
|
51
|
-
```python
|
52
|
-
{
|
53
|
-
"question_column": "question",
|
54
|
-
"contexts_column": "context_info"
|
55
|
-
}
|
56
|
-
```
|
57
|
-
|
58
|
-
If the data is stored as a dictionary in another column, specify the column and key
|
59
|
-
like this:
|
60
|
-
```python
|
61
|
-
pred_col = dataset.prediction_column(model)
|
62
|
-
params = {
|
63
|
-
"contexts_column": f"{pred_col}.contexts",
|
64
|
-
}
|
65
|
-
```
|
66
|
-
|
67
|
-
For more complex situations, you can use a function to extract the data:
|
68
|
-
```python
|
69
|
-
pred_col = dataset.prediction_column(model)
|
70
|
-
params = {
|
71
|
-
"contexts_column": lambda x: [x[pred_col]["context_message"]],
|
72
|
-
}
|
73
|
-
```
|
74
|
-
"""
|
75
|
-
try:
|
76
|
-
from ragas import evaluate
|
77
|
-
from ragas.metrics import context_relevancy
|
78
|
-
except ImportError:
|
79
|
-
raise ImportError("Please run `pip install validmind[llm]` to use LLM tests")
|
80
|
-
|
81
|
-
warnings.filterwarnings(
|
82
|
-
"ignore",
|
83
|
-
category=FutureWarning,
|
84
|
-
message="promote has been superseded by promote_options='default'.",
|
85
|
-
)
|
86
|
-
|
87
|
-
required_columns = {
|
88
|
-
"question": question_column,
|
89
|
-
"contexts": contexts_column,
|
90
|
-
}
|
91
|
-
|
92
|
-
df = get_renamed_columns(dataset.df, required_columns)
|
93
|
-
|
94
|
-
result_df = evaluate(
|
95
|
-
Dataset.from_pandas(df), metrics=[context_relevancy], **get_ragas_config()
|
96
|
-
).to_pandas()
|
97
|
-
|
98
|
-
fig_histogram = px.histogram(x=result_df["context_relevancy"].to_list(), nbins=10)
|
99
|
-
fig_box = px.box(x=result_df["context_relevancy"].to_list())
|
100
|
-
|
101
|
-
return (
|
102
|
-
{
|
103
|
-
"Scores (will not be uploaded to UI)": result_df[
|
104
|
-
["question", "contexts", "context_relevancy"]
|
105
|
-
],
|
106
|
-
"Aggregate Scores": [
|
107
|
-
{
|
108
|
-
"Mean Score": result_df["context_relevancy"].mean(),
|
109
|
-
"Median Score": result_df["context_relevancy"].median(),
|
110
|
-
"Max Score": result_df["context_relevancy"].max(),
|
111
|
-
"Min Score": result_df["context_relevancy"].min(),
|
112
|
-
"Standard Deviation": result_df["context_relevancy"].std(),
|
113
|
-
"Count": len(result_df),
|
114
|
-
}
|
115
|
-
],
|
116
|
-
},
|
117
|
-
fig_histogram,
|
118
|
-
fig_box,
|
119
|
-
)
|
File without changes
|
File without changes
|
File without changes
|