glasspy.predict package

Submodules

glasspy.predict.base module

Module with base classes for building predictive models.

class glasspy.predict.base.AE(hparams: Dict[str, Any])

Bases: LightningModule, Predict

Base class for creating Autoencoders.

Parameters:

hparams

Dictionary with the hyperparemeters of the network. The possible parameters are: + “n_features”: number of input features (required). Must be a positive

integer. Will be the same as the number of output features.

  • ”num_layers”: number of encoder hidden layers (defaults to 1). Must be a positive integer. NOTE: The decoder will have the same number of hidden layers.

  • ”layer_n_size”: number of neurons in layer n of the encoder (replace n for an integer starting at 1, defaults to 10). Must be a positive integer. NOTE: The decoder architecture will be the same as the encoder, but mirrored.

  • ”layer_n_activation”: activation function of layer n of the encoder (replace n for an integer starting at 1, defaults to Tanh). Available values are [“Tanh”, “Sigmoid”, “ReLU”, “LeakyReLU”, “SELU”, “GELU”, “ELU”, “PReLU”, “SiLU”, “Mish”, “Softplus”, “Linear”].

  • ”layer_n_dropout”: dropout of layer n of the encoder (replace n for an integer starting at 1, defaults to False meaning no dropout). Any value between 0 and 1 (or False) is permitted.

  • ”layer_n_batchnorm”: True will use batch normalization in layer n of the encoder, False will not use batch normalization in layer n (replace n for an integer starting at 1, defaults to False meaning no batch normalization).

  • ”loss”: loss function to use for the backpropagation algorithm (defaults to mse). Use mse for mean squared error loss (L2) or huber for a smooth L1 loss.

  • ”optimizer”: optimizer algorithm to use (defaults SGD). Use SGD for stochastic gradient descend, Adam for Adam, or AdamW for weighted Adam.

  • ”lr”: optimizer learning rate (defaults to 1e-4 if optimizer is SGD or 1e-3 if optimizer is Adam or AdamW).

  • ”momentum”: momentum to use when optmizer is SGD (defaults to 0).

  • ”optimizer_Adam_eps”: eps to use for Adam or AdamW optimizers (defaults to 1e-8).

Raises:

NotImplementedError – When the selected hyperparameters is not one of the permited values.

configure_optimizers()

Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple. Optimization with multiple optimizers only works in the manual optimization mode.

Returns:

Any of these 6 options.

  • Single optimizer.

  • List or Tuple of optimizers.

  • Two lists - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple lr_scheduler_config).

  • Dictionary, with an "optimizer" key, and (optionally) a "lr_scheduler" key whose value is a single LR scheduler or lr_scheduler_config.

  • None - Fit will run without any optimizer.

The lr_scheduler_config is a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.

lr_scheduler_config = {
    # REQUIRED: The scheduler instance
    "scheduler": lr_scheduler,
    # The unit of the scheduler's step size, could also be 'step'.
    # 'epoch' updates the scheduler on epoch end whereas 'step'
    # updates it after a optimizer update.
    "interval": "epoch",
    # How many epochs/steps should pass between calls to
    # `scheduler.step()`. 1 corresponds to updating the learning
    # rate after every epoch/step.
    "frequency": 1,
    # Metric to to monitor for schedulers like `ReduceLROnPlateau`
    "monitor": "val_loss",
    # If set to `True`, will enforce that the value specified 'monitor'
    # is available when the scheduler is updated, thus stopping
    # training if not found. If set to `False`, it will only produce a warning
    "strict": True,
    # If using the `LearningRateMonitor` callback to monitor the
    # learning rate progress, this keyword can be used to specify
    # a custom logged name
    "name": None,
}

When there are schedulers in which the .step() method is conditioned on a value, such as the torch.optim.lr_scheduler.ReduceLROnPlateau scheduler, Lightning requires that the lr_scheduler_config contains the keyword "monitor" set to the metric name that the scheduler should be conditioned on.

Metrics can be made available to monitor by simply logging it using self.log('metric_to_track', metric_val) in your LightningModule.

Note

