platypush.plugins.tensorflow

class platypush.plugins.tensorflow.TensorflowPlugin(workdir: Optional[str] = None, **kwargs)[source]

This plugin can be used to create, train, load and make predictions with TensorFlow-compatible machine learning models.

Triggers:

Requires:

  • numpy (pip install numpy)
  • pandas (pip install pandas) (optional, for CSV parsing)
  • tensorflow (pip install 'tensorflow>=2.0')
  • keras (pip install keras)
__init__(workdir: Optional[str] = None, **kwargs)[source]
Parameters:workdir – Working directory for TensorFlow, where models will be stored (default: PLATYPUSH_WORKDIR/tensorflow).
create_network(name: str, layers: List[Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b80435518>, Dict[str, Any]]], input_names: Optional[List[str]] = None, output_names: Optional[List[str]] = None, optimizer: Optional[str] = 'rmsprop', loss: Union[str, List[str], Dict[str, str], None] = None, metrics: Union[str, List[Union[str, List[str]]], Dict[str, Union[str, List[str]]], None] = None, loss_weights: Union[List[float], Dict[str, float], None] = None, sample_weight_mode: Union[str, List[str], Dict[str, str], None] = None, weighted_metrics: Optional[List[str]] = None, target_tensors=None, **kwargs) → Dict[str, Any][source]

Create a neural network TensorFlow Keras model.

Parameters:
  • name – Name of the model.
  • layers – List of layers. Example:
[
  // Input flatten layer with 10 units
  {
    "type": "Flatten",
    "input_shape": [10, 10]
  },

  // Dense hidden layer with 500 units
  {
    "type": "Dense",
    "units": 500,
    "activation": "relu"
  },

  // Dense hidden layer with 100 units
  {
    "type": "Dense",
    "units": 100,
    "activation": "relu"
  },

  // Dense output layer with 2 units (labels) and ``softmax`` activation function
  {
    "type": "Dense",
    "units": 2,
    "activation": "softmax"
  }
]
Parameters:
  • input_names – List of names for the input units (default: TensorFlow name auto-assign logic).
  • output_names – List of labels for the output units (default: TensorFlow name auto-assign logic).
  • optimizer – Optimizer, see <https://keras.io/optimizers/> (default: rmsprop).
  • loss – Loss function, see <https://keras.io/losses/>. An objective function is any callable with the signature scalar_loss = fn(y_true, y_pred). If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses (default: None).
  • metrics – List of metrics to be evaluated by the model during training and testing. Typically you will use metrics=['accuracy']. To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}. You can also pass a list (len = len(outputs)) of lists of metrics such as metrics=[['accuracy'], ['accuracy', 'mse']] or metrics=['accuracy', ['accuracy', 'mse']]. Default: ['accuracy'].
  • loss_weights – Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the weighted sum of all individual losses, weighted by the loss_weights coefficients. If a list, it is expected to have a 1:1 mapping to the model’s outputs. If a tensor, it is expected to map output names (strings) to scalar coefficients.
  • sample_weight_mode – If you need to do time-step-wise sample weighting (2D weights), set this to "temporal". None defaults to sample-wise weights (1D). If the model has multiple outputs, you can use a different sample_weight_mode on each output by passing a dictionary or a list of modes.
  • weighted_metrics – List of metrics to be evaluated and weighted by sample_weight or class_weight during training and testing.
  • target_tensors – By default, Keras will create placeholders for the model’s target, which will be fed with the target data during training. If instead you would like to use your own target tensors (in turn, Keras will not expect external numpy data for these targets at training time), you can specify them via the target_tensors argument. It can be a single tensor (for a single-output model), a list of tensors, or a dict mapping output names to target tensors.
  • kwargs – Extra arguments to pass to Model.compile().
Returns:

The model configuration, as a dict. Example:

