Skip to content

Training Data

physXAI.preprocessing.training_data

Classes

TrainingDataGeneric

Bases: ABC

A generic container class to hold all data related to a machine learning model's lifecycle. This includes training, validation, and test datasets (as NumPy arrays), model predictions, evaluation metrics, training history, and training time.

Source code in physXAI/preprocessing/training_data.py
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 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
class TrainingDataGeneric(ABC):
    """
     A generic container class to hold all data related to a machine learning model's lifecycle.
    This includes training, validation, and test datasets (as NumPy arrays),
    model predictions, evaluation metrics, training history, and training time.
    """

    def __init__(self):
        self.X_train = None
        self.X_val = None
        self.X_test = None
        self.y_train = None
        self.y_val = None
        self.y_test = None

        self.y_train_pred = None
        self.y_val_pred = None
        self.y_test_pred = None

        self.file_path = None

        self.training_record = None

        self.training_time = None

        self.metrics = None

        self.columns = None

    def add_training_record(self, data):
        """
        Stores the training history or record.
        For Keras models, this is typically the `History` object returned by `model.fit()`.

        Args:
            data: The training record data.
        """
        self.training_record = data

    def add_predictions(self, y_train_pred: np.array, y_val_pred: np.array, y_test_pred: np.array):
        """
        Stores the model's predictions for the training, validation, and test sets.

        Args:
            y_train_pred (np.ndarray): Predictions on the training set.
            y_val_pred (Optional[np.ndarray]): Predictions on the validation set.
            y_test_pred (np.ndarray): Predictions on the test set.
        """

        self.y_train_pred = y_train_pred
        self.y_val_pred = y_val_pred
        self.y_test_pred = y_test_pred

    def add_metrics(self, metrics):
        """
        Stores the calculated evaluation metrics.

        Args:
            metrics: The metrics object.
        """

        self.metrics = metrics

    def add_training_time(self, time: float):
        """
        Stores the duration of the model training process.

        Args:
            time (float): The training time in seconds.
        """
        self.training_time = time

    def add_file_path(self, path: str):
        self.file_path = path

    @abstractmethod
    def get_config(self) -> dict:
        pass

    @property
    @abstractmethod
    def X_train_single(self):
        pass

    @property
    @abstractmethod
    def y_train_single(self):
        pass

    @property
    @abstractmethod
    def X_val_single(self):
        pass

    @property
    @abstractmethod
    def y_val_single(self):
        pass

    @property
    @abstractmethod
    def X_test_single(self):
        pass

    @property
    @abstractmethod
    def y_test_single(self):
        pass

    @property
    @abstractmethod
    def y_train_pred_single(self):
        pass

    @property
    @abstractmethod
    def y_val_pred_single(self):
        pass

    @property
    @abstractmethod
    def y_test_pred_single(self):
        pass
Attributes
X_train = None instance-attribute
X_val = None instance-attribute
X_test = None instance-attribute
y_train = None instance-attribute
y_val = None instance-attribute
y_test = None instance-attribute
y_train_pred = None instance-attribute
y_val_pred = None instance-attribute
y_test_pred = None instance-attribute
file_path = None instance-attribute
training_record = None instance-attribute
training_time = None instance-attribute
metrics = None instance-attribute
columns = None instance-attribute
X_train_single abstractmethod property
y_train_single abstractmethod property
X_val_single abstractmethod property
y_val_single abstractmethod property
X_test_single abstractmethod property
y_test_single abstractmethod property
y_train_pred_single abstractmethod property
y_val_pred_single abstractmethod property
y_test_pred_single abstractmethod property
Functions
__init__()
Source code in physXAI/preprocessing/training_data.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def __init__(self):
    self.X_train = None
    self.X_val = None
    self.X_test = None
    self.y_train = None
    self.y_val = None
    self.y_test = None

    self.y_train_pred = None
    self.y_val_pred = None
    self.y_test_pred = None

    self.file_path = None

    self.training_record = None

    self.training_time = None

    self.metrics = None

    self.columns = None
add_training_record(data)

Stores the training history or record. For Keras models, this is typically the History object returned by model.fit().

Parameters:

Name Type Description Default
data

The training record data.