Some things to know:

  • Lightning calls .backward() and .step() automatically in case of automatic optimization.

  • If a learning rate scheduler is specified in configure_optimizers() with key "interval" (default “epoch”) in the scheduler configuration, Lightning will call the scheduler’s .step() method automatically in case of automatic optimization.

  • If you use 16-bit precision (precision=16), Lightning will automatically handle the optimizer.

  • If you use torch.optim.LBFGS, Lightning handles the closure function automatically for you.

  • If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.

  • If you need to control how often the optimizer steps, override the optimizer_step() hook.

distance_from_training()
property domain: Domain
forward(x)

Same as torch.nn.Module.forward().

Parameters:
  • *args – Whatever you decide to pass into the forward method.

  • **kwargs – Keyword arguments are also possible.

Returns:

Your model’s output

get_test_dataset()
get_training_dataset()
get_validation_dataset()
is_within_domain()
learning_curve_train = []
learning_curve_val = []
load_training(path)
predict(x)
save_training(path)
training_epoch_end(outputs)
training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

validation_epoch_end(outputs)
validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.

class glasspy.predict.base.Domain(element: Dict[str, float] = None, compound: Dict[str, float] = None)

Bases: NamedTuple

Simple class to store chemical domain information.

compound: Dict[str, float]

Alias for field number 1

element: Dict[str, float]

Alias for field number 0

class glasspy.predict.base.MLP(**hparams: Dict[str, Any])

Bases: LightningModule, Predict

Base class for creating Multilayer Perceptrons.

Parameters:

hparams

Dictionary with the hyperparemeters of the network. The possible parameters are: + “n_features”: number of input features (required). Must be a positive

integer.

  • ”num_layers”: number of hidden layers (defaults to 1). Must be a positive integer.

  • ”layer_n_size”: number of neurons in layer n (replace n for an integer starting at 1, defaults to 10). Must be a positive integer.

  • ”layer_n_activation”: activation function of layer n (replace n for an integer starting at 1, defaults to Tanh). Available values are [“Tanh”, “Sigmoid”, “ReLU”, “LeakyReLU”, “SELU”, “GELU”, “ELU”, “PReLU”, “SiLU”, “Mish”, “Softplus”, “Linear”].

  • ”layer_n_dropout”: dropout of layer n (replace n for an integer starting at 1, defaults to False meaning no dropout). Any value between 0 and 1 (or False) is permitted.

  • ”layer_n_batchnorm”: True will use batch normalization in layer n, False will not use batch normalization in layer n (replace n for an integer starting at 1, defaults to False meaning no batch normalization).

  • ”loss”: loss function to use for the backpropagation algorithm (defaults to mse). Use mse for mean squared error loss (L2) or huber for a smooth L1 loss.

  • ”optimizer”: optimizer algorithm to use (defaults SGD). Use SGD for stochastic gradient descend, Adam for Adam, or AdamW for weighted Adam.

  • ”lr”: optimizer learning rate (defaults to 1e-4 if optimizer is SGD or 1e-3 if optimizer is Adam or AdamW).

  • ”momentum”: momentum to use when optmizer is SGD (defaults to 0).

  • ”optimizer_Adam_eps”: eps to use for Adam or AdamW optimizers (defaults to 1e-8).

Raises:

NotImplementedError – When the selected hyperparameters is not one of the permited values.

configure_optimizers()

Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple. Optimization with multiple optimizers only works in the manual optimization mode.

Returns:

Any of these 6 options.

  • Single optimizer.

  • List or Tuple of optimizers.

  • Two lists - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple lr_scheduler_config).

  • Dictionary, with an "optimizer" key, and (optionally) a "lr_scheduler" key whose value is a single LR scheduler or lr_scheduler_config.

  • None - Fit will run without any optimizer.

The lr_scheduler_config is a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.

lr_scheduler_config = {
    # REQUIRED: The scheduler instance
    "scheduler": lr_scheduler,
    # The unit of the scheduler's step size, could also be 'step'.
    # 'epoch' updates the scheduler on epoch end whereas 'step'
    # updates it after a optimizer update.
    "interval": "epoch",
    # How many epochs/steps should pass between calls to
    # `scheduler.step()`. 1 corresponds to updating the learning
    # rate after every epoch/step.
    "frequency": 1,
    # Metric to to monitor for schedulers like `ReduceLROnPlateau`
    "monitor": "val_loss",
    # If set to `True`, will enforce that the value specified 'monitor'
    # is available when the scheduler is updated, thus stopping
    # training if not found. If set to `False`, it will only produce a warning
    "strict": True,
    # If using the `LearningRateMonitor` callback to monitor the
    # learning rate progress, this keyword can be used to specify
    # a custom logged name
    "name": None,
}