{
  "name": "test_model",
  "layers": [
    {
      "class_name": "Flatten",
      "config": {
        "name": "flatten",
        "trainable": true,
        "batch_input_shape": [
          null,
          10
        ],
        "dtype": "float32",
        "data_format": "channels_last"
      }
    },
    {
      "class_name": "Dense",
      "config": {
        "name": "dense",
        "trainable": true,
        "dtype": "float32",
        "units": 100,
        "activation": "relu",
        "use_bias": true,
        "kernel_initializer": {
          "class_name": "GlorotUniform",
          "config": {
            "seed": null
          }
        },
        "bias_initializer": {
          "class_name": "Zeros",
          "config": {}
        },
        "kernel_regularizer": null,
        "bias_regularizer": null,
        "activity_regularizer": null,
        "kernel_constraint": null,
        "bias_constraint": null
      }
    },
    {
      "class_name": "Dense",
      "config": {
        "name": "dense_1",
        "trainable": true,
        "dtype": "float32",
        "units": 50,
        "activation": "relu",
        "use_bias": true,
        "kernel_initializer": {
          "class_name": "GlorotUniform",
          "config": {
            "seed": null
          }
        },
        "bias_initializer": {
          "class_name": "Zeros",
          "config": {}
        },
        "kernel_regularizer": null,
        "bias_regularizer": null,
        "activity_regularizer": null,
        "kernel_constraint": null,
        "bias_constraint": null
      }
    },
    {
      "class_name": "Dense",
      "config": {
        "name": "dense_2",
        "trainable": true,
        "dtype": "float32",
        "units": 2,
        "activation": "softmax",
        "use_bias": true,
        "kernel_initializer": {
          "class_name": "GlorotUniform",
          "config": {
            "seed": null
          }
        },
        "bias_initializer": {
          "class_name": "Zeros",
          "config": {}
        },
        "kernel_regularizer": null,
        "bias_regularizer": null,
        "activity_regularizer": null,
        "kernel_constraint": null,
        "bias_constraint": null
      }
    }
  ]
}
create_regression(name: str, units: int = 1, input_names: Optional[List[str]] = None, output_names: Optional[List[str]] = None, activation: str = 'linear', use_bias: bool = True, kernel_initializer: str = 'glorot_uniform', bias_initializer: str = 'zeros', kernel_regularizer: Optional[str] = None, bias_regularizer: Optional[str] = None, optimizer: Optional[str] = 'rmsprop', loss: Union[str, List[str], Dict[str, str], None] = 'mse', metrics: Union[str, List[Union[str, List[str]]], Dict[str, Union[str, List[str]]], None] = None, loss_weights: Union[List[float], Dict[str, float], None] = None, sample_weight_mode: Union[str, List[str], Dict[str, str], None] = None, weighted_metrics: Optional[List[str]] = None, target_tensors=None, **kwargs) → Dict[str, Any][source]

Create a linear/logistic regression model.

Parameters:
  • name – Name of the model.
  • units – Output dimension (default: 1).
  • input_names – List of names for the input units (default: TensorFlow name auto-assign logic).
  • output_names – List of labels for the output units (default: TensorFlow name auto-assign logic).
  • activation – Activation function to be used (default: None).
  • use_bias – Whether to calculate the bias/intercept for this model. If set to False, no bias/intercept will be used in calculations, e.g., the data is already centered (default: True).
  • kernel_initializer – Initializer for the kernel weights matrices (default: glorot_uniform).
  • bias_initializer – Initializer for the bias vector (default: zeros).
  • kernel_regularizer – Regularizer for kernel vectors (default: None).
  • bias_regularizer – Regularizer for bias vectors (default: None).
  • optimizer – Optimizer, see <https://keras.io/optimizers/> (default: rmsprop).
  • loss – Loss function, see <https://keras.io/losses/>. An objective function is any callable with the signature scalar_loss = fn(y_true, y_pred). If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses (default: mse, mean squared error).
  • metrics – List of metrics to be evaluated by the model during training and testing. Typically you will use metrics=['accuracy']. To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}. You can also pass a list (len = len(outputs)) of lists of metrics such as metrics=[['accuracy'], ['accuracy', 'mse']] or metrics=['accuracy', ['accuracy', 'mse']]. Default: ['mae', 'mse'].
  • loss_weights – Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the weighted sum of all individual losses, weighted by the loss_weights coefficients. If a list, it is expected to have a 1:1 mapping to the model’s outputs. If a tensor, it is expected to map output names (strings) to scalar coefficients.
  • sample_weight_mode – If you need to do time-step-wise sample weighting (2D weights), set this to "temporal". None defaults to sample-wise weights (1D). If the model has multiple outputs, you can use a different sample_weight_mode on each output by passing a dictionary or a list of modes.
  • weighted_metrics – List of metrics to be evaluated and weighted by sample_weight or class_weight during training and testing.
  • target_tensors – By default, Keras will create placeholders for the model’s target, which will be fed with the target data during training. If instead you would like to use your own target tensors (in turn, Keras will not expect external numpy data for these targets at training time), you can specify them via the target_tensors argument. It can be a single tensor (for a single-output model), a list of tensors, or a dict mapping output names to target tensors.
  • kwargs – Extra arguments to pass to Model.compile().
