qml.numpy.tensor

class tensor(input_array, *args, requires_grad=True, **kwargs)[source]

Bases: numpy.ndarray

Constructs a PennyLane tensor for use with Autograd QNodes.

The tensor class is a subclass of numpy.ndarray, providing the same multidimensional, homogeneous data-structure of fixed-size items, with an additional flag to indicate to PennyLane whether the contained data is differentiable or not.

Warning

PennyLane tensor objects are only used as part of the Autograd QNode interface. If using another machine learning library such as PyTorch or TensorFlow, use their built-in tf.Variable and torch.tensor classes instead.

Warning

Tensors should be constructed using standard array construction functions provided as part of PennyLane’s NumPy implementation, including np.array, np.zeros or np.empty.

The parameters given here refer to a low-level class for instantiating tensors.

Parameters
  • input_array (array_like) – Any data structure in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

  • requires_grad (bool) – whether the tensor supports differentiation

Example

The trainability of a tensor can be set on construction via the requires_grad keyword argument,

>>> from pennylane import numpy as np
>>> x = np.array([0, 1, 2], requires_grad=True)
>>> x
tensor([0, 1, 2], requires_grad=True)

or in-place by modifying the requires_grad attribute:

>>> x.requires_grad = False
tensor([0, 1, 2], requires_grad=False)

Since tensors are subclasses of np.ndarray, they can be provided as arguments to any PennyLane-wrapped NumPy function:

>>> np.sin(x)
tensor([0.        , 0.84147098, 0.90929743], requires_grad=True)

When composing functions of multiple tensors, if at least one input tensor is differentiable, then the output will also be differentiable:

>>> x = np.array([0, 1, 2], requires_grad=False)
>>> y = np.zeros([3], requires_grad=True)
>>> np.vstack([x, y])
tensor([[0., 1., 2.],
    [0., 0., 0.]], requires_grad=True)

T

View of the transposed array.

base

Base object if memory is from some other object.

ctypes

An object to simplify the interaction of the array with the ctypes module.

data

Python buffer object pointing to the start of the array’s data.

dtype

Data-type of the array’s elements.

flags

Information about the memory layout of the array.

flat

A 1-D iterator over the array.

imag

The imaginary part of the array.

itemsize

Length of one array element in bytes.

nbytes

Total bytes consumed by the elements of the array.

ndim

Number of array dimensions.

real

The real part of the array.

shape

Tuple of array dimensions.

size

Number of elements in the array.

strides

Tuple of bytes to step in each dimension when traversing an array.

all([axis, out, keepdims, where])

Returns True if all elements evaluate to True.

any([axis, out, keepdims, where])

Returns True if any of the elements of a evaluate to True.

argmax([axis, out, keepdims])

Return indices of the maximum values along the given axis.

argmin([axis, out, keepdims])

Return indices of the minimum values along the given axis.

argpartition(kth[, axis, kind, order])

Returns the indices that would partition this array.

argsort([axis, kind, order])

Returns the indices that would sort this array.

astype(dtype[, order, casting, subok, copy])

Copy of the array, cast to a specified type.

byteswap([inplace])

Swap the bytes of the array elements

choose(choices[, out, mode])

Use an index array to construct a new array from a set of choices.

clip([min, max, out])

Return an array whose values are limited to [min, max].

compress(condition[, axis, out])

Return selected slices of this array along given axis.

conj()

Complex-conjugate all elements.

conjugate()

Return the complex conjugate, element-wise.

copy([order])

Return a copy of the array.

cumprod([axis, dtype, out])

Return the cumulative product of the elements along the given axis.

cumsum([axis, dtype, out])

Return the cumulative sum of the elements along the given axis.

diagonal([offset, axis1, axis2])

Return specified diagonals.

dot

dump(file)

Dump a pickle of the array to the specified file.

dumps()

Returns the pickle of the array as a string.

fill(value)

Fill the array with a scalar value.

flatten([order])

Return a copy of the array collapsed into one dimension.

getfield(dtype[, offset])

Returns a field of the given array as a certain type.

item(*args)