When there are schedulers in which the .step() method is conditioned on a value, such as the torch.optim.lr_scheduler.ReduceLROnPlateau scheduler, Lightning requires that the lr_scheduler_config contains the keyword "monitor" set to the metric name that the scheduler should be conditioned on.

Metrics can be made available to monitor by simply logging it using self.log('metric_to_track', metric_val) in your LightningModule.

Note

Some things to know:

  • Lightning calls .backward() and .step() automatically in case of automatic optimization.

  • If a learning rate scheduler is specified in configure_optimizers() with key "interval" (default “epoch”) in the scheduler configuration, Lightning will call the scheduler’s .step() method automatically in case of automatic optimization.

  • If you use 16-bit precision (precision=16), Lightning will automatically handle the optimizer.

  • If you use torch.optim.LBFGS, Lightning handles the closure function automatically for you.

  • If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.

  • If you need to control how often the optimizer steps, override the optimizer_step() hook.

distance_from_training()
property domain: Domain
forward(x)

Method used for training the neural network.

Consider using other methods for prediction.

Parameters:

x – Feature tensor.

Returns

Tensor with the predictions.

get_test_dataset()
get_training_dataset()
is_within_domain()
learning_curve_train = []
learning_curve_val = []
load_training(path)
on_train_epoch_end()

Called in the training loop at the very end of the epoch.

To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the LightningModule and access them in this hook:

class MyLightningModule(L.LightningModule):
    def __init__(self):
        super().__init__()
        self.training_step_outputs = []

    def training_step(self):
        loss = ...
        self.training_step_outputs.append(loss)
        return loss

    def on_train_epoch_end(self):
        # do something with all training_step outputs, for example:
        epoch_mean = torch.stack(self.training_step_outputs).mean()
        self.log("training_epoch_mean", epoch_mean)
        # free up the memory
        self.training_step_outputs.clear()
on_validation_epoch_end()

Called in the validation loop at the very end of the epoch.

predict(x)
save_training(path)
test_step(batch, batch_idx)

Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one test dataloader:
def test_step(self, batch, batch_idx): ...


# if you have multiple test dataloaders:
def test_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single test dataset
def test_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'test_loss': loss, 'test_acc': test_acc})

If you pass in multiple test dataloaders, test_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple test dataloaders
def test_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to test you don’t need to implement this method.

Note

When the test_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.

training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.

class glasspy.predict.base.MTL(hparams: Dict[str, Any], num_neurons_per_head=None)

Bases: MLP

Base class for creating Multitask Learning NN.

Parameters:
  • hparams

    Dictionary with the hyperparemeters of the network. The possible parameters are: + “n_features”: number of input features (required). Must be a positive

    integer.

    • ”num_layers”: number of hidden layers (defaults to 1). Must be a positive integer.

    • ”layer_n_size”: number of neurons in layer n (replace n for an integer starting at 1, defaults to 10). Must be a positive integer.

    • ”layer_n_activation”: activation function of layer n (replace n for an integer starting at 1, defaults to Tanh). Available values are [“Tanh”, “Sigmoid”, “ReLU”, “LeakyReLU”, “SELU”, “GELU”, “ELU”, “PReLU”, “SiLU”, “Mish”, “Softplus”, “Linear”].

    • ”layer_n_dropout”: dropout of layer n (replace n for an integer starting at 1, defaults to False meaning no dropout). Any value between 0 and 1 (or False) is permitted.

    • ”layer_n_batchnorm”: True will use batch normalization in layer n, False will not use batch normalization in layer n (replace n for an integer starting at 1, defaults to False meaning no batch normalization).

    • ”loss”: loss function to use for the backpropagation algorithm (defaults to mse). Use mse for mean squared error loss (L2) or huber for a smooth L1 loss.

    • ”optimizer”: optimizer algorithm to use (defaults SGD). Use SGD for stochastic gradient descend, Adam for Adam, or AdamW for weighted Adam.

    • ”lr”: optimizer learning rate (defaults to 1e-4 if optimizer is SGD or 1e-3 if optimizer is Adam or AdamW).

    • ”momentum”: momentum to use when optmizer is SGD (defaults to 0).

    • ”optimizer_Adam_eps”: eps to use for Adam or AdamW optimizers (defaults to 1e-8).

  • num_neurons_per_head – Positive integer or None. The number of neurons for each head of the NN. If None, then the neural network will not have multi-head.