Returns:

Configuration of the model, as a dict. Example:

{
  "name": "test_regression_model",
  "trainable": true,
  "dtype": "float32",
  "units": 1,
  "activation": "linear",
  "use_bias": true,
  "kernel_initializer": {
    "class_name": "GlorotUniform",
    "config": {
      "seed": null
    }
  },
  "bias_initializer": {
    "class_name": "Zeros",
    "config": {}
  },
  "kernel_regularizer": null,
  "bias_regularizer": null
}
evaluate(model: str, inputs: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b80bf55c0>, Iterable], outputs: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b80bf5a20>, Iterable, None] = None, batch_size: Optional[int] = None, verbose: int = 1, sample_weight: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b80bf57f0>, Iterable, None] = None, steps: Optional[int] = None, max_queue_size: int = 10, workers: int = 1, use_multiprocessing: bool = False) → Union[Dict[str, float], List[float]][source]

Returns the loss value and metrics values for the model in test model.

Parameters:
  • model – Name of the existing model to be trained.
  • inputs

    Input data. It can be:

    • A numpy array (or array-like), or a list of arrays in case the model has multiple inputs.
    • A TensorFlow tensor, or a list of tensors in case the model has multiple inputs.
    • A dict mapping input names to the corresponding array/tensors, if the model has named inputs.
    • A tf.data dataset. Should return a tuple of either (inputs, targets) or (inputs, targets, sample_weights).
    • A generator or keras.utils.Sequence returning (inputs, targets) or (inputs, targets, sample weights).
    • A string that points to a file. Supported formats:
      • CSV with header (.csv extension``)
      • Numpy raw or compressed files (.npy or .npz extension)
      • Image files
      • An HTTP URL pointing to one of the file types listed above
      • Directories with images. If inputs points to a directory of images then the following conventions are followed:
        • The folder must contain exactly as many subfolders as the output units of your model. If the model has output_labels then those subfolders should be named as the output labels. Each subfolder will contain training examples that match the associated label (e.g. positive will contain all the positive images and negative all the negative images).
        • outputs doesn’t have to be specified.
  • outputs – Target data. Like the input data x, it can be a numpy array (or array-like) or TensorFlow tensor(s). It should be consistent with x (you cannot have Numpy inputs and tensor targets, or inversely). If x is a dataset, generator, or keras.utils.Sequence instance, y should not be specified (since targets will be obtained from x).
  • batch_size – Number of samples per gradient update. If unspecified, batch_size will default to 32. Do not specify the batch_size if your data is in the form of symbolic tensors, datasets, generators, or keras.utils.Sequence instances (since they generate batches).
  • verbose – Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment).
  • sample_weight – Optional iterable/numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) numpy array/iterable with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every time step of every sample. In this case you should make sure to specify sample_weight_mode="temporal" in compile(). This argument is not supported when x is a dataset, generator, or keras.utils.Sequence instance, instead provide the sample_weights as the third element of x.
  • steps – Total number of steps (batches of samples) before declaring the evaluation round finished. Ignored with the default value of None. If x is a tf.data dataset and steps is None, ‘evaluate’ will run until the dataset is exhausted. This argument is not supported with array inputs.
  • max_queue_size – Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue. If unspecified, max_queue_size will default to 10.
  • workers – Used for generator or keras.utils.Sequence input only. Maximum number of processes to spin up when using process-based threading. If unspecified, workers will default to 1. If 0, will execute the generator on the main thread.
  • use_multiprocessing – Used for generator or keras.utils.Sequence input only. If True, use process-based threading. If unspecified, use_multiprocessing will default to False. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can’t be passed easily to children processes.
Returns:

{test_metric: metric_value} dictionary if the metrics_names of the model are specified, otherwise a list with the result test metrics (loss is usually the first value).

load(model: str, reload: bool = False) → Dict[str, Any][source]

(Re)-load a model from the file system.

Parameters:
  • model – Name of the model. Must be a folder name stored under <workdir>/models.
  • reload – If True, the model will be reloaded from the filesystem even if it’s been already loaded, otherwise the model currently in memory will be kept (default: False).
Returns:

The model configuration.

