likelihood 1.5.7__py3-none-any.whl → 2.0.0__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.
@@ -0,0 +1,895 @@
1
+ from .autoencoders import (
2
+ DataFrame,
3
+ EarlyStopping,
4
+ LoRALayer,
5
+ OneHotEncoder,
6
+ cal_loss_step,
7
+ keras_tuner,
8
+ l2,
9
+ np,
10
+ partial,
11
+ pd,
12
+ sampling,
13
+ suppress_warnings,
14
+ tf,
15
+ train_step,
16
+ )
17
+
18
+
19
+ @tf.keras.utils.register_keras_serializable(package="Custom", name="stabilize_log_var")
20
+ def stabilize_log_var(x):
21
+ return x + 1e-7
22
+
23
+
24
+ @tf.keras.utils.register_keras_serializable(package="Custom", name="sampling_wrapper")
25
+ def sampling_wrapper(args):
26
+ mean, log_var = args
27
+ return sampling(mean, log_var)
28
+
29
+
30
+ @tf.keras.utils.register_keras_serializable(package="Custom", name="sampling_output_shape")
31
+ def sampling_output_shape(input_shapes):
32
+ return input_shapes[0]
33
+
34
+
35
+ class AutoClassifier:
36
+ """
37
+ An auto-classifier model that automatically determines the best classification strategy based on the input data.
38
+
39
+ Parameters
40
+ ----------
41
+ input_shape_parm : `int`
42
+ The shape of the input data.
43
+ num_classes : `int`
44
+ The number of classes in the dataset.
45
+ units : `int`
46
+ The number of neurons in each hidden layer.
47
+ activation : `str`
48
+ The type of activation function to use for the neural network layers.
49
+
50
+ Keyword Arguments:
51
+ ----------
52
+ Additional keyword arguments to pass to the model.
53
+
54
+ classifier_activation : `str`
55
+ The activation function to use for the classifier layer. Default is `softmax`. If the activation function is not a classification function, the model can be used in regression problems.
56
+ num_layers : `int`
57
+ The number of hidden layers in the classifier. Default is 1.
58
+ dropout : `float`
59
+ The dropout rate to use in the classifier. Default is None.
60
+ l2_reg : `float`
61
+ The L2 regularization parameter. Default is 0.0.
62
+ vae_mode : `bool`
63
+ Whether to use variational autoencoder mode. Default is False.
64
+ vae_units : `int`
65
+ The number of units in the variational autoencoder. Default is 2.
66
+ lora_mode : `bool`
67
+ Whether to use LoRA layers. Default is False.
68
+ lora_rank : `int`
69
+ The rank of the LoRA layer. Default is 4.
70
+ """
71
+
72
+ def __init__(self, input_shape_parm, num_classes, units, activation, **kwargs):
73
+ self.input_shape_parm = input_shape_parm
74
+ self.num_classes = num_classes
75
+ self.units = units
76
+ self.activation = activation
77
+
78
+ # Store all configuration parameters
79
+ self.classifier_activation = kwargs.get("classifier_activation", "softmax")
80
+ self.num_layers = kwargs.get("num_layers", 1)
81
+ self.dropout = kwargs.get("dropout", None)
82
+ self.l2_reg = kwargs.get("l2_reg", 0.0)
83
+ self.vae_mode = kwargs.get("vae_mode", False)
84
+ self.vae_units = kwargs.get("vae_units", 2)
85
+ self.lora_mode = kwargs.get("lora_mode", False)
86
+ self.lora_rank = kwargs.get("lora_rank", 4)
87
+
88
+ # Initialize models as None - will be built when needed
89
+ self._encoder = None
90
+ self._decoder = None
91
+ self._classifier = None
92
+ self._main_model = None
93
+
94
+ # Build all models
95
+ self._build_models()
96
+
97
+ def _build_encoder(self):
98
+ """Build the encoder model."""
99
+ if self.vae_mode:
100
+ inputs = tf.keras.Input(shape=(self.input_shape_parm,), name="encoder_input")
101
+ x = tf.keras.layers.Dense(
102
+ units=self.units,
103
+ kernel_regularizer=l2(self.l2_reg),
104
+ kernel_initializer="he_normal",
105
+ name="vae_encoder_dense_1",
106
+ )(inputs)
107
+ x = tf.keras.layers.BatchNormalization(name="vae_encoder_bn_1")(x)
108
+ x = tf.keras.layers.Activation(self.activation, name="vae_encoder_act_1")(x)
109
+ x = tf.keras.layers.Dense(
110
+ units=int(self.units / 2),
111
+ kernel_regularizer=l2(self.l2_reg),
112
+ kernel_initializer="he_normal",
113
+ name="encoder_hidden",
114
+ )(x)
115
+ x = tf.keras.layers.BatchNormalization(name="vae_encoder_bn_2")(x)
116
+ x = tf.keras.layers.Activation(self.activation, name="vae_encoder_act_2")(x)
117
+
118
+ mean = tf.keras.layers.Dense(self.vae_units, name="mean")(x)
119
+ log_var = tf.keras.layers.Dense(self.vae_units, name="log_var")(x)
120
+ log_var = tf.keras.layers.Lambda(stabilize_log_var, name="log_var_stabilized")(log_var)
121
+
122
+ self._encoder = tf.keras.Model(inputs, [mean, log_var], name="vae_encoder")
123
+ else:
124
+ inputs = tf.keras.Input(shape=(self.input_shape_parm,), name="encoder_input")
125
+ x = tf.keras.layers.Dense(
126
+ units=self.units,
127
+ activation=self.activation,
128
+ kernel_regularizer=l2(self.l2_reg),
129
+ name="encoder_dense_1",
130
+ )(inputs)
131
+ outputs = tf.keras.layers.Dense(
132
+ units=int(self.units / 2),
133
+ activation=self.activation,
134
+ kernel_regularizer=l2(self.l2_reg),
135
+ name="encoder_dense_2",
136
+ )(x)
137
+
138
+ self._encoder = tf.keras.Model(inputs, outputs, name="encoder")
139
+
140
+ def _build_decoder(self):
141
+ """Build the decoder model."""
142
+ if self.vae_mode:
143
+ inputs = tf.keras.Input(shape=(self.vae_units,), name="decoder_input")
144
+ x = tf.keras.layers.Dense(
145
+ units=self.units, kernel_regularizer=l2(self.l2_reg), name="vae_decoder_dense_1"
146
+ )(inputs)
147
+ x = tf.keras.layers.BatchNormalization(name="vae_decoder_bn_1")(x)
148
+ x = tf.keras.layers.Activation(self.activation, name="vae_decoder_act_1")(x)
149
+ x = tf.keras.layers.Dense(
150
+ units=self.input_shape_parm,
151
+ kernel_regularizer=l2(self.l2_reg),
152
+ name="vae_decoder_dense_2",
153
+ )(x)
154
+ x = tf.keras.layers.BatchNormalization(name="vae_decoder_bn_2")(x)
155
+ outputs = tf.keras.layers.Activation(self.activation, name="vae_decoder_act_2")(x)
156
+ else:
157
+ inputs = tf.keras.Input(shape=(int(self.units / 2),), name="decoder_input")
158
+ x = tf.keras.layers.Dense(
159
+ units=self.units,
160
+ activation=self.activation,
161
+ kernel_regularizer=l2(self.l2_reg),
162
+ name="decoder_dense_1",
163
+ )(inputs)
164
+ outputs = tf.keras.layers.Dense(
165
+ units=self.input_shape_parm,
166
+ activation=self.activation,
167
+ kernel_regularizer=l2(self.l2_reg),
168
+ name="decoder_dense_2",
169
+ )(x)
170
+
171
+ self._decoder = tf.keras.Model(inputs, outputs, name="decoder")
172
+
173
+ def _build_classifier(self):
174
+ """Build the classifier model."""
175
+ # Input shape is decoded + encoded features
176
+ if self.vae_mode:
177
+ input_dim = self.input_shape_parm + self.vae_units
178
+ else:
179
+ input_dim = self.input_shape_parm + int(self.units / 2)
180
+
181
+ inputs = tf.keras.Input(shape=(input_dim,), name="classifier_input")
182
+ x = inputs
183
+
184
+ # Build hidden layers
185
+ if self.num_layers > 1 and not self.lora_mode:
186
+ for i in range(self.num_layers - 1):
187
+ x = tf.keras.layers.Dense(
188
+ units=self.units,
189
+ activation=self.activation,
190
+ kernel_regularizer=l2(self.l2_reg),
191
+ name=f"classifier_dense_{i+1}",
192
+ )(x)
193
+ if self.dropout:
194
+ x = tf.keras.layers.Dropout(self.dropout, name=f"classifier_dropout_{i+1}")(x)
195
+
196
+ elif self.lora_mode and self.num_layers > 1:
197
+ for i in range(self.num_layers - 1):
198
+ x = LoRALayer(units=self.units, rank=self.lora_rank, name=f"LoRA_{i}")(x)
199
+ x = tf.keras.layers.Activation(self.activation, name=f"lora_activation_{i+1}")(x)
200
+ if self.dropout:
201
+ x = tf.keras.layers.Dropout(self.dropout, name=f"lora_dropout_{i+1}")(x)
202
+
203
+ # Output layer
204
+ outputs = tf.keras.layers.Dense(
205
+ units=self.num_classes,
206
+ activation=self.classifier_activation,
207
+ kernel_regularizer=l2(self.l2_reg),
208
+ name="classifier_output",
209
+ )(x)
210
+
211
+ self._classifier = tf.keras.Model(inputs, outputs, name="classifier")
212
+
213
+ def _build_main_model(self):
214
+ """Build the main model that combines encoder, decoder, and classifier."""
215
+ inputs = tf.keras.Input(shape=(self.input_shape_parm,), name="main_input")
216
+
217
+ # Encoder forward pass
218
+ if self.vae_mode:
219
+ mean, log_var = self._encoder(inputs)
220
+ # Sampling layer
221
+ encoded = tf.keras.layers.Lambda(
222
+ sampling_wrapper, output_shape=sampling_output_shape, name="sampling_layer"
223
+ )([mean, log_var])
224
+ else:
225
+ encoded = self._encoder(inputs)
226
+
227
+ # Decoder forward pass
228
+ decoded = self._decoder(encoded)
229
+
230
+ # Combine decoded and encoded features
231
+ combined = tf.keras.layers.Concatenate(name="combine_features")([decoded, encoded])
232
+
233
+ # Classifier forward pass
234
+ outputs = self._classifier(combined)
235
+
236
+ self._main_model = tf.keras.Model(
237
+ inputs=inputs, outputs=outputs, name="auto_classifier_main"
238
+ )
239
+
240
+ def _build_models(self):
241
+ """Build all component models."""
242
+ self._build_encoder()
243
+ self._build_decoder()
244
+ self._build_classifier()
245
+ self._build_main_model()
246
+
247
+ @property
248
+ def encoder(self):
249
+ """Get the encoder model."""
250
+ return self._encoder
251
+
252
+ @encoder.setter
253
+ def encoder(self, value):
254
+ """Set the encoder model and rebuild main model."""
255
+ self._encoder = value
256
+ if self._decoder and self._classifier:
257
+ self._build_main_model()
258
+
259
+ @property
260
+ def decoder(self):
261
+ """Get the decoder model."""
262
+ return self._decoder
263
+
264
+ @decoder.setter
265
+ def decoder(self, value):
266
+ """Set the decoder model and rebuild main model."""
267
+ self._decoder = value
268
+ if self._encoder and self._classifier:
269
+ self._build_main_model()
270
+
271
+ @property
272
+ def classifier(self):
273
+ """Get the classifier model."""
274
+ return self._classifier
275
+
276
+ @classifier.setter
277
+ def classifier(self, value):
278
+ """Set the classifier model and rebuild main model."""
279
+ self._classifier = value
280
+ if self._encoder and self._decoder:
281
+ self._build_main_model()
282
+
283
+ def train_encoder_decoder(
284
+ self, data, epochs, batch_size, validation_split=0.2, patience=10, **kwargs
285
+ ):
286
+ """
287
+ Trains the encoder and decoder on the input data.
288
+
289
+ Parameters
290
+ ----------
291
+ data : tf.data.Dataset, np.ndarray
292
+ The input data.
293
+ epochs : int
294
+ The number of epochs to train for.
295
+ batch_size : int
296
+ The batch size to use.
297
+ validation_split : float
298
+ The proportion of the dataset to use for validation. Default is 0.2.
299
+ patience : int
300
+ The number of epochs to wait before early stopping. Default is 10.
301
+ """
302
+ verbose = kwargs.get("verbose", True)
303
+ optimizer = kwargs.get("optimizer", tf.keras.optimizers.Adam())
304
+
305
+ # Prepare data
306
+ if isinstance(data, np.ndarray):
307
+ data = tf.data.Dataset.from_tensor_slices(data).batch(batch_size)
308
+ data = data.map(lambda x: tf.cast(x, tf.float32))
309
+
310
+ early_stopping = EarlyStopping(patience=patience)
311
+ train_batches = data.take(int((1 - validation_split) * len(data)))
312
+ val_batches = data.skip(int((1 - validation_split) * len(data)))
313
+
314
+ for epoch in range(epochs):
315
+ train_loss = 0
316
+ val_loss = 0
317
+
318
+ # Training step
319
+ for train_batch in train_batches:
320
+ loss_train = train_step(
321
+ train_batch, self._encoder, self._decoder, optimizer, self.vae_mode
322
+ )
323
+ train_loss = loss_train # Keep last batch loss
324
+
325
+ # Validation step
326
+ for val_batch in val_batches:
327
+ loss_val = cal_loss_step(
328
+ val_batch, self._encoder, self._decoder, self.vae_mode, False
329
+ )
330
+ val_loss = loss_val # Keep last batch loss
331
+
332
+ early_stopping(train_loss)
333
+
334
+ if early_stopping.stop_training:
335
+ if verbose:
336
+ print(f"Early stopping triggered at epoch {epoch}.")
337
+ break
338
+
339
+ if epoch % 10 == 0 and verbose:
340
+ print(
341
+ f"Epoch {epoch}: Train Loss: {train_loss:.6f} Validation Loss: {val_loss:.6f}"
342
+ )
343
+
344
+ self.freeze_encoder_decoder()
345
+
346
+ def freeze_encoder_decoder(self):
347
+ """Freezes the encoder and decoder layers to prevent them from being updated during training."""
348
+ if self._encoder:
349
+ for layer in self._encoder.layers:
350
+ layer.trainable = False
351
+ if self._decoder:
352
+ for layer in self._decoder.layers:
353
+ layer.trainable = False
354
+
355
+ # Rebuild main model to reflect trainability changes
356
+ self._build_main_model()
357
+
358
+ def unfreeze_encoder_decoder(self):
359
+ """Unfreezes the encoder and decoder layers allowing them to be updated during training."""
360
+ if self._encoder:
361
+ for layer in self._encoder.layers:
362
+ layer.trainable = True
363
+ if self._decoder:
364
+ for layer in self._decoder.layers:
365
+ layer.trainable = True
366
+
367
+ # Rebuild main model to reflect trainability changes
368
+ self._build_main_model()
369
+
370
+ def set_encoder_decoder(self, source_model):
371
+ """
372
+ Sets the encoder and decoder layers from another AutoClassifier instance,
373
+ ensuring compatibility in dimensions.
374
+
375
+ Parameters
376
+ ----------
377
+ source_model : AutoClassifier
378
+ The source model to copy the encoder and decoder layers from.
379
+
380
+ Raises
381
+ ------
382
+ ValueError
383
+ If the input shape or units of the source model do not match.
384
+ """
385
+ if not isinstance(source_model, AutoClassifier):
386
+ raise ValueError("Source model must be an instance of AutoClassifier.")
387
+
388
+ if self.input_shape_parm != source_model.input_shape_parm:
389
+ raise ValueError(
390
+ f"Incompatible input shape. Expected {self.input_shape_parm}, got {source_model.input_shape_parm}."
391
+ )
392
+ if self.units != source_model.units:
393
+ raise ValueError(
394
+ f"Incompatible number of units. Expected {self.units}, got {source_model.units}."
395
+ )
396
+
397
+ # Clone and copy weights
398
+ if source_model._encoder:
399
+ self._encoder = tf.keras.models.clone_model(source_model._encoder)
400
+ self._encoder.set_weights(source_model._encoder.get_weights())
401
+
402
+ if source_model._decoder:
403
+ self._decoder = tf.keras.models.clone_model(source_model._decoder)
404
+ self._decoder.set_weights(source_model._decoder.get_weights())
405
+
406
+ # Rebuild main model with new encoder/decoder
407
+ self._build_main_model()
408
+
409
+ # Main model interface methods
410
+ def __call__(self, x, training=None):
411
+ """Forward pass through the model."""
412
+ return self._main_model(x, training=training)
413
+
414
+ def compile(self, *args, **kwargs):
415
+ """Compile the main model."""
416
+ return self._main_model.compile(*args, **kwargs)
417
+
418
+ def fit(self, *args, **kwargs):
419
+ """Fit the main model."""
420
+ return self._main_model.fit(*args, **kwargs)
421
+
422
+ def evaluate(self, *args, **kwargs):
423
+ """Evaluate the main model."""
424
+ return self._main_model.evaluate(*args, **kwargs)
425
+
426
+ def predict(self, *args, **kwargs):
427
+ """Predict using the main model."""
428
+ return self._main_model.predict(*args, **kwargs)
429
+
430
+ def save(self, filepath, **kwargs):
431
+ """
432
+ Save the complete model including all components.
433
+
434
+ Parameters
435
+ ----------
436
+ filepath : str
437
+ Path where to save the model.
438
+ """
439
+ import os
440
+
441
+ # Create directory if it doesn't exist
442
+ os.makedirs(filepath, exist_ok=True)
443
+
444
+ # Save all component models
445
+ self._encoder.save(os.path.join(filepath, "encoder.keras"))
446
+ self._decoder.save(os.path.join(filepath, "decoder.keras"))
447
+ self._classifier.save(os.path.join(filepath, "classifier.keras"))
448
+ self._main_model.save(os.path.join(filepath, "main_model.keras"))
449
+
450
+ # Save configuration
451
+ import json
452
+
453
+ config = {
454
+ "input_shape_parm": self.input_shape_parm,
455
+ "num_classes": self.num_classes,
456
+ "units": self.units,
457
+ "activation": self.activation,
458
+ "classifier_activation": self.classifier_activation,
459
+ "num_layers": self.num_layers,
460
+ "dropout": self.dropout,
461
+ "l2_reg": self.l2_reg,
462
+ "vae_mode": self.vae_mode,
463
+ "vae_units": self.vae_units,
464
+ "lora_mode": self.lora_mode,
465
+ "lora_rank": self.lora_rank,
466
+ }
467
+
468
+ with open(os.path.join(filepath, "config.json"), "w") as f:
469
+ json.dump(config, f, indent=2)
470
+
471
+ @classmethod
472
+ def load(cls, filepath):
473
+ """
474
+ Load a complete model from saved components.
475
+
476
+ Parameters
477
+ ----------
478
+ filepath : str
479
+ Path where the model was saved.
480
+
481
+ Returns
482
+ -------
483
+ AutoClassifier
484
+ The loaded model instance.
485
+ """
486
+ import json
487
+ import os
488
+
489
+ # Load configuration
490
+ with open(os.path.join(filepath, "config.json"), "r") as f:
491
+ config = json.load(f)
492
+
493
+ # Create new instance
494
+ instance = cls(**config)
495
+
496
+ # Load component models
497
+ instance._encoder = tf.keras.models.load_model(os.path.join(filepath, "encoder.keras"))
498
+ instance._decoder = tf.keras.models.load_model(os.path.join(filepath, "decoder.keras"))
499
+ instance._classifier = tf.keras.models.load_model(
500
+ os.path.join(filepath, "classifier.keras")
501
+ )
502
+ instance._main_model = tf.keras.models.load_model(
503
+ os.path.join(filepath, "main_model.keras")
504
+ )
505
+
506
+ return instance
507
+
508
+ # Additional properties and methods for compatibility
509
+ @property
510
+ def weights(self):
511
+ """Get all model weights."""
512
+ return self._main_model.weights
513
+
514
+ def get_weights(self):
515
+ """Get all model weights."""
516
+ return self._main_model.get_weights()
517
+
518
+ def set_weights(self, weights):
519
+ """Set all model weights."""
520
+ return self._main_model.set_weights(weights)
521
+
522
+ @property
523
+ def trainable_variables(self):
524
+ """Get trainable variables."""
525
+ return self._main_model.trainable_variables
526
+
527
+ @property
528
+ def non_trainable_variables(self):
529
+ """Get non-trainable variables."""
530
+ return self._main_model.non_trainable_variables
531
+
532
+ def summary(self, *args, **kwargs):
533
+ """Print model summary."""
534
+ print("=== AutoClassifier Summary ===")
535
+ print("\n--- Encoder ---")
536
+ self._encoder.summary(*args, **kwargs)
537
+ print("\n--- Decoder ---")
538
+ self._decoder.summary(*args, **kwargs)
539
+ print("\n--- Classifier ---")
540
+ self._classifier.summary(*args, **kwargs)
541
+ print("\n--- Main Model ---")
542
+ self._main_model.summary(*args, **kwargs)
543
+
544
+ def get_config(self):
545
+ """Get model configuration."""
546
+ return {
547
+ "input_shape_parm": self.input_shape_parm,
548
+ "num_classes": self.num_classes,
549
+ "units": self.units,
550
+ "activation": self.activation,
551
+ "classifier_activation": self.classifier_activation,
552
+ "num_layers": self.num_layers,
553
+ "dropout": self.dropout,
554
+ "l2_reg": self.l2_reg,
555
+ "vae_mode": self.vae_mode,
556
+ "vae_units": self.vae_units,
557
+ "lora_mode": self.lora_mode,
558
+ "lora_rank": self.lora_rank,
559
+ }
560
+
561
+
562
+ def call_existing_code(
563
+ units: int,
564
+ activation: str,
565
+ threshold: float,
566
+ optimizer: str,
567
+ input_shape_parm: None | int = None,
568
+ num_classes: None | int = None,
569
+ num_layers: int = 1,
570
+ **kwargs,
571
+ ) -> AutoClassifier:
572
+ """
573
+ Calls an existing AutoClassifier instance.
574
+
575
+ Parameters
576
+ ----------
577
+ units : `int`
578
+ The number of neurons in each hidden layer.
579
+ activation : `str`
580
+ The type of activation function to use for the neural network layers.
581
+ threshold : `float`
582
+ The threshold for the classifier.
583
+ optimizer : `str`
584
+ The type of optimizer to use for the neural network layers.
585
+ input_shape_parm : `None` | `int`
586
+ The shape of the input data.
587
+ num_classes : `int`
588
+ The number of classes in the dataset.
589
+ num_layers : `int`
590
+ The number of hidden layers in the classifier. Default is 1.
591
+
592
+ Keyword Arguments:
593
+ ----------
594
+ vae_mode : `bool`
595
+ Whether to use variational autoencoder mode. Default is False.
596
+ vae_units : `int`
597
+ The number of units in the variational autoencoder. Default is 2.
598
+
599
+ Returns
600
+ -------
601
+ `AutoClassifier`
602
+ The AutoClassifier instance.
603
+ """
604
+ dropout = kwargs.get("dropout", None)
605
+ l2_reg = kwargs.get("l2_reg", 0.0)
606
+ vae_mode = kwargs.get("vae_mode", False)
607
+ vae_units = kwargs.get("vae_units", 2)
608
+ model = AutoClassifier(
609
+ input_shape_parm=input_shape_parm,
610
+ num_classes=num_classes,
611
+ units=units,
612
+ activation=activation,
613
+ num_layers=num_layers,
614
+ dropout=dropout,
615
+ l2_reg=l2_reg,
616
+ vae_mode=vae_mode,
617
+ vae_units=vae_units,
618
+ )
619
+ model.compile(
620
+ optimizer=optimizer,
621
+ loss=tf.keras.losses.CategoricalCrossentropy(),
622
+ metrics=[tf.keras.metrics.F1Score(threshold=threshold)],
623
+ )
624
+ return model._main_model
625
+
626
+
627
+ def build_model(
628
+ hp, input_shape_parm: None | int, num_classes: None | int, **kwargs
629
+ ) -> AutoClassifier:
630
+ """Builds a neural network model using Keras Tuner's search algorithm.
631
+
632
+ Parameters
633
+ ----------
634
+ hp : `keras_tuner.HyperParameters`
635
+ The hyperparameters to tune.
636
+ input_shape_parm : `None` | `int`
637
+ The shape of the input data.
638
+ num_classes : `int`
639
+ The number of classes in the dataset.
640
+
641
+ Keyword Arguments:
642
+ ----------
643
+ Additional keyword arguments to pass to the model.
644
+
645
+ hyperparameters : `dict`
646
+ The hyperparameters to set.
647
+
648
+ Returns
649
+ -------
650
+ `keras.Model`
651
+ The neural network model.
652
+ """
653
+ hyperparameters = kwargs.get("hyperparameters", None)
654
+ hyperparameters_keys = hyperparameters.keys() if hyperparameters is not None else []
655
+
656
+ units = (
657
+ hp.Int(
658
+ "units",
659
+ min_value=int(input_shape_parm * 0.2),
660
+ max_value=int(input_shape_parm * 1.5),
661
+ step=2,
662
+ )
663
+ if "units" not in hyperparameters_keys
664
+ else (
665
+ hp.Choice("units", hyperparameters["units"])
666
+ if isinstance(hyperparameters["units"], list)
667
+ else hyperparameters["units"]
668
+ )
669
+ )
670
+ activation = (
671
+ hp.Choice("activation", ["sigmoid", "relu", "tanh", "selu", "softplus", "softsign"])
672
+ if "activation" not in hyperparameters_keys
673
+ else (
674
+ hp.Choice("activation", hyperparameters["activation"])
675
+ if isinstance(hyperparameters["activation"], list)
676
+ else hyperparameters["activation"]
677
+ )
678
+ )
679
+ optimizer = (
680
+ hp.Choice("optimizer", ["sgd", "adam", "adadelta", "rmsprop", "adamax", "adagrad"])
681
+ if "optimizer" not in hyperparameters_keys
682
+ else (
683
+ hp.Choice("optimizer", hyperparameters["optimizer"])
684
+ if isinstance(hyperparameters["optimizer"], list)
685
+ else hyperparameters["optimizer"]
686
+ )
687
+ )
688
+ threshold = (
689
+ hp.Float("threshold", min_value=0.1, max_value=0.9, sampling="log")
690
+ if "threshold" not in hyperparameters_keys
691
+ else (
692
+ hp.Choice("threshold", hyperparameters["threshold"])
693
+ if isinstance(hyperparameters["threshold"], list)
694
+ else hyperparameters["threshold"]
695
+ )
696
+ )
697
+ num_layers = (
698
+ hp.Int("num_layers", min_value=1, max_value=10, step=1)
699
+ if "num_layers" not in hyperparameters_keys
700
+ else (
701
+ hp.Choice("num_layers", hyperparameters["num_layers"])
702
+ if isinstance(hyperparameters["num_layers"], list)
703
+ else hyperparameters["num_layers"]
704
+ )
705
+ )
706
+ dropout = (
707
+ hp.Float("dropout", min_value=0.1, max_value=0.9, sampling="log")
708
+ if "dropout" not in hyperparameters_keys
709
+ else (
710
+ hp.Choice("dropout", hyperparameters["dropout"])
711
+ if isinstance(hyperparameters["dropout"], list)
712
+ else hyperparameters["dropout"]
713
+ )
714
+ )
715
+ l2_reg = (
716
+ hp.Float("l2_reg", min_value=1e-6, max_value=0.1, sampling="log")
717
+ if "l2_reg" not in hyperparameters_keys
718
+ else (
719
+ hp.Choice("l2_reg", hyperparameters["l2_reg"])
720
+ if isinstance(hyperparameters["l2_reg"], list)
721
+ else hyperparameters["l2_reg"]
722
+ )
723
+ )
724
+ vae_mode = (
725
+ hp.Choice("vae_mode", [True, False])
726
+ if "vae_mode" not in hyperparameters_keys
727
+ else hyperparameters["vae_mode"]
728
+ )
729
+
730
+ try:
731
+ vae_units = (
732
+ hp.Int("vae_units", min_value=2, max_value=10, step=1)
733
+ if ("vae_units" not in hyperparameters_keys) and vae_mode
734
+ else (
735
+ hp.Choice("vae_units", hyperparameters["vae_units"])
736
+ if isinstance(hyperparameters["vae_units"], list)
737
+ else hyperparameters["vae_units"]
738
+ )
739
+ )
740
+ except KeyError:
741
+ vae_units = None
742
+
743
+ model = call_existing_code(
744
+ units=units,
745
+ activation=activation,
746
+ threshold=threshold,
747
+ optimizer=optimizer,
748
+ input_shape_parm=input_shape_parm,
749
+ num_classes=num_classes,
750
+ num_layers=num_layers,
751
+ dropout=dropout,
752
+ l2_reg=l2_reg,
753
+ vae_mode=vae_mode,
754
+ vae_units=vae_units,
755
+ )
756
+ return model
757
+
758
+
759
+ @suppress_warnings
760
+ def setup_model(
761
+ data: DataFrame,
762
+ target: str,
763
+ epochs: int,
764
+ train_size: float = 0.7,
765
+ seed=None,
766
+ train_mode: bool = True,
767
+ filepath: str = "./my_dir/best_model",
768
+ method: str = "Hyperband",
769
+ **kwargs,
770
+ ) -> AutoClassifier:
771
+ """Setup model for training and tuning.
772
+
773
+ Parameters
774
+ ----------
775
+ data : `DataFrame`
776
+ The dataset to train the model on.
777
+ target : `str`
778
+ The name of the target column.
779
+ epochs : `int`
780
+ The number of epochs to train the model for.
781
+ train_size : `float`
782
+ The proportion of the dataset to use for training.
783
+ seed : `Any` | `int`
784
+ The random seed to use for reproducibility.
785
+ train_mode : `bool`
786
+ Whether to train the model or not.
787
+ filepath : `str`
788
+ The path to save the best model to.
789
+ method : `str`
790
+ The method to use for hyperparameter tuning. Options are "Hyperband" and "RandomSearch".
791
+
792
+ Keyword Arguments:
793
+ ----------
794
+ Additional keyword arguments to pass to the model.
795
+
796
+ max_trials : `int`
797
+ The maximum number of trials to perform.
798
+ directory : `str`
799
+ The directory to save the model to.
800
+ project_name : `str`
801
+ The name of the project.
802
+ objective : `str`
803
+ The objective to optimize.
804
+ verbose : `bool`
805
+ Whether to print verbose output.
806
+ hyperparameters : `dict`
807
+ The hyperparameters to set.
808
+
809
+ Returns
810
+ -------
811
+ model : `AutoClassifier`
812
+ The trained model.
813
+ """
814
+ max_trials = kwargs.get("max_trials", 10)
815
+ directory = kwargs.get("directory", "./my_dir")
816
+ project_name = kwargs.get("project_name", "get_best")
817
+ objective = kwargs.get("objective", "val_loss")
818
+ verbose = kwargs.get("verbose", True)
819
+ hyperparameters = kwargs.get("hyperparameters", None)
820
+
821
+ X = data.drop(columns=target)
822
+ input_sample = X.sample(1)
823
+ y = data[target]
824
+ assert (
825
+ X.select_dtypes(include=["object"]).empty == True
826
+ ), "Categorical variables within the DataFrame must be encoded, this is done by using the DataFrameEncoder from likelihood."
827
+ validation_split = 1.0 - train_size
828
+
829
+ if train_mode:
830
+ try:
831
+ if (not os.path.exists(directory)) and directory != "./":
832
+ os.makedirs(directory)
833
+ elif directory != "./":
834
+ print(f"Directory {directory} already exists, it will be deleted.")
835
+ rmtree(directory)
836
+ os.makedirs(directory)
837
+ except:
838
+ print("Warning: unable to create directory")
839
+
840
+ y_encoder = OneHotEncoder()
841
+ y = y_encoder.encode(y.to_list())
842
+ X = X.to_numpy()
843
+ input_sample.to_numpy()
844
+ X = np.asarray(X).astype(np.float32)
845
+ input_sample = np.asarray(input_sample).astype(np.float32)
846
+ y = np.asarray(y).astype(np.float32)
847
+
848
+ input_shape_parm = X.shape[1]
849
+ num_classes = y.shape[1]
850
+ global build_model
851
+ build_model = partial(
852
+ build_model,
853
+ input_shape_parm=input_shape_parm,
854
+ num_classes=num_classes,
855
+ hyperparameters=hyperparameters,
856
+ )
857
+
858
+ if method == "Hyperband":
859
+ tuner = keras_tuner.Hyperband(
860
+ hypermodel=build_model,
861
+ objective=objective,
862
+ max_epochs=epochs,
863
+ factor=3,
864
+ directory=directory,
865
+ project_name=project_name,
866
+ seed=seed,
867
+ )
868
+ elif method == "RandomSearch":
869
+ tuner = keras_tuner.RandomSearch(
870
+ hypermodel=build_model,
871
+ objective=objective,
872
+ max_trials=max_trials,
873
+ directory=directory,
874
+ project_name=project_name,
875
+ seed=seed,
876
+ )
877
+
878
+ tuner.search(X, y, epochs=epochs, validation_split=validation_split, verbose=verbose)
879
+ models = tuner.get_best_models(num_models=2)
880
+ best_model = models[0]
881
+ best_model(input_sample)
882
+
883
+ best_model.save(filepath if filepath.endswith(".keras") else filepath + ".keras")
884
+
885
+ if verbose:
886
+ tuner.results_summary()
887
+ else:
888
+ best_model = tf.keras.models.load_model(
889
+ filepath if filepath.endswith(".keras") else filepath + ".keras"
890
+ )
891
+ best_hps = tuner.get_best_hyperparameters(1)[0].values
892
+ vae_mode = best_hps.get("vae_mode", hyperparameters.get("vae_mode", False))
893
+ best_hps["vae_units"] = None if not vae_mode else best_hps["vae_units"]
894
+
895
+ return best_model, pd.DataFrame(best_hps, index=["Value"]).dropna(axis=1)