Raises:

NotImplementedError – When the selected hyperparameters is not one of the permited values.

forward_multihead(x)

Method used for training the neural network with multihead.

Consider using other methods for prediction.

Parameters:

x – Feature tensor.

Returns

Tensor with the predictions.

test_step(batch, batch_idx)

Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one test dataloader:
def test_step(self, batch, batch_idx): ...


# if you have multiple test dataloaders:
def test_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single test dataset
def test_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'test_loss': loss, 'test_acc': test_acc})

If you pass in multiple test dataloaders, test_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple test dataloaders
def test_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to test you don’t need to implement this method.

Note

When the test_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.

training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.

class glasspy.predict.base.Predict(**kwargs)

Bases: ABC

Base class for GlassPy predictors.

static MAE(y_true: ndarray, y_pred: ndarray) float

Computes the mean absolute error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

Returns:

The mean absolute error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static MSE(y_true: ndarray, y_pred: ndarray) float

Computes the mean squared error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

Returns:

The mean squared error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static MedAE(y_true: ndarray, y_pred: ndarray) float

Computes the median absolute error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

Returns:

The median absolute error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static PercAE(y_true: ndarray, y_pred: ndarray, q=75) float

Computes the percentile absolute error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

  • q – Percentile to compute.

Returns:

The percentile absolute error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static R2(y_true: ndarray, y_pred: ndarray, one_param: bool = True) float

Computes the coefficient of determination.

Parameters:
  • y_true – 1D array with the true values of y.

  • y_pred – 1D array with the predicted values of y.

  • one_param – Determines the relationship between y_true and y_pred. If ´True´ then it is a relationship with one parameter (y_true = y_pred * c_0 + error). If ´False´ then it is a relationship with two parameters (y_true = y_pred * c_0 + c_1 + error). In most of regression problems, the first case is desired.

Returns:

The coefficient of determination.

static RD(y_true: ndarray, y_pred: ndarray) float

Computes the relative deviation.

Parameters:
  • y_true – 1D array with the true values of y.

  • y_pred – 1D array with the predicted values of y.

Returns:

The relative deviation.

static RMSE(y_true: ndarray, y_pred: ndarray) float

Computes the root mean squared error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

Returns:

The root mean squared error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static RRMSE(y_true: ndarray, y_pred: ndarray) float

Computes the relative root mean squared error.

Parameters:
  • y_true – 1D array with the true values of y.

  • y_pred – 1D array with the predicted values of y.

Returns:

The relative root mean squared error.

abstract property domain
abstract get_test_dataset()
abstract get_training_dataset()
abstract is_within_domain()
abstract predict()

glasspy.predict.models module

Predictive models offered by GlassPy.

class glasspy.predict.models.GlassNet(st_models='default')

Bases: GlassNetMTMH

Hybrid neural network for predicting glass properties.

This hybrid model has a multitask neural network to compute most of the properties and especialized neural networks to predict selected properties.

Parameters:

st_models – List of the properties to use especialized models instead of using the multitask network. If default, then the model uses those properties that performed better than the multitask model.

predict(composition: str | List[float] | List[List[float]] | ndarray | Dict[str, float] | Dict[str, List[float]] | Dict[str, ndarray] | DataFrame | ChemArray, input_cols: List[str] = [], return_dataframe: bool = True)

Makes prediction of properties.

Parameters:
  • composition – Any composition-like object.

  • input_cols – List of strings representing the chemical entities related to each column of composition. Necessary only when composition is a list or array, ignored otherwise.

  • return_dataframe – If True, then returns a pandas DataFrame, else returns an array. Default value is True.

Returns:

Predicted values of properties. Will be a DataFrame if return_dataframe is True, otherwise will be an array.

class glasspy.predict.models.GlassNetMTMH

