26from typing
import Any, Iterable, Optional, Sequence
45 """Fully connected autoencoder with a separate latent encoder and decoder."""
46 def __init__(self, input_size, latent_size=2):
51 fst_layer_size = input_size//2
if input_size > 7
else 4
52 snd_layer_size = input_size//4
if input_size > 7
else 2
55 nn.Linear(input_size, fst_layer_size),
57 nn.Linear(fst_layer_size, snd_layer_size),
59 nn.Linear(snd_layer_size, latent_size))
61 nn.Linear(latent_size, snd_layer_size),
63 nn.Linear(snd_layer_size, fst_layer_size),
65 nn.Linear(fst_layer_size, input_size), nn.Tanh())
69 if type(m) == nn.Linear:
70 torch.nn.init.normal_(m.weight, mean=0.0, std=0.3)
71 torch.nn.init.ones_(m.bias)
72 self.
encoder.apply(init_weights)
73 self.
decoder.apply(init_weights)
77 """Encode and reconstruct a batch of score vectors."""
85 def _TorchFeatureExtractionContainerDecorator_get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike:
86 version_key = f
"{self._score_prefix}version"
87 if individual.scores.get(version_key) == self._descriptor_version:
89 while (name := f
"{self._score_prefix}{len(row)}")
in individual.scores:
90 row.append(individual.scores[name])
92 return self.compute_latent([individual])[0]
97 """Use an autoencoder's latent values as archive descriptors.
99 Install PyTorch separately. Supply consistent numeric named scores
100 across candidates. Choose their order with ``base_scores``. By default,
101 use the non-extracted scores in the order of the first training
102 entry's keys. The default model uses the wrapped container's
103 descriptor dimension as its latent width. Set ``observation_score``
104 to encode one fixed-shape numeric observation per individual.
105 The default model flattens these records. Supplied models receive
106 the observation shape with a leading batch dimension.
108 Train periodically from explicit training archives, immediate parents,
109 or the retained entries. After training, recompute latent features
110 and rebuild the wrapped archive. Pair with an autoscaling grid when
111 the latent domain should adjust as the model changes. Alternatively,
112 set ``quantile_transform=True`` and use a fixed unit grid. The decoder
113 still trains in observation space. Before the first fit, a sigmoid
114 maps provisional descriptors into the unit domain.
116 :param quantile_transform: Fit a separate empirical cumulative
117 distribution for each latent coordinate during a rebuild.
118 :param observation_score: Name of the array-valued record to encode.
119 Supply this or ``base_scores`` to choose the input.
122 training_containers: Sequence[ContainerLike]
123 model: Optional[nn.Module]
124 initial_nb_epochs: int
129 base_scores: Optional[Sequence[str]]
132 def __init__(self, container: ContainerLike,
133 training_containers: Sequence[ContainerLike] = (),
134 model: Optional[nn.Module] =
None,
135 initial_nb_epochs: int = 100,
136 nb_epochs: int = 2, batch_size: int = 128,
137 learning_rate: float = 1e-3,
138 training_period: int = 100,
139 base_scores: Optional[Sequence[str]] =
None,
141 quantile_transform: bool =
False,
142 observation_score: Optional[str] =
None,
143 **kwargs: Any) ->
None:
151 if base_scores
is not None and observation_score
is not None:
152 raise ValueError(
"Choose either base_scores or observation_score.")
162 super().__init__(container, **kwargs)
168 lookup = partial(_TorchFeatureExtractionContainerDecorator_get_ind_features, self)
174 return tuple(f
"{self._score_prefix}{i}" for i
in range(len(self.
features_domain)))
178 if '_orig_get_ind_features' in state:
179 del state[
'_orig_get_ind_features']
180 if 'get_ind_features' in state[
'container'].__dict__:
181 del state[
'container'].__dict__[
'get_ind_features']
182 state.setdefault(
"observation_score",
None)
183 state.setdefault(
"quantile_transform",
False)
184 state.setdefault(
"_quantile_transformer",
None)
185 state.setdefault(
"_score_prefix", f
"extracted_{uuid4().hex}_")
186 state.setdefault(
"_descriptor_version", 0)
187 state.setdefault(
"_initial_model_seed",
None)
193 """Build the encoder input in the configured score order."""
196 if data.ndim < 2
or data.size == 0
or not np.isfinite(data).all():
197 raise ValueError(
"Observations must be nonempty, finite arrays of a common shape.")
198 return torch.as_tensor(data, dtype=torch.get_default_dtype())
201 names = [name
for name
in inds[0].scores.keys()
if not name.startswith(
"extracted_")]
206 if type(ind)
is not Individual
or type(scores)
not in (dict, ScoresDict):
208 row = [scores.get(name)
for name
in names]
209 if not all(type(value)
in (float, np.float32, np.float64)
for value
in row):
213 return torch.tensor(rows, dtype=torch.get_default_dtype())
217 data = torch.empty(len(inds), len(names))
218 for i, ind
in enumerate(inds):
219 for j, name
in enumerate(names):
220 data[i, j] = ind.scores[name]
225 parameter = next(model.parameters(),
None)
226 return data
if parameter
is None else data.to(parameter)
232 with torch.no_grad():
234 if latent.ndim != 2
or len(latent) != len(data)
or not torch.isfinite(latent).all():
235 raise ValueError(
"Expected one finite latent vector per record.")
236 return latent.detach().to(device=
"cpu", dtype=torch.float64).numpy()
240 return QuantileTransformer(n_quantiles=min(len(latent), 1000),
241 subsample=max(10_000, len(latent)), random_state=0).fit(latent)
245 if transformer
is not None:
246 return transformer.transform(latent)
253 for ind, row
in zip(inds, rows):
254 for index, value
in enumerate(row):
255 ind.scores[f
"{self._score_prefix}{index}"] = value
263 fit_transform: bool =
False) -> Sequence[FeaturesLike]:
264 """Encode candidates and cache the returned latent descriptors.
266 Set ``fit_transform=True`` when encoding the training archive
267 before rebuilding it. Ordinary inference reuses the fitted
271 raise ValueError(
"At least one individual is required to compute latent descriptors.")
272 if self.
model is None:
281 return [
Features(row)
for row
in rows]
288 with torch.random.fork_rng(devices=[]):
298 model.encoder.insert(0, nn.Flatten())
299 model.decoder.append(nn.Unflatten(1, shape))
308 return (sum(
not name.startswith(
"extracted_")
for name
in example_ind.scores),)
310 def _get_training_inds(self) -> Sequence[IndividualLike]:
313 all_training_inds = [i
for sublist
in training_cont_as_lists
for i
in sublist]
314 return all_training_inds
321 def train(self, nb_epochs: int) ->
None:
322 """Fit the model to score records for the requested number of epochs.
324 The training data comes from configured training containers first,
325 parent archives second, or the wrapped container last. Update
326 ``current_loss`` with the most recent batch's reconstruction loss.
327 Call ``recompute_features_all_ind()`` after manual training to
328 realign the archive with the encoder.
330 :raises ValueError: If there are no training records or no epochs.
333 if not training_inds
or nb_epochs <= 0:
334 raise ValueError(
"Training requires records and at least one epoch.")
335 if self.
model is None:
340 dataloader: Any = DataLoader(data, batch_size=self.
batch_size, shuffle=
True)
343 criterion = nn.MSELoss()
344 optimizer = torch.optim.Adam(self.
model.parameters(), lr=self.
learning_rate, weight_decay=1e-5)
347 for _
in range(nb_epochs):
348 for data
in dataloader:
350 output = self.
model(d)
351 loss = criterion(d, output)
352 optimizer.zero_grad()
358 """Recalculate latent descriptors and re-admit the training archive.
360 Compute the descriptors before clearing the wrapped archive so
361 records remain available if encoding fails.
364 if not training_inds:
385 def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool =
False) -> Optional[int]:
386 """Check the retraining schedule, then offer one candidate to the wrapped archive."""
389 return self.
container.
add(individual, raise_if_not_added_to_parents)
391 def update(self, iterable: Iterable, ignore_exceptions: bool =
True, issue_warning: bool =
False) -> int:
392 """Check the retraining schedule once, then pass the batch to the wrapped archive."""
394 return self.
container.
update(iterable, ignore_exceptions, issue_warning)
401 def __init__(self, *args, **kwargs):
402 raise NotImplementedError(
"`TorchAE` needs the 'torch' package to be installed and importable.")
406 def __init__(self, *args, **kwargs):
407 raise NotImplementedError(
"`TorchFeatureExtractionContainerDecorator` needs the 'torch' package to be installed and importable.")