required
Source code in physXAI/preprocessing/training_data.py
35
36
37
38
39
40
41
42
43
def add_training_record(self, data):
    """
    Stores the training history or record.
    For Keras models, this is typically the `History` object returned by `model.fit()`.

    Args:
        data: The training record data.
    """
    self.training_record = data
add_predictions(y_train_pred: np.array, y_val_pred: np.array, y_test_pred: np.array)

Stores the model's predictions for the training, validation, and test sets.

Parameters:

Name Type Description Default
y_train_pred ndarray

Predictions on the training set.

required
y_val_pred Optional[ndarray]

Predictions on the validation set.

required
y_test_pred ndarray

Predictions on the test set.

required
Source code in physXAI/preprocessing/training_data.py
45
46
47
48
49
50
51
52
53
54
55
56
57
def add_predictions(self, y_train_pred: np.array, y_val_pred: np.array, y_test_pred: np.array):
    """
    Stores the model's predictions for the training, validation, and test sets.

    Args:
        y_train_pred (np.ndarray): Predictions on the training set.
        y_val_pred (Optional[np.ndarray]): Predictions on the validation set.
        y_test_pred (np.ndarray): Predictions on the test set.
    """

    self.y_train_pred = y_train_pred
    self.y_val_pred = y_val_pred
    self.y_test_pred = y_test_pred
add_metrics(metrics)

Stores the calculated evaluation metrics.

Parameters:

Name Type Description Default
metrics

The metrics object.

required
Source code in physXAI/preprocessing/training_data.py
59
60
61
62
63
64
65
66
67
def add_metrics(self, metrics):
    """
    Stores the calculated evaluation metrics.

    Args:
        metrics: The metrics object.
    """

    self.metrics = metrics
add_training_time(time: float)

Stores the duration of the model training process.

Parameters:

Name Type Description Default
time float

The training time in seconds.

required
Source code in physXAI/preprocessing/training_data.py
69
70
71
72
73
74
75
76
def add_training_time(self, time: float):
    """
    Stores the duration of the model training process.

    Args:
        time (float): The training time in seconds.
    """
    self.training_time = time
add_file_path(path: str)
Source code in physXAI/preprocessing/training_data.py
78
79
def add_file_path(self, path: str):
    self.file_path = path
get_config() -> dict abstractmethod
Source code in physXAI/preprocessing/training_data.py
81
82
83
@abstractmethod
def get_config(self) -> dict:
    pass

TrainingData

Bases: TrainingDataGeneric

A container class to hold all data related to a single-step machine learning model's lifecycle. This includes training, validation, and test datasets (as NumPy arrays), model predictions, evaluation metrics, training history, and training time.

Source code in physXAI/preprocessing/training_data.py
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
class TrainingData(TrainingDataGeneric):
    """
    A container class to hold all data related to a single-step machine learning model's lifecycle.
    This includes training, validation, and test datasets (as NumPy arrays),
    model predictions, evaluation metrics, training history, and training time.
    """

    def __init__(self, X_train: np.array, X_val: np.array, X_test: np.array,
                 y_train: np.array, y_val: np.array, y_test: np.array,
                 columns: list[str]):
        """
        Initializes the TrainingData object.

        Args:
            X_train (np.ndarray): NumPy array of training features.
            X_val (Optional[np.ndarray]): NumPy array of validation features. Can be None.
            X_test (np.ndarray): NumPy array of test features.
            y_train (np.ndarray): NumPy array of training target values.
            y_val (Optional[np.ndarray]): NumPy array of validation target values. Can be None.
            y_test (np.ndarray): NumPy array of test target values.
            columns (List[str]): List of input feature names (columns of X).
        """
        super().__init__()

        self.X_train: np.ndarray = X_train
        self.X_val: np.ndarray = X_val
        self.X_test: np.ndarray = X_test
        self.y_train: np.ndarray = y_train
        self.y_val: np.ndarray = y_val
        self.y_test: np.ndarray = y_test
        self.columns: list[str] = columns

    def get_config(self) -> dict:
        config = {
            'file_path': self.file_path,
            'metrics': self.metrics.get_config() if self.metrics is not None else None,
            'training_time': self.training_time,
            'training_record': self.training_record.history if self.training_record is not None else None,
        }
        return config

    @property
    def X_train_single(self):
        return self.X_train

    @property
    def y_train_single(self):
        return self.y_train

    @property
    def X_val_single(self):
        return self.X_val

    @property
    def y_val_single(self):
        return self.y_val

    @property
    def X_test_single(self):
        return self.X_test

    @property
    def y_test_single(self):
        return self.y_test

    @property
    def y_train_pred_single(self):
        return self.y_train_pred

    @property
    def y_val_pred_single(self):
        return self.y_val_pred

    @property
    def y_test_pred_single(self):
        return self.y_test_pred