Bases: _BaseGlassNet, _BaseGlassNetViscosity

Multitask neural network for predicting glass properties.

This is the MT-MH model.

class glasspy.predict.models.GlassNetMTMLP

Bases: _BaseGlassNet, _BaseGlassNetViscosity

Multitask neural network for predicting glass properties.

This is the MT-MLP model.

class glasspy.predict.models.GlassNetSTNN(model_name)

Bases: _BaseGlassNet

Single-task neural network for predicting glass properties.

This is the ST-NN model.

test_step(batch, batch_idx)

Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one test dataloader:
def test_step(self, batch, batch_idx): ...


# if you have multiple test dataloaders:
def test_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single test dataset
def test_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'test_loss': loss, 'test_acc': test_acc})

If you pass in multiple test dataloaders, test_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple test dataloaders
def test_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to test you don’t need to implement this method.

Note

When the test_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.

training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.

class glasspy.predict.models.ViscNet

Bases: _BaseViscNet

ViscNet predictor of viscosity and viscosity parameters.

ViscNet is a physics-informed neural network that has the MYEGA [1] viscosity equation embedded in it. See Ref. [2] for the original publication.

References

[1] J.C. Mauro, Y. Yue, A.J. Ellison, P.K. Gupta, D.C. Allan, Viscosity of

glass-forming liquids., Proceedings of the National Academy of Sciences of the United States of America. 106 (2009) 19780–19784. https://doi.org/10.1073/pnas.0911705106.

[2] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

absolute_features = [('ElectronAffinity', 'std1'), ('FusionEnthalpy', 'std1'), ('GSenergy_pa', 'std1'), ('GSmagmom', 'std1'), ('NdUnfilled', 'std1'), ('NfValence', 'std1'), ('NpUnfilled', 'std1'), ('atomic_radius_rahm', 'std1'), ('c6_gb', 'std1'), ('lattice_constant', 'std1'), ('mendeleev_number', 'std1'), ('num_oxistates', 'std1'), ('nvalence', 'std1'), ('vdw_radius_alvarez', 'std1'), ('vdw_radius_uff', 'std1'), ('zeff', 'std1')]
featurizer(composition: str | List[float] | List[List[float]] | ndarray | Dict[str, float] | Dict[str, List[float]] | Dict[str, ndarray] | DataFrame | ChemArray, input_cols: List[str] = []) ndarray

Compute the chemical features used for viscosity prediction.

Parameters:
  • composition – Any composition like object.

  • input_cols – List of strings representing the chemical entities related to each column of composition. Necessary only when composition is a list or array, ignored otherwise.

Returns:

Array with the computed chemical features

log_viscosity_fun(T, log_eta_inf, Tg, m)

Computes the base-10 logarithm of viscosity using the MYEGA equation.

parameters_range = {'Tg': [400, 1400], 'log_eta_inf': [-18, 5], 'm': [10, 130]}
state_dict_path = PosixPath('/home/daniel/data/Git/Work/glasspy/glasspy/predict/models/ViscNet_SD.p')
weighted_features = [('FusionEnthalpy', 'min'), ('GSbandgap', 'max'), ('GSmagmom', 'mean'), ('GSvolume_pa', 'max'), ('MiracleRadius', 'std1'), ('NValence', 'max'), ('NValence', 'min'), ('NdUnfilled', 'max'), ('NdValence', 'max'), ('NsUnfilled', 'max'), ('SpaceGroupNumber', 'max'), ('SpaceGroupNumber', 'min'), ('atomic_radius', 'max'), ('atomic_volume', 'max'), ('c6_gb', 'max'), ('c6_gb', 'min'), ('max_ionenergy', 'min'), ('num_oxistates', 'max'), ('nvalence', 'min')]
x_mean = tensor([5.7542e+01, 2.2090e+01, 2.0236e+00, 3.6861e-02, 3.2621e-01, 1.4419e+00,         2.0165e+00, 3.4408e+01, 1.2353e+03, 1.4793e+00, 4.2045e+01, 8.4131e-01,         2.3045e+00, 4.7985e+01, 5.6984e+01, 1.1146e+00, 9.2186e-02, 2.1363e-01,         2.2581e-04, 5.8150e+00, 1.2964e+01, 3.7008e+00, 1.3743e-01, 1.8370e-02,         3.2303e-01, 7.1325e-02, 5.0019e+01, 4.3720e+00, 3.6446e+01, 8.4037e+00,         2.0281e+02, 7.5614e+00, 1.2259e+02, 6.7183e-01, 1.0508e-01])
x_std = tensor([7.6421e+00, 4.7181e+00, 4.5828e-01, 1.6873e-01, 9.7033e-01, 2.7695e+00,         3.3153e-01, 6.4521e+00, 6.3392e+02, 4.0606e-01, 1.1777e+01, 2.8130e-01,         7.9214e-01, 7.5883e+00, 1.1335e+01, 2.8823e-01, 4.4787e-02, 1.1219e-01,         1.2392e-03, 1.1634e+00, 2.9514e+00, 4.7246e-01, 3.1958e-01, 8.8973e-02,         6.7548e-01, 6.2869e-02, 1.0004e+01, 2.7434e+00, 1.9245e+00, 3.4735e-01,         1.2475e+02, 3.2668e+00, 1.5287e+02, 7.3511e-02, 1.6188e-01])
class glasspy.predict.models.ViscNetHuber

