QDpy
Loading...
Searching...
No Matches
feature_extraction.py
Go to the documentation of this file.
1# type: ignore
2# This file is part of qdpy.
3#
4# qdpy is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Lesser General Public License as
6# published by the Free Software Foundation, either version 3 of
7# the License, or (at your option) any later version.
8#
9# qdpy is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Lesser General Public License for more details.
13#
14# You should have received a copy of the GNU Lesser General Public
15# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
16
17
19
20"""Optional PyTorch autoencoders and latent descriptors."""
21
22__all__ = ["TorchFeatureExtractionContainerDecorator", "TorchAE"]
23
24from functools import partial
25import math
26from typing import Any, Iterable, Optional, Sequence
27from uuid import uuid4
28
29import numpy as np
30from scipy.special import expit
31from sklearn.preprocessing import QuantileTransformer
32
33from qdpy.base import registry
34from qdpy.phenotype import Features, FeaturesLike, Individual, IndividualLike, ScoresDict
35from .base import ContainerDecorator, ContainerLike
36
37
38try:
39 import torch
40 import torch.nn as nn
41 from torch.utils.data import DataLoader
42
43
44 class TorchAE(nn.Module):
45 """Fully connected autoencoder with a separate latent encoder and decoder."""
46 def __init__(self, input_size, latent_size=2):
47 super().__init__()
48 self.input_size = input_size
49 self.latent_size = latent_size
50
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
53
54 self.encoder = nn.Sequential(
55 nn.Linear(input_size, fst_layer_size),
56 nn.ReLU(True),
57 nn.Linear(fst_layer_size, snd_layer_size),
58 nn.ReLU(True),
59 nn.Linear(snd_layer_size, latent_size))
60 self.decoder = nn.Sequential(
61 nn.Linear(latent_size, snd_layer_size),
62 nn.ReLU(True),
63 nn.Linear(snd_layer_size, fst_layer_size),
64 nn.ReLU(True),
65 nn.Linear(fst_layer_size, input_size), nn.Tanh())
66
67 # Initialize weights
68 def init_weights(m):
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)
74
75
76 def forward(self, x):
77 """Encode and reconstruct a batch of score vectors."""
78 x = self.encoder(x)
79 x = self.decoder(x)
80 return x
81
82
83
84
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:
88 row = []
89 while (name := f"{self._score_prefix}{len(row)}") in individual.scores:
90 row.append(individual.scores[name])
91 return Features(row)
92 return self.compute_latent([individual])[0]
93
94
95 @registry.register
97 """Use an autoencoder's latent values as archive descriptors.
98
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.
107
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.
115
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.
120 """
121
122 training_containers: Sequence[ContainerLike]
123 model: Optional[nn.Module]
124 initial_nb_epochs: int
125 nb_epochs: int
126 batch_size: int
127 learning_rate: float
128 training_period: int
129 base_scores: Optional[Sequence[str]]
130 current_loss: float
131
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,
140 *,
141 quantile_transform: bool = False,
142 observation_score: Optional[str] = None,
143 **kwargs: Any) -> None:
144 self.training_containers = training_containers
145 self.model = model
146 self.initial_nb_epochs = initial_nb_epochs
147 self.nb_epochs = nb_epochs
148 self.batch_size = batch_size
149 self.learning_rate = learning_rate
150 self.training_period = training_period
151 if base_scores is not None and observation_score is not None:
152 raise ValueError("Choose either base_scores or observation_score.")
153 self.base_scores = base_scores
154 self.observation_score = observation_score
155 self.quantile_transform = quantile_transform
156 self._quantile_transformer = None
157 self._score_prefix = f"extracted_{uuid4().hex}_"
158 self._descriptor_version = 0
159 self._initial_model_seed = None
160 self.current_loss = np.nan
162 super().__init__(container, **kwargs)
164
165
166
168 lookup = partial(_TorchFeatureExtractionContainerDecorator_get_ind_features, self)
169 self.container.get_ind_features = lookup
170 self.get_ind_features = lookup
171
172
173 def _extracted_score_names(self) -> tuple[str, ...]:
174 return tuple(f"{self._score_prefix}{i}" for i in range(len(self.features_domain)))
175
176
177 def __setstate__(self, state):
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)
188 self.__dict__.update(state)
190
191
192 def _score_tensor(self, inds: Sequence[IndividualLike]) -> torch.Tensor:
193 """Build the encoder input in the configured score order."""
194 if self.observation_score is not None:
195 data = np.stack([ind.scores[self.observation_score] for ind in inds])
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())
199 names = self.base_scores
200 if names is None:
201 names = [name for name in inds[0].scores.keys() if not name.startswith("extracted_")]
202
203 rows = []
204 for ind in inds:
205 scores = ind.scores
206 if type(ind) is not Individual or type(scores) not in (dict, ScoresDict):
207 break
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):
210 break
211 rows.append(row)
212 else:
213 return torch.tensor(rows, dtype=torch.get_default_dtype())
214
215 # Tensor-valued scores can carry gradients. Scalar assignment
216 # preserves their conversion and autograd behavior.
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]
221 return data
222
223
224 def _model_input(self, model, data):
225 parameter = next(model.parameters(), None)
226 return data if parameter is None else data.to(parameter)
227
228
230 def _encode(self, model, data):
231 model.eval()
232 with torch.no_grad():
233 latent = model.encoder(self._model_input(model, data))
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()
237
238
239 def _fit_quantile_transform(self, latent):
240 return QuantileTransformer(n_quantiles=min(len(latent), 1000),
241 subsample=max(10_000, len(latent)), random_state=0).fit(latent)
242
243
244 def _transform_latent(self, latent, transformer):
245 if transformer is not None:
246 return transformer.transform(latent)
247 if self.quantile_transform:
248 return expit(latent)
249 return latent
250
251
252 def _store_descriptors(self, inds, rows):
253 for ind, row in zip(inds, rows):
254 for index, value in enumerate(row):
255 ind.scores[f"{self._score_prefix}{index}"] = value
256 ind.scores[f"{self._score_prefix}version"] = self._descriptor_version
257
258
262 def compute_latent(self, inds: Sequence[IndividualLike], *,
263 fit_transform: bool = False) -> Sequence[FeaturesLike]:
264 """Encode candidates and cache the returned latent descriptors.
265
266 Set ``fit_transform=True`` when encoding the training archive
267 before rebuilding it. Ordinary inference reuses the fitted
268 transform.
269 """
270 if len(inds) == 0:
271 raise ValueError("At least one individual is required to compute latent descriptors.")
272 if self.model is None:
273 self._create_default_model(inds[0])
274 latent = self._encode(self.model, self._score_tensor(inds))
275 if fit_transform and self.quantile_transform:
277 if fit_transform:
278 self._descriptor_version += 1
279 rows = self._transform_latent(latent, self._quantile_transformer).tolist()
280 self._store_descriptors(inds, rows)
281 return [Features(row) for row in rows]
282
283
284 def _create_default_model(self, example_ind: IndividualLike) -> None:
285 if self._initial_model_seed is None:
286 self.model = self._make_default_model(example_ind)
287 else:
288 with torch.random.fork_rng(devices=[]):
289 torch.random.default_generator.manual_seed(self._initial_model_seed)
290 self.model = self._make_default_model(example_ind)
291 self.container.features_score_names = self._extracted_score_names()
292
293
294 def _make_default_model(self, example_ind: IndividualLike):
295 shape = self._input_shape(example_ind)
296 model = TorchAE(math.prod(shape), len(self.features_domain))
297 if self.observation_score is not None:
298 model.encoder.insert(0, nn.Flatten())
299 model.decoder.append(nn.Unflatten(1, shape))
300 return model
301
302
303 def _input_shape(self, example_ind):
304 if self.observation_score is not None:
305 return np.shape(example_ind.scores[self.observation_score])
306 if self.base_scores is not None:
307 return (len(self.base_scores),)
308 return (sum(not name.startswith("extracted_") for name in example_ind.scores),)
309
310 def _get_training_inds(self) -> Sequence[IndividualLike]:
311 if len(self.training_containers) > 0:
312 training_cont_as_lists = [list(p) for p in self.training_containers]
313 all_training_inds = [i for sublist in training_cont_as_lists for i in sublist]
314 return all_training_inds
315 elif len(self.parents) > 0:
316 return self.all_parents_inds()
317 else:
318 return list(self)
319
320
321 def train(self, nb_epochs: int) -> None:
322 """Fit the model to score records for the requested number of epochs.
323
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.
329
330 :raises ValueError: If there are no training records or no epochs.
331 """
332 training_inds = self._get_training_inds()
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:
336 self._create_default_model(training_inds[0])
337 self.model.train()
338
339 data = self._score_tensor(training_inds)
340 dataloader: Any = DataLoader(data, batch_size=self.batch_size, shuffle=True) # type: ignore
341
342 # Create criterion and optimizer
343 criterion = nn.MSELoss()
344 optimizer = torch.optim.Adam(self.model.parameters(), lr=self.learning_rate, weight_decay=1e-5) # type: ignore
345
346 # Train !
347 for _ in range(nb_epochs):
348 for data in dataloader:
349 d = self._model_input(self.model, data)
350 output = self.model(d) # type: ignore
351 loss = criterion(d, output)
352 optimizer.zero_grad()
353 loss.backward()
354 optimizer.step()
355 self.current_loss = loss.item()
356
357 def recompute_features_all_ind(self, update_params=None) -> None:
358 """Recalculate latent descriptors and re-admit the training archive.
359
360 Compute the descriptors before clearing the wrapped archive so
361 records remain available if encoding fails.
362 """
363 training_inds = self._get_training_inds()
364 if not training_inds:
365 return
366 self.compute_latent(training_inds, fit_transform=True)
367 self.container.clear()
368 self.container.update(training_inds, **(update_params or {}))
369
370
375 def _train_and_recompute_if_needed(self, update_params=None):
376 count = len(self._get_training_inds())
377 period = self.training_period
378 if period > 0 and count // period > self._last_training_nb_inds // period:
379 epochs = self.initial_nb_epochs if self._last_training_nb_inds == 0 else self.nb_epochs
380 self.train(epochs)
381 self.recompute_features_all_ind(update_params)
382 self._last_training_nb_inds = count
383
384
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."""
388
389 return self.container.add(individual, raise_if_not_added_to_parents)
390
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."""
393 self._train_and_recompute_if_needed({'ignore_exceptions': ignore_exceptions, 'issue_warning': issue_warning})
394 return self.container.update(iterable, ignore_exceptions, issue_warning)
395
396
397
398
399except ImportError:
400 class TorchAE():
401 def __init__(self, *args, **kwargs):
402 raise NotImplementedError("`TorchAE` needs the 'torch' package to be installed and importable.")
403
404 @registry.register # type: ignore
406 def __init__(self, *args, **kwargs):
407 raise NotImplementedError("`TorchFeatureExtractionContainerDecorator` needs the 'torch' package to be installed and importable.")
408
409
410
411
412
Sequence[IndividualLike] all_parents_inds(self)
Definition base.py:165
None _create_default_model(self, IndividualLike example_ind)
Construct a dense autoencoder from an example record.
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
_model_input(self, model, data)
Move encoder inputs to the model's device and floating-point dtype.
_train_and_recompute_if_needed(self, update_params=None)
Train while the current archive is still available.
_transform_latent(self, latent, transformer)
Apply a fitted transform, or use sigmoid before the first fit.
_init_methods_hooks(self)
Route descriptor lookups through the wrapping encoder.
Optional[int] add(self, IndividualLike individual, bool raise_if_not_added_to_parents=False)
__setstate__(self, state)
Reinstall the descriptor lookup after loading an archive.
tuple[str,...] _extracted_score_names(self)
List the stable names of the wrapped archive's latent coordinates.
Sequence[FeaturesLike] compute_latent(self, Sequence[IndividualLike] inds, *, bool fit_transform=False)
Encode named scores and cache the descriptors used for admission.
_make_default_model(self, IndividualLike example_ind)
Build a default model without installing it or changing the archive.
_fit_quantile_transform(self, latent)
Fit one empirical quantile mapping per latent coordinate.
_encode(self, model, data)
Encode a batch without autograd or training-time layers.
_store_descriptors(self, inds, rows)
Cache the descriptors returned to the underlying archive.
_input_shape(self, example_ind)
Infer the shape of a score vector or array-valued observation.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405