Attributes
X_train: np.ndarray = X_train instance-attribute
X_val: np.ndarray = X_val instance-attribute
X_test: np.ndarray = X_test instance-attribute
y_train: np.ndarray = y_train instance-attribute
y_val: np.ndarray = y_val instance-attribute
y_test: np.ndarray = y_test instance-attribute
columns: list[str] = columns instance-attribute
X_train_single property
y_train_single property
X_val_single property
y_val_single property
X_test_single property
y_test_single property
y_train_pred_single property
y_val_pred_single property
y_test_pred_single property
Functions
__init__(X_train: np.array, X_val: np.array, X_test: np.array, y_train: np.array, y_val: np.array, y_test: np.array, columns: list[str])

Initializes the TrainingData object.

Parameters:

Name Type Description Default
X_train ndarray

NumPy array of training features.

required
X_val Optional[ndarray]

NumPy array of validation features. Can be None.

required
X_test ndarray

NumPy array of test features.

required
y_train ndarray

NumPy array of training target values.

required
y_val Optional[ndarray]

NumPy array of validation target values. Can be None.

required
y_test ndarray

NumPy array of test target values.

required
columns List[str]

List of input feature names (columns of X).

required
Source code in physXAI/preprocessing/training_data.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def __init__(self, X_train: np.array, X_val: np.array, X_test: np.array,
             y_train: np.array, y_val: np.array, y_test: np.array,
             columns: list[str]):
    """
    Initializes the TrainingData object.

    Args:
        X_train (np.ndarray): NumPy array of training features.
        X_val (Optional[np.ndarray]): NumPy array of validation features. Can be None.
        X_test (np.ndarray): NumPy array of test features.
        y_train (np.ndarray): NumPy array of training target values.
        y_val (Optional[np.ndarray]): NumPy array of validation target values. Can be None.
        y_test (np.ndarray): NumPy array of test target values.
        columns (List[str]): List of input feature names (columns of X).
    """
    super().__init__()

    self.X_train: np.ndarray = X_train
    self.X_val: np.ndarray = X_val
    self.X_test: np.ndarray = X_test
    self.y_train: np.ndarray = y_train
    self.y_val: np.ndarray = y_val
    self.y_test: np.ndarray = y_test
    self.columns: list[str] = columns
get_config() -> dict
Source code in physXAI/preprocessing/training_data.py
163
164
165
166
167
168
169
170
def get_config(self) -> dict:
    config = {
        'file_path': self.file_path,
        'metrics': self.metrics.get_config() if self.metrics is not None else None,
        'training_time': self.training_time,
        'training_record': self.training_record.history if self.training_record is not None else None,
    }
    return config

TrainingDataMultiStep

Bases: TrainingDataGeneric

A container class for data related to multi-step forecasting models, typically using tf.data.Dataset objects for handling windowed sequence data. It also extracts NumPy array versions of these datasets for easier inspection or use with libraries that expect NumPy arrays.