Bases: ViscNet

ViscNet-Huber predictor of viscosity and viscosity parameters.

ViscNet-Huber is a physics-informed neural network that has the MYEGA [1] viscosity equation embedded in it. The difference between this model and ViscNet is the loss function: this model has a robust smooth-L1 loss function, while ViscNet has a MSE (L2) loss function. See Ref. [2] for the original publication.

References

[1] J.C. Mauro, Y. Yue, A.J. Ellison, P.K. Gupta, D.C. Allan, Viscosity of

glass-forming liquids., Proceedings of the National Academy of Sciences of the United States of America. 106 (2009) 19780–19784. https://doi.org/10.1073/pnas.0911705106.

[2] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

class glasspy.predict.models.ViscNetVFT

Bases: ViscNet

ViscNet-VFT predictor of viscosity and viscosity parameters.

ViscNet-VFT is a physics-informed neural network that has the VFT [1-3] viscosity equation embedded in it. See Ref. [4] for the original publication.

References

[1] H. Vogel, Das Temperatureabhängigketsgesetz der Viskosität von

Flüssigkeiten, Physikalische Zeitschrift. 22 (1921) 645–646.

[2] G.S. Fulcher, Analysis of recent measurements of the viscosity of

glasses, Journal of the American Ceramic Society. 8 (1925) 339–355. https://doi.org/10.1111/j.1151-2916.1925.tb16731.x.

[3] G. Tammann, W. Hesse, Die Abhängigkeit der Viscosität von der

Temperatur bie unterkühlten Flüssigkeiten, Z. Anorg. Allg. Chem. 156 (1926) 245–257. https://doi.org/10.1002/zaac.19261560121.

[4] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

log_viscosity_fun(T, log_eta_inf, Tg, m)

Computes the base-10 logarithm of viscosity using the VFT equation.

Reference:
[1] H. Vogel, Das Temperatureabhängigketsgesetz der Viskosität von

Flüssigkeiten, Physikalische Zeitschrift. 22 (1921) 645–646.

[2] G.S. Fulcher, Analysis of recent measurements of the viscosity of

glasses, Journal of the American Ceramic Society. 8 (1925) 339–355. https://doi.org/10.1111/j.1151-2916.1925.tb16731.x.

[3] G. Tammann, W. Hesse, Die Abhängigkeit der Viscosität von der

Temperatur bie unterkühlten Flüssigkeiten, Z. Anorg. Allg. Chem. 156 (1926) 245–257. https://doi.org/10.1002/zaac.19261560121.

Module contents

class glasspy.predict.GlassNet(st_models='default')

Bases: GlassNetMTMH

Hybrid neural network for predicting glass properties.

This hybrid model has a multitask neural network to compute most of the properties and especialized neural networks to predict selected properties.

Parameters:

st_models – List of the properties to use especialized models instead of using the multitask network. If default, then the model uses those properties that performed better than the multitask model.

predict(composition: str | List[float] | List[List[float]] | ndarray | Dict[str, float] | Dict[str, List[float]] | Dict[str, ndarray] | DataFrame | ChemArray, input_cols: List[str] = [], return_dataframe: bool = True)