Copy an element of an array to a standard Python scalar and return it.

itemset(*args)

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

max([axis, out, keepdims, initial, where])

Return the maximum along a given axis.

mean([axis, dtype, out, keepdims, where])

Returns the average of the array elements along given axis.

min([axis, out, keepdims, initial, where])

Return the minimum along a given axis.

newbyteorder([new_order])

Return the array with the same data viewed with a different byte order.

nonzero()

Return the indices of the elements that are non-zero.

numpy()

Converts the tensor to a standard, non-differentiable NumPy ndarray or Python scalar if the tensor is 0-dimensional.

partition(kth[, axis, kind, order])

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.

prod([axis, dtype, out, keepdims, initial, …])

Return the product of the array elements over the given axis

ptp([axis, out, keepdims])

Peak to peak (maximum - minimum) value along a given axis.

put(indices, values[, mode])

Set a.flat[n] = values[n] for all n in indices.

ravel([order])

Return a flattened array.

repeat(repeats[, axis])

Repeat elements of an array.

reshape(shape[, order])

Returns an array containing the same data with a new shape.

resize(new_shape[, refcheck])

Change shape and size of array in-place.

round([decimals, out])

Return a with each element rounded to the given number of decimals.

searchsorted(v[, side, sorter])

Find indices where elements of v should be inserted in a to maintain order.

setfield(val, dtype[, offset])

Put a value into a specified place in a field defined by a data-type.

setflags([write, align, uic])

Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.

sort([axis, kind, order])

Sort an array in-place.

squeeze([axis])

Remove axes of length one from a.

std([axis, dtype, out, ddof, keepdims, where])

Returns the standard deviation of the array elements along given axis.

sum([axis, dtype, out, keepdims, initial, where])

Return the sum of the array elements over the given axis.

swapaxes(axis1, axis2)

Return a view of the array with axis1 and axis2 interchanged.

take(indices[, axis, out, mode])

Return an array formed from the elements of a at the given indices.

tobytes([order])

Construct Python bytes containing the raw data bytes in the array.

tofile(fid[, sep, format])

Write array to a file as text or binary (default).

tolist()

Return the array as an a.ndim-levels deep nested list of Python scalars.

tostring([order])

A compatibility alias for tobytes, with exactly the same behavior.

trace([offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

transpose(*axes)

Returns a view of the array with axes transposed.

unwrap()

Converts the tensor to a standard, non-differentiable NumPy ndarray or Python scalar if the tensor is 0-dimensional.

var([axis, dtype, out, ddof, keepdims, where])

Returns the variance of the array elements, along given axis.

view([dtype][, type])

New view of array with the same data.

numpy()[source]

Converts the tensor to a standard, non-differentiable NumPy ndarray or Python scalar if the tensor is 0-dimensional.

This method is an alias for unwrap(). See unwrap() for more details.

unwrap()[source]

Converts the tensor to a standard, non-differentiable NumPy ndarray or Python scalar if the tensor is 0-dimensional.

All information regarding differentiability of the tensor will be lost.

Warning

The returned array is a new view onto the same data. That is, the tensor and the returned ndarray share the same underlying storage. Changes to the tensor object will be reflected within the returned array, and vice versa.

Example

>>> from pennylane import numpy as np
>>> x = np.array([1, 2], requires_grad=True)
>>> x
tensor([1, 2], requires_grad=True)
>>> x.unwrap()
array([1, 2])

Zero dimensional array are converted to Python scalars:

>>> x = np.array(1.543, requires_grad=False)
>>> x.unwrap()
1.543
>>> type(x.unwrap())
float

The underlying data is not copied:

>>> x = np.array([1, 2], requires_grad=True)
>>> y = x.unwrap()
>>> x[0] = 5
>>> y
array([5, 2])
>>> y[1] = 7
>>> x
tensor([5, 7], requires_grad=True)

To create a copy, the copy() method can be used:

>>> x = np.array([1, 2], requires_grad=True)
>>> y = x.unwrap().copy()
>>> x[0] = 5
>>> y
array([1, 2])