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 | class LinearVRExClassifier(ClassifierMixin, BaseEstimator):
"""Linear multiclass VREx classifier for strict source-only generalization."""
def __init__(
self,
penalty_weight: float = 1.0,
l2: float = 1e-4,
max_iter: int = 500,
tol: float = 1e-8,
fit_intercept: bool = True,
standardize: bool = True,
class_weight: str | Mapping[Any, float] | None = "balanced",
):
self.penalty_weight = penalty_weight
self.l2 = l2
self.max_iter = max_iter
self.tol = tol
self.fit_intercept = fit_intercept
self.standardize = standardize
self.class_weight = class_weight
def fit(
self,
source_features: Sequence[Sequence[float]] | np.ndarray,
source_labels: Sequence[Any] | np.ndarray,
*,
source_domains: Sequence[Hashable] | np.ndarray,
) -> "LinearVRExClassifier":
x = _feature_matrix(source_features, name="source_features")
labels = _object_vector(source_labels, expected_length=x.shape[0], name="source_labels")
domains = _object_vector(source_domains, expected_length=x.shape[0], name="source_domains")
_validate_hashable(domains, name="source_domains")
classes = tuple(dict.fromkeys(labels.tolist()))
domain_values = tuple(dict.fromkeys(domains.tolist()))
if len(classes) < 2:
raise ValueError("VREx requires at least two source classes.")
if len(domain_values) < 2:
raise ValueError("VREx requires at least two source domains.")
class_to_index = _unique_index(classes, name="source classes")
domain_to_index = _unique_index(domain_values, name="source domains")
y = np.asarray([class_to_index[value] for value in labels.tolist()], dtype=int)
domain_ids = np.asarray([domain_to_index[value] for value in domains.tolist()], dtype=int)
penalty_weight = _nonnegative_float(self.penalty_weight, name="penalty_weight")
l2 = _nonnegative_float(self.l2, name="l2")
max_iter = _positive_int(self.max_iter, name="max_iter")
tol = _positive_float(self.tol, name="tol")
fit_intercept = _boolean_config_value(self.fit_intercept, name="fit_intercept")
standardize = _boolean_config_value(self.standardize, name="standardize")
sample_weights = _class_weights(labels, classes=classes, class_weight=self.class_weight)
self.fit_intercept_ = fit_intercept
self.standardize_ = standardize
self.feature_mean_ = np.mean(x, axis=0) if standardize else np.zeros(x.shape[1], dtype=float)
centered = x - self.feature_mean_
self.feature_scale_ = (
np.maximum(np.std(centered, axis=0, ddof=1 if x.shape[0] > 1 else 0), _MIN_SCALE)
if standardize
else np.ones(x.shape[1], dtype=float)
)
z = centered / self.feature_scale_
self.classes_ = _object_vector(classes, expected_length=len(classes), name="classes")
self.source_domains_ = _object_vector(domain_values, expected_length=len(domain_values), name="source_domains")
self.n_features_in_ = int(x.shape[1])
self.n_classes_ = len(classes)
self.n_source_domains_ = len(domain_values)
self.penalty_weight_ = penalty_weight
self.l2_ = l2
self.class_weight_vector_ = sample_weights.copy()
n_free_classes = self.n_classes_ - 1
coefficient_size = self.n_features_in_ * n_free_classes
parameter_size = coefficient_size + (n_free_classes if fit_intercept else 0)
initial = np.zeros(parameter_size, dtype=float)
def objective(parameters: np.ndarray) -> tuple[float, np.ndarray]:
coefficients, intercept = self._unpack(parameters)
losses: list[float] = []
gradients: list[np.ndarray] = []
for domain_index in range(self.n_source_domains_):
mask = domain_ids == domain_index
domain_x = z[mask]
domain_y = y[mask]
weights = sample_weights[mask]
weights = weights / np.sum(weights)
probabilities = _softmax(_reference_logits(domain_x, coefficients, intercept))
loss = float(np.sum(weights * -np.log(np.maximum(probabilities[np.arange(domain_y.shape[0]), domain_y], _MIN_SCALE))))
residual = probabilities
residual[np.arange(domain_y.shape[0]), domain_y] -= 1.0
residual *= weights[:, None]
coefficient_gradient = domain_x.T @ residual[:, :-1]
pieces = [coefficient_gradient.ravel()]
if fit_intercept:
pieces.append(np.sum(residual[:, :-1], axis=0))
losses.append(loss)
gradients.append(np.concatenate(pieces))
loss_vector = np.asarray(losses, dtype=float)
gradient_matrix = np.vstack(gradients)
mean_loss = float(np.mean(loss_vector))
centered_losses = loss_vector - mean_loss
value = mean_loss + penalty_weight * float(np.mean(centered_losses**2))
gradient = np.mean(gradient_matrix, axis=0) + 2.0 * penalty_weight * np.mean(centered_losses[:, None] * gradient_matrix, axis=0)
if l2 > 0.0:
value += 0.5 * l2 * float(np.sum(parameters[:coefficient_size] ** 2))
gradient[:coefficient_size] += l2 * parameters[:coefficient_size]
return value, gradient
optimization = minimize(
fun=lambda parameters: objective(parameters)[0],
x0=initial,
jac=lambda parameters: objective(parameters)[1],
method="L-BFGS-B",
options={"maxiter": max_iter, "ftol": tol, "gtol": tol},
)
if not np.all(np.isfinite(optimization.x)) or not np.isfinite(optimization.fun):
raise RuntimeError("VREx optimization produced non-finite parameters or objective values.")
self.coef_, self.intercept_ = self._unpack(np.asarray(optimization.x, dtype=float))
self.optimization_success_ = bool(optimization.success)
self.optimization_status_ = int(optimization.status)
self.optimization_message_ = str(optimization.message)
self.n_iter_ = int(getattr(optimization, "nit", 0))
self.objective_ = float(optimization.fun)
self.domain_risks_ = self._domain_risks(z, y, domain_ids, sample_weights)
self.domain_risk_variance_ = float(np.var(self.domain_risks_))
self.mean_domain_risk_ = float(np.mean(self.domain_risks_))
return self
def _unpack(self, parameters: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
n_free_classes = self.n_classes_ - 1
coefficient_size = self.n_features_in_ * n_free_classes
coefficients = parameters[:coefficient_size].reshape(self.n_features_in_, n_free_classes)
intercept = parameters[coefficient_size:] if self.fit_intercept_ else np.zeros(n_free_classes, dtype=float)
return coefficients, intercept
def _standardized(self, features: Sequence[Sequence[float]] | np.ndarray) -> np.ndarray:
if not hasattr(self, "coef_"):
raise RuntimeError("LinearVRExClassifier must be fitted before prediction.")
matrix = _feature_matrix(features, name="features")
if matrix.shape[1] != self.n_features_in_:
raise ValueError(f"features width {matrix.shape[1]} does not match fitted width {self.n_features_in_}.")
return (matrix - self.feature_mean_) / self.feature_scale_
def decision_function(self, features: Sequence[Sequence[float]] | np.ndarray) -> np.ndarray:
logits = _reference_logits(self._standardized(features), self.coef_, self.intercept_)
return logits[:, 1] - logits[:, 0] if self.n_classes_ == 2 else logits
def predict_proba(self, features: Sequence[Sequence[float]] | np.ndarray) -> np.ndarray:
return _softmax(_reference_logits(self._standardized(features), self.coef_, self.intercept_))
def predict(self, features: Sequence[Sequence[float]] | np.ndarray) -> np.ndarray:
return self.classes_[np.argmax(self.predict_proba(features), axis=1)]
def _domain_risks(self, x: np.ndarray, y: np.ndarray, domains: np.ndarray, sample_weights: np.ndarray) -> np.ndarray:
probabilities = _softmax(_reference_logits(x, self.coef_, self.intercept_))
risks = []
for domain_index in range(self.n_source_domains_):
mask = domains == domain_index
weights = sample_weights[mask]
weights = weights / np.sum(weights)
risks.append(float(np.sum(weights * -np.log(np.maximum(probabilities[mask, y[mask]], _MIN_SCALE)))))
return np.asarray(risks, dtype=float)
def metadata(self, *, test_rows: int | None = None) -> dict[str, Any]:
if not hasattr(self, "coef_"):
raise RuntimeError("LinearVRExClassifier must be fitted before metadata is available.")
return {
"vrex": True,
"vrex_protocol": VREX_PROTOCOL,
"vrex_protocol_category": VREX_CATEGORY,
"vrex_uses_source_features": True,
"vrex_uses_source_labels": True,
"vrex_uses_source_domains": True,
"vrex_uses_target_features": False,
"vrex_uses_target_labels": False,
"vrex_valid_for_strict_source_only": True,
"vrex_n_source_domains": int(self.n_source_domains_),
"vrex_n_classes": int(self.n_classes_),
"vrex_n_features": int(self.n_features_in_),
"vrex_test_rows": "" if test_rows is None else int(test_rows),
"vrex_penalty_weight": float(self.penalty_weight_),
"vrex_l2": float(self.l2_),
"vrex_standardize": bool(self.standardize_),
"vrex_fit_intercept": bool(self.fit_intercept_),
"vrex_mean_domain_risk": float(self.mean_domain_risk_),
"vrex_domain_risk_variance": float(self.domain_risk_variance_),
"vrex_domain_risks": "|".join(f"{value:.12g}" for value in self.domain_risks_),
"vrex_objective": float(self.objective_),
"vrex_optimization_success": bool(self.optimization_success_),
"vrex_optimization_status": int(self.optimization_status_),
"vrex_optimization_message": self.optimization_message_,
"vrex_n_iter": int(self.n_iter_),
}
|