Training Deep Learning Probabilistic Models¶
BayesianTrainer ¶
BayesianTrainer(model, objective, custom_loss_function=None, optimizer=None, lr_scheduler=None, callbacks=None, metrics=None, verbose=1, seed=1, **kwargs)
Bases: BaseBayesianTrainer
Class to set the of attributes that will be used during the training process.
Both the Bayesian models and the Trainer in this repo are based on the paper: Weight Uncertainty in Neural Networks.
Parameters:
-
model
(BaseBayesianModel
) –An object of class
BaseBayesianModel
. See theModel Components
section here in the docs. -
objective
(str
) –Defines the objective, loss or cost function.
Param aliases:loss_function
,loss_fn
,loss
,cost_function
,cost_fn
,cost
Possible values are: 'binary', 'multiclass', 'regression' -
custom_loss_function
(Optional[Module]
, default:None
) –If none of the loss functions available suits the user, it is possible to pass a custom loss function. See for example
pytorch_widedeep.losses.FocalLoss
for the required structure of the object or the Examples folder in the repo. -
optimizer
(Optional[Optimizer]
, default:None
) –An instance of Pytorch's
Optimizer
object(e.g.torch.optim.Adam ()
). if no optimizer is passed it will default toAdamW
. -
lr_scheduler
(Optional[LRScheduler]
, default:None
) –An instance of Pytorch's
LRScheduler
object (e.gtorch.optim.lr_scheduler.StepLR(opt, step_size=5)
). -
callbacks
(Optional[List[Callback]]
, default:None
) –List with
Callback
objects. The three callbacks available inpytorch-widedeep
are:LRHistory
,ModelCheckpoint
andEarlyStopping
. This can also be a custom callback. Seepytorch_widedeep.callbacks.Callback
or the Examples folder in the repo. -
metrics
(Optional[Union[List[Metric], List[Metric]]]
, default:None
) –- List of objects of type
Metric
. Metrics available are:Accuracy
,Precision
,Recall
,FBetaScore
,F1Score
andR2Score
. This can also be a custom metric as long as it is an object of typeMetric
. Seepytorch_widedeep.metrics.Metric
or the Examples folder in the repo - List of objects of type
torchmetrics.Metric
. This can be any metric from torchmetrics library Examples classification-metrics>_. It can also be a torchmetric custom metric as long as it is an object of type
Metric. See
the instructions
- List of objects of type
-
verbose
(int
, default:1
) –Setting it to 0 will print nothing during training.
-
seed
(int
, default:1
) –Random seed to be used internally for train_test_split
Other Parameters:
-
**kwargs
–Other infrequently used arguments that can also be passed as kwargs are:
-
device:
str
string indicating the device. One of 'cpu' or 'gpu' -
num_workers:
int
number of workers to be used internally by the data loaders -
class_weight:
List[float]
This is theweight
orpos_weight
parameter inCrossEntropyLoss
andBCEWithLogitsLoss
, depending on whether -
reducelronplateau_criterion:
str
This sets the criterion that will be used by the lr scheduler to take a step: One of 'loss' or 'metric'. The ReduceLROnPlateau learning rate is a bit particular.
-
Attributes:
-
cyclic_lr
(bool
) –Attribute that indicates if the lr_scheduler is cyclic_lr (i.e.
CyclicLR
orOneCycleLR
). SeePytorch schedulers <https://pytorch.org/docs/stable/optim.html>
_.
Source code in pytorch_widedeep/training/bayesian_trainer.py
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 |
|
fit ¶
fit(X_tab, target, X_tab_val=None, target_val=None, val_split=None, n_epochs=1, validation_freq=1, batch_size=32, n_train_samples=2, n_val_samples=2)
Fit method.
Parameters:
-
X_tab
(ndarray
) –tabular dataset
-
target
(ndarray
) –target values
-
X_tab_val
(Optional[ndarray]
, default:None
) –validation data
-
target_val
(Optional[ndarray]
, default:None
) –validation target values
-
val_split
(Optional[float]
, default:None
) –An alterative to passing the validation set is to use a train/val split fraction via
val_split
-
n_epochs
(int
, default:1
) –number of epochs
-
validation_freq
(int
, default:1
) –epochs validation frequency
-
batch_size
(int
, default:32
) –batch size
-
n_train_samples
(int
, default:2
) –number of samples to average over during the training process. See Weight Uncertainty in Neural Networks for details.
-
n_val_samples
(int
, default:2
) –number of samples to average over during the validation process. See Weight Uncertainty in Neural Networks for details.
Source code in pytorch_widedeep/training/bayesian_trainer.py
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 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 |
|
predict ¶
predict(X_tab, n_samples=5, return_samples=False, batch_size=256)
Returns the predictions
Parameters:
-
X_tab
(ndarray
) –tabular dataset
-
n_samples
(int
, default:5
) –number of samples that will be either returned or averaged to produce an overal prediction
-
return_samples
(bool
, default:False
) –Boolean indicating whether the n samples will be averaged or directly returned
-
batch_size
(int
, default:256
) –batch size
Returns:
-
np.ndarray:
–array with the predictions
Source code in pytorch_widedeep/training/bayesian_trainer.py
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 |
|
predict_proba ¶
predict_proba(X_tab, n_samples=5, return_samples=False, batch_size=256)
Returns the predicted probabilities
Parameters:
-
X_tab
(ndarray
) –tabular dataset
-
n_samples
(int
, default:5
) –number of samples that will be either returned or averaged to produce an overal prediction
-
return_samples
(bool
, default:False
) –Boolean indicating whether the n samples will be averaged or directly returned
-
batch_size
(int
, default:256
) –batch size
Returns:
-
ndarray
–array with the probabilities per class
Source code in pytorch_widedeep/training/bayesian_trainer.py
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 |
|
save ¶
save(path, save_state_dict=False, model_filename='bayesian_model.pt')
Saves the model, training and evaluation history to disk
The Trainer
class is built so that it 'just' trains a model. With
that in mind, all the torch related parameters (such as optimizers or
learning rate schedulers) have to be defined externally and then
passed to the Trainer
. As a result, the Trainer
does not
generate any attribute or additional data products that need to be
saved other than the model
object itself, which can be saved as
any other torch model (e.g. torch.save(model, path)
).
Parameters:
-
path
(str
) –path to the directory where the model and the feature importance attribute will be saved.
-
save_state_dict
(bool
, default:False
) –Boolean indicating whether to save directly the model or the model's state dictionary
-
model_filename
(str
, default:'bayesian_model.pt'
) –filename where the model weights will be store
Source code in pytorch_widedeep/training/bayesian_trainer.py
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 |
|