TorchConnector

class TorchConnector(*args, **kwargs)[source]

Bases: torch.nn.Module

Connector class to integrate a neural network with PyTorch.

Parameters:
  • neural_network (NeuralNetwork) – The neural network to be connected to PyTorch. Note: input_gradients must be set to True in the neural network initialization before passing it to the TorchConnector for gradient computations to work properly during training.

  • initial_weights (np.ndarray | Tensor | None) – The initial weights to start training the network. If this is None, the initial weights are chosen uniformly at random from \([-1, 1]\).

  • sparse (bool | None) – Whether this connector should return sparse output or not. If sparse is set to None, then the setting from the given neural network is used. Note that sparse output is only returned if the underlying neural network also returns sparse output, otherwise an error will be raised.

Raises:

QiskitMachineLearningError – If the connector is configured as sparse and the underlying network is not sparse.

Attributes

neural_network

Returns the underlying neural network.

Returns:

The neural network connected to this TorchConnector.

Return type:

NeuralNetwork

sparse

Returns whether this connector returns sparse output or not.

Returns:

True if the connector returns sparse output, False otherwise, or None if it uses the setting from the neural network.

Return type:

bool | None

weight

Returns the weights of the underlying network.

Returns:

The weights tensor.

Return type:

Tensor

Methods

forward(input_data=None)[source]

Forward pass. Defaults to an empty tensor if input_data is None.

Parameters:

input_data (Tensor | None) – Data to be evaluated.

Returns:

Result of the forward pass of this model.

Return type:

Tensor