Source code in physXAI/preprocessing/training_data.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
class TrainingDataMultiStep(TrainingDataGeneric):
    """
    A container class for data related to multi-step forecasting models,
    typically using tf.data.Dataset objects for handling windowed sequence data.
    It also extracts NumPy array versions of these datasets for easier inspection or
    use with libraries that expect NumPy arrays.
    """

    def __init__(self, train_ds, val_ds, test_ds, columns: list[str], output: list[str], init_columns: list[str]):
        """
        Initializes the TrainingDataMultiStep object.

        Args:
            train_ds (tf.data.Dataset): TensorFlow Dataset for training.
                                        Each element is typically a tuple (features, labels).
                                        Features can be a single tensor or a tuple (e.g., (main_input, warmup_input)).
            val_ds (Optional[tf.data.Dataset]): TensorFlow Dataset for validation. Can be None.
            test_ds (tf.data.Dataset): TensorFlow Dataset for testing.
            columns (List[str]): List of input feature names (columns of X).
            output  (str): (List of) Name(s) of the output column(s).
        """
        super().__init__()

        self.train_ds = train_ds
        self.val_ds = val_ds
        self.test_ds = test_ds

        self.columns = columns
        self.output = output
        self.init_columns = init_columns

        # Extract numpy objects
        self._Xy_train()
        if self.val_ds is not None:
            self._Xy_val()
        else:
            self.X_val = None
            self.y_val = None
        self._Xy_test()

        self.single_step_metrics = None

    def add_single_step_metrics(self, metrics):
        """
        Stores the calculated evaluation single step metrics.

        Args:
            metrics: The metrics object.
        """

        self.single_step_metrics = metrics

    def _Xy_train(self):
        """
        Converts the training tf.data.Dataset into NumPy arrays.
        """
        y_values = []
        X_values = []
        X_values_init = []
        for X, y in self.train_ds:
            if isinstance(X, tuple):
                # With warmup
                X_values.append(X[0].numpy())
                X_values_init.append(X[1].numpy())
            else:
                # Without warmup
                X_values.append(X.numpy())
            y_values.append(y.numpy())
        self.X_train = np.concatenate(X_values)
        if len(X_values_init) > 0:
            self.X_train = (self.X_train, np.concatenate(X_values_init))
        self.y_train = np.concatenate(y_values)

    def _Xy_val(self):
        """
        Converts the validation tf.data.Dataset into NumPy arrays.
        """
        y_values = []
        X_values = []
        X_values_init = []
        for X, y in self.val_ds:
            if isinstance(X, tuple):
                X_values.append(X[0].numpy())
                X_values_init.append(X[1].numpy())
            else:
                X_values.append(X.numpy())
            y_values.append(y.numpy())
        self.X_val = np.concatenate(X_values)
        if len(X_values_init) > 0:
            self.X_val = (self.X_val, np.concatenate(X_values_init))
        self.y_val = np.concatenate(y_values)

    def _Xy_test(self):
        """
        Converts the test tf.data.Dataset into NumPy arrays.
        """
        y_values = []
        X_values = []
        X_values_init = []
        for X, y in self.test_ds:
            if isinstance(X, tuple):
                X_values.append(X[0].numpy())
                X_values_init.append(X[1].numpy())
            else:
                X_values.append(X.numpy())
            y_values.append(y.numpy())
        self.X_test = np.concatenate(X_values)
        if len(X_values_init) > 0:
            self.X_test = (self.X_test, np.concatenate(X_values_init))
        self.y_test = np.concatenate(y_values)

    def get_config(self) -> dict:
        config = {
            'file_path': self.file_path,
            'metrics': self.metrics.get_config() if self.metrics is not None else None,
            'training_time': self.training_time,
            'training_record': self.training_record.history if self.training_record is not None else None,
        }
        return config

    @property
    def X_train_single(self):
        if isinstance(self.X_train, tuple):
            X = self.X_train[0]
        else:
            X = self.X_train
        return X.reshape(-1, *X.shape[2:])

    @property
    def X_train_init(self):
        if isinstance(self.X_train, tuple):
            X = self.X_train[1]
        else:
            X = None
        return X

    @property
    def X_train_features(self):
        if isinstance(self.X_train, tuple):
            X = self.X_train[0]
        else:
            X = self.X_train
        return X

    @property
    def y_train_single(self):
        return self.y_train.reshape(-1, *self.y_train.shape[2:])

    @property
    def X_val_single(self):
        if isinstance(self.X_val, tuple):
            X = self.X_val[0]
        else:
            X = self.X_val
        return X.reshape(-1, *X.shape[2:]) if X is not None else None

    @property
    def X_val_init(self):
        if isinstance(self.X_val, tuple):
            X = self.X_val[1]
        else:
            X = None
        return X

    @property
    def X_val_features(self):
        if isinstance(self.X_val, tuple):
            X = self.X_val[0]
        else:
            X = self.X_val
        return X

    @property
    def y_val_single(self):
        return self.y_val.reshape(-1, *self.y_val.shape[2:]) if self.y_val is not None else None

    @property
    def X_test_single(self):
        if isinstance(self.X_test, tuple):
            X = self.X_test[0]
        else:
            X = self.X_test
        return X.reshape(-1, *X.shape[2:])

    @property
    def X_test_init(self):
        if isinstance(self.X_test, tuple):
            X = self.X_test[1]
        else:
            X = None
        return X

    @property
    def X_test_features(self):
        if isinstance(self.X_test, tuple):
            X = self.X_test[0]
        else:
            X = self.X_test
        return X

    @property
    def y_test_single(self):
        return self.y_test.reshape(-1, *self.y_test.shape[2:])

    @property
    def y_train_pred_single(self):
        if self.y_train_pred.ndim == 3:
            return self.y_train_pred.reshape(-1, *self.y_train_pred.shape[2:])
        else:
            return self.y_train_pred

    @property
    def y_val_pred_single(self):
        if self.y_val_pred.ndim == 3:
            return self.y_val_pred.reshape(-1, *self.y_val_pred.shape[2:]) if self.y_val_pred is not None else None
        else:
            return self.y_val_pred

    @property
    def y_test_pred_single(self):
        if self.y_test_pred.ndim == 3:
            return self.y_test_pred.reshape(-1, *self.y_test_pred.shape[2:])
        else:
            return self.y_test_pred