Makes prediction of properties.

Parameters:
  • composition – Any composition-like object.

  • input_cols – List of strings representing the chemical entities related to each column of composition. Necessary only when composition is a list or array, ignored otherwise.

  • return_dataframe – If True, then returns a pandas DataFrame, else returns an array. Default value is True.

Returns:

Predicted values of properties. Will be a DataFrame if return_dataframe is True, otherwise will be an array.

class glasspy.predict.GlassNetMTMH

Bases: _BaseGlassNet, _BaseGlassNetViscosity

Multitask neural network for predicting glass properties.

This is the MT-MH model.

class glasspy.predict.GlassNetMTMLP

Bases: _BaseGlassNet, _BaseGlassNetViscosity

Multitask neural network for predicting glass properties.

This is the MT-MLP model.

class glasspy.predict.GlassNetSTNN(model_name)

Bases: _BaseGlassNet

Single-task neural network for predicting glass properties.

This is the ST-NN model.

test_step(batch, batch_idx)

Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one test dataloader:
def test_step(self, batch, batch_idx): ...


# if you have multiple test dataloaders:
def test_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single test dataset
def test_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'test_loss': loss, 'test_acc': test_acc})

If you pass in multiple test dataloaders, test_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple test dataloaders
def test_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to test you don’t need to implement this method.

Note

When the test_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.

training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.

class glasspy.predict.ViscNet

Bases: _BaseViscNet

ViscNet predictor of viscosity and viscosity parameters.

ViscNet is a physics-informed neural network that has the MYEGA [1] viscosity equation embedded in it. See Ref. [2] for the original publication.

References

[1] J.C. Mauro, Y. Yue, A.J. Ellison, P.K. Gupta, D.C. Allan, Viscosity of

glass-forming liquids., Proceedings of the National Academy of Sciences of the United States of America. 106 (2009) 19780–19784. https://doi.org/10.1073/pnas.0911705106.

[2] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

absolute_features = [('ElectronAffinity', 'std1'), ('FusionEnthalpy', 'std1'), ('GSenergy_pa', 'std1'), ('GSmagmom', 'std1'), ('NdUnfilled', 'std1'), ('NfValence', 'std1'), ('NpUnfilled', 'std1'), ('atomic_radius_rahm', 'std1'), ('c6_gb', 'std1'), ('lattice_constant', 'std1'), ('mendeleev_number', 'std1'), ('num_oxistates', 'std1'), ('nvalence', 'std1'), ('vdw_radius_alvarez', 'std1'), ('vdw_radius_uff', 'std1'), ('zeff', 'std1')]
allow_zero_length_dataloader_with_multiple_devices: bool
featurizer(composition: str | List[float] | List[List[float]] | ndarray | Dict[str, float] | Dict[str, List[float]] | Dict[str, ndarray] | DataFrame | ChemArray, input_cols: List[str] = []) ndarray

Compute the chemical features used for viscosity prediction.

Parameters:
  • composition – Any composition like object.

  • input_cols – List of strings representing the chemical entities related to each column of composition. Necessary only when composition is a list or array, ignored otherwise.

Returns:

Array with the computed chemical features

log_viscosity_fun(T, log_eta_inf, Tg, m)

Computes the base-10 logarithm of viscosity using the MYEGA equation.