predict(model: str, inputs: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b80bf5278>, Iterable], batch_size: Optional[int] = None, verbose: int = 0, steps: Optional[int] = None, max_queue_size: int = 10, workers: int = 1, use_multiprocessing: bool = False) → platypush.message.response.tensorflow.TensorflowPredictResponse[source]

Generates output predictions for the input samples.

Parameters:
  • model – Name of the existing model to be trained.
  • inputs

    Input data. It can be:

    • A numpy array (or array-like), or a list of arrays in case the model has multiple inputs.
    • A TensorFlow tensor, or a list of tensors in case the model has multiple inputs.
    • A dict mapping input names to the corresponding array/tensors, if the model has named inputs.
    • A tf.data dataset. Should return a tuple of either (inputs, targets) or (inputs, targets, sample_weights).
    • A generator or keras.utils.Sequence returning (inputs, targets) or (inputs, targets, sample weights).
    • A string that points to a file. Supported formats:
      • CSV with header (.csv extension``)
      • Numpy raw or compressed files (.npy or .npz extension)
      • Image files
      • An HTTP URL pointing to one of the file types listed above
  • batch_size – Number of samples per gradient update. If unspecified, batch_size will default to 32. Do not specify the batch_size if your data is in the form of symbolic tensors, datasets, generators, or keras.utils.Sequence instances (since they generate batches).
  • verbose – Verbosity mode, 0 or 1.
  • steps – Total number of steps (batches of samples) before declaring the prediction round finished. Ignored with the default value of None. If x is a tf.data dataset and steps is None, predict will run until the input dataset is exhausted.
  • max_queue_size – Integer. Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue (default: 10).
  • workers – Used for generator or keras.utils.Sequence input only. Maximum number of processes to spin up when using process-based threading. If unspecified, workers will default to 1. If 0, will execute the generator on the main thread.
  • use_multiprocessing – Used for generator or keras.utils.Sequence input only. If True, use process-based threading. If unspecified, use_multiprocessing will default to False. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can’t be passed easily to children processes.
Returns:

platypush.message.response.tensorflow.TensorflowPredictResponse. Format:

  • For regression models with no output labels specified: values will contain the output vector:
{
    "values": [[3.1415]]
}
  • For regression models with output labels specified: values will be a list of {label -> value} maps:
{
    "values": [
        {
            "x": 42.0,
            "y": 43.0
        }
    ]
}
  • For neural networks: values will contain the list of the output vector like in the case of regression, and labels will store the list of argmax (i.e. the index of the output unit with the highest value) or their labels, if the model has output labels:
{
    "labels": [
        "positive"
    ],
    "values": [
        {
            "positive": 0.998,
            "negative": 0.002
        }
    ]
}

remove(model: str) → None[source]

Unload a module and, if stored on the filesystem, remove its resource files as well. WARNING: This operation is not reversible.

Parameters:model – Name of the model.
save(model: str, overwrite: bool = True, **opts) → None[source]

Save a model in memory to the filesystem. The model files will be stored under <WORKDIR>/models/<model_name>.

Parameters:
  • model – Model name.
  • overwrite – Overwrite the model files if they already exist.
  • opts – Extra options to be passed to Model.save().
train(model: str, inputs: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b80d82c88>, Iterable], outputs: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b805c2630>, Iterable, None] = None, batch_size: Optional[int] = None, epochs: int = 1, verbose: int = 1, validation_split: float = 0.0, validation_data: Optional[Tuple[Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b80d82198>, Iterable]]] = None, shuffle: Union[bool, str] = True, class_weight: Optional[Dict[int, float]] = None, sample_weight: Union[<sphinx.ext.autodoc.importer._MockObject object at 0x7f6b817e7da0>, Iterable, None] = None, initial_epoch: int = 0, steps_per_epoch: Optional[int] = None, validation_steps: int = None, validation_freq: int = 1, max_queue_size: int = 10, workers: int = 1, use_multiprocessing: bool = False) → platypush.message.response.tensorflow.TensorflowTrainResponse[source]

Trains a model on a dataset for a fixed number of epochs.