Attributes
train_ds = train_ds instance-attribute
val_ds = val_ds instance-attribute
test_ds = test_ds instance-attribute
columns = columns instance-attribute
output = output instance-attribute
init_columns = init_columns instance-attribute
X_val = None instance-attribute
y_val = None instance-attribute
single_step_metrics = None instance-attribute
X_train_single property
X_train_init property
X_train_features property
y_train_single property
X_val_single property
X_val_init property
X_val_features property
y_val_single property
X_test_single property
X_test_init property
X_test_features property
y_test_single property
y_train_pred_single property
y_val_pred_single property
y_test_pred_single property
Functions
__init__(train_ds, val_ds, test_ds, columns: list[str], output: list[str], init_columns: list[str])

Initializes the TrainingDataMultiStep object.

Parameters:

Name Type Description Default
train_ds Dataset

TensorFlow Dataset for training. Each element is typically a tuple (features, labels). Features can be a single tensor or a tuple (e.g., (main_input, warmup_input)).

required
val_ds Optional[Dataset]

TensorFlow Dataset for validation. Can be None.

required
test_ds Dataset

TensorFlow Dataset for testing.

required
columns List[str]

List of input feature names (columns of X).

required
output (str

(List of) Name(s) of the output column(s).

required
Source code in physXAI/preprocessing/training_data.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def __init__(self, train_ds, val_ds, test_ds, columns: list[str], output: list[str], init_columns: list[str]):
    """
    Initializes the TrainingDataMultiStep object.

    Args:
        train_ds (tf.data.Dataset): TensorFlow Dataset for training.
                                    Each element is typically a tuple (features, labels).
                                    Features can be a single tensor or a tuple (e.g., (main_input, warmup_input)).
        val_ds (Optional[tf.data.Dataset]): TensorFlow Dataset for validation. Can be None.
        test_ds (tf.data.Dataset): TensorFlow Dataset for testing.
        columns (List[str]): List of input feature names (columns of X).
        output  (str): (List of) Name(s) of the output column(s).
    """
    super().__init__()

    self.train_ds = train_ds
    self.val_ds = val_ds
    self.test_ds = test_ds

    self.columns = columns
    self.output = output
    self.init_columns = init_columns

    # Extract numpy objects
    self._Xy_train()
    if self.val_ds is not None:
        self._Xy_val()
    else:
        self.X_val = None
        self.y_val = None
    self._Xy_test()

    self.single_step_metrics = None
add_single_step_metrics(metrics)

Stores the calculated evaluation single step metrics.

Parameters:

Name Type Description Default
metrics

The metrics object.

required
Source code in physXAI/preprocessing/training_data.py
251
252
253
254
255
256
257
258
259
def add_single_step_metrics(self, metrics):
    """
    Stores the calculated evaluation single step metrics.

    Args:
        metrics: The metrics object.
    """

    self.single_step_metrics = metrics
get_config() -> dict
Source code in physXAI/preprocessing/training_data.py
320
321
322
323
324
325
326
327
def get_config(self) -> dict:
    config = {
        'file_path': self.file_path,
        'metrics': self.metrics.get_config() if self.metrics is not None else None,
        'training_time': self.training_time,
        'training_record': self.training_record.history if self.training_record is not None else None,
    }
    return config