parameters_range = {'Tg': [400, 1400], 'log_eta_inf': [-18, 5], 'm': [10, 130]}
prepare_data_per_node: bool
state_dict_path = PosixPath('/home/daniel/data/Git/Work/glasspy/glasspy/predict/models/ViscNet_SD.p')
training: bool
weighted_features = [('FusionEnthalpy', 'min'), ('GSbandgap', 'max'), ('GSmagmom', 'mean'), ('GSvolume_pa', 'max'), ('MiracleRadius', 'std1'), ('NValence', 'max'), ('NValence', 'min'), ('NdUnfilled', 'max'), ('NdValence', 'max'), ('NsUnfilled', 'max'), ('SpaceGroupNumber', 'max'), ('SpaceGroupNumber', 'min'), ('atomic_radius', 'max'), ('atomic_volume', 'max'), ('c6_gb', 'max'), ('c6_gb', 'min'), ('max_ionenergy', 'min'), ('num_oxistates', 'max'), ('nvalence', 'min')]
x_mean = tensor([5.7542e+01, 2.2090e+01, 2.0236e+00, 3.6861e-02, 3.2621e-01, 1.4419e+00,         2.0165e+00, 3.4408e+01, 1.2353e+03, 1.4793e+00, 4.2045e+01, 8.4131e-01,         2.3045e+00, 4.7985e+01, 5.6984e+01, 1.1146e+00, 9.2186e-02, 2.1363e-01,         2.2581e-04, 5.8150e+00, 1.2964e+01, 3.7008e+00, 1.3743e-01, 1.8370e-02,         3.2303e-01, 7.1325e-02, 5.0019e+01, 4.3720e+00, 3.6446e+01, 8.4037e+00,         2.0281e+02, 7.5614e+00, 1.2259e+02, 6.7183e-01, 1.0508e-01])
x_std = tensor([7.6421e+00, 4.7181e+00, 4.5828e-01, 1.6873e-01, 9.7033e-01, 2.7695e+00,         3.3153e-01, 6.4521e+00, 6.3392e+02, 4.0606e-01, 1.1777e+01, 2.8130e-01,         7.9214e-01, 7.5883e+00, 1.1335e+01, 2.8823e-01, 4.4787e-02, 1.1219e-01,         1.2392e-03, 1.1634e+00, 2.9514e+00, 4.7246e-01, 3.1958e-01, 8.8973e-02,         6.7548e-01, 6.2869e-02, 1.0004e+01, 2.7434e+00, 1.9245e+00, 3.4735e-01,         1.2475e+02, 3.2668e+00, 1.5287e+02, 7.3511e-02, 1.6188e-01])
class glasspy.predict.ViscNetHuber

Bases: ViscNet

ViscNet-Huber predictor of viscosity and viscosity parameters.

ViscNet-Huber is a physics-informed neural network that has the MYEGA [1] viscosity equation embedded in it. The difference between this model and ViscNet is the loss function: this model has a robust smooth-L1 loss function, while ViscNet has a MSE (L2) loss function. See Ref. [2] for the original publication.

References

[1] J.C. Mauro, Y. Yue, A.J. Ellison, P.K. Gupta, D.C. Allan, Viscosity of

glass-forming liquids., Proceedings of the National Academy of Sciences of the United States of America. 106 (2009) 19780–19784. https://doi.org/10.1073/pnas.0911705106.

[2] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

class glasspy.predict.ViscNetVFT

Bases: ViscNet

ViscNet-VFT predictor of viscosity and viscosity parameters.

ViscNet-VFT is a physics-informed neural network that has the VFT [1-3] viscosity equation embedded in it. See Ref. [4] for the original publication.

References

[1] H. Vogel, Das Temperatureabhängigketsgesetz der Viskosität von

Flüssigkeiten, Physikalische Zeitschrift. 22 (1921) 645–646.

[2] G.S. Fulcher, Analysis of recent measurements of the viscosity of

glasses, Journal of the American Ceramic Society. 8 (1925) 339–355. https://doi.org/10.1111/j.1151-2916.1925.tb16731.x.

[3] G. Tammann, W. Hesse, Die Abhängigkeit der Viscosität von der

Temperatur bie unterkühlten Flüssigkeiten, Z. Anorg. Allg. Chem. 156 (1926) 245–257. https://doi.org/10.1002/zaac.19261560121.

[4] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

log_viscosity_fun(T, log_eta_inf, Tg, m)

Computes the base-10 logarithm of viscosity using the VFT equation.

Reference:
[1] H. Vogel, Das Temperatureabhängigketsgesetz der Viskosität von

Flüssigkeiten, Physikalische Zeitschrift. 22 (1921) 645–646.

[2] G.S. Fulcher, Analysis of recent measurements of the viscosity of

glasses, Journal of the American Ceramic Society. 8 (1925) 339–355. https://doi.org/10.1111/j.1151-2916.1925.tb16731.x.

[3] G. Tammann, W. Hesse, Die Abhängigkeit der Viscosität von der

Temperatur bie unterkühlten Flüssigkeiten, Z. Anorg. Allg. Chem. 156 (1926) 245–257. https://doi.org/10.1002/zaac.19261560121.