Parameters:
  • model – Name of the existing model to be trained.
  • inputs

    Input data. It can be:

    • A numpy array (or array-like), or a list of arrays in case the model has multiple inputs.
    • A TensorFlow tensor, or a list of tensors in case the model has multiple inputs.
    • A dict mapping input names to the corresponding array/tensors, if the model has named inputs.
    • A tf.data dataset. Should return a tuple of either (inputs, targets) or (inputs, targets, sample_weights).
    • A generator or keras.utils.Sequence returning (inputs, targets) or (inputs, targets, sample weights).
    • A string that points to a file. Supported formats:
      • CSV with header (.csv extension``)
      • Numpy raw or compressed files (.npy or .npz extension)
      • Image files
      • An HTTP URL pointing to one of the file types listed above
      • Directories with images. If inputs points to a directory of images then the following conventions are followed:
        • The folder must contain exactly as many subfolders as the output units of your model. If the model has output_labels then those subfolders should be named as the output labels. Each subfolder will contain training examples that match the associated label (e.g. positive will contain all the positive images and negative all the negative images).
        • outputs doesn’t have to be specified.
  • outputs – Target data. Like the input data x, it can be a numpy array (or array-like) or TensorFlow tensor(s). It should be consistent with x (you cannot have Numpy inputs and tensor targets, or inversely). If x is a dataset, generator, or keras.utils.Sequence instance, y should not be specified (since targets will be obtained from x).
  • batch_size – Number of samples per gradient update. If unspecified, batch_size will default to 32. Do not specify the batch_size if your data is in the form of symbolic tensors, datasets, generators, or keras.utils.Sequence instances (since they generate batches).
  • epochs – Number of epochs to train the model. An epoch is an iteration over the entire x and y data provided. Note that in conjunction with initial_epoch, epochs is to be understood as “final epoch”. The model is not trained for a number of iterations given by epochs, but merely until the epoch of index epochs is reached.
  • verbose – Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment).
  • validation_split
    Float between 0 and 1.
    Fraction of the training data to be used as validation data. The model will set apart this fraction of the training data, will not train on it, and will evaluate the loss and any model metrics on this data at the end of each epoch. The validation data is selected from the last samples in the x and y data provided, before shuffling. This argument is not supported when x is a dataset, generator or

    keras.utils.Sequence instance.

  • validation_data

    Data on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. validation_data will override validation_split. validation_data could be:

    • tuple (x_val, y_val) of arrays/numpy arrays/tensors
    • tuple (x_val, y_val, val_sample_weights) of Numpy arrays
    • dataset

    For the first two cases, batch_size must be provided. For the last case, validation_steps could be provided.

  • shuffle – Boolean (whether to shuffle the training data before each epoch) or str (for ‘batch’). ‘batch’ is a special option for dealing with the limitations of HDF5 data; it shuffles in batch-sized chunks. Has no effect when steps_per_epoch is not None.
  • class_weight – Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to “pay more attention” to samples from an under-represented class.
  • sample_weight – Optional iterable/numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) numpy array/iterable with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every time step of every sample. In this case you should make sure to specify sample_weight_mode="temporal" in compile(). This argument is not supported when x is a dataset, generator, or keras.utils.Sequence instance, instead provide the sample_weights as the third element of x.
  • initial_epoch – Epoch at which to start training (useful for resuming a previous training run).
  • steps_per_epoch – Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. When training with input tensors such as TensorFlow data tensors, the default None is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined. If x is a tf.data dataset, and ‘steps_per_epoch’ is None, the epoch will run until the input dataset is exhausted. This argument is not supported with array inputs.
  • validation_steps – Only relevant if validation_data is provided and is a tf.data dataset. Total number of steps (batches of samples) to draw before stopping when performing validation at the end of every epoch. If ‘validation_steps’ is None, validation will run until the validation_data dataset is exhausted. In the case of a infinite dataset, it will run into a infinite loop. If ‘validation_steps’ is specified and only part of the dataset will be consumed, the evaluation will start from the beginning of the dataset at each epoch. This ensures that the same validation samples are used every time.
  • validation_freq – Only relevant if validation data is provided. Integer or collections_abc.Container instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g. validation_freq=2 runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g. validation_freq=[1, 2, 10] runs validation at the end of the 1st, 2nd, and 10th epochs.
  • max_queue_size – Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue. If unspecified, max_queue_size will default to 10.
  • workers – Used for generator or keras.utils.Sequence input only. Maximum number of processes to spin up when using process-based threading. If unspecified, workers will default to 1. If 0, will execute the generator on the main thread.
  • use_multiprocessing – Used for generator or keras.utils.Sequence input only. If True, use process-based threading. If unspecified, use_multiprocessing will default to False. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can’t be passed easily to children processes.
Returns:

platypush.message.response.tensorflow.TensorflowTrainResponse

unload(model: str) → None[source]

Remove a loaded model from memory.

Parameters:model – Name of the model.