doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
tf.keras.wrappers.scikit_learn.KerasClassifier View source on GitHub Implementation of the scikit-learn classifier API for Keras. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.wrappers.scikit_learn.KerasClassifier
tf.keras.wrappers.scikit_learn.KerasClassifier(
build_fn=None, **sk_params
)
Methods check_params View source
check_params(
params
)
Checks for user typos in params.
Arguments
params dictionary; the parameters to be checked
Raises
ValueError if any member of params is not a valid argument. filter_sk_params View source
filter_sk_params(
fn, override=None
)
Filters sk_params and returns those in fn's arguments.
Arguments
fn arbitrary function
override dictionary, values to override sk_params
Returns
res dictionary containing variables in both sk_params and fn's arguments. fit View source
fit(
x, y, **kwargs
)
Constructs a new model with build_fn & fit the model to (x, y).
Arguments
x array-like, shape (n_samples, n_features) Training samples where n_samples is the number of samples and n_features is the number of features.
y array-like, shape (n_samples,) or (n_samples, n_outputs) True labels for x.
**kwargs dictionary arguments Legal arguments are the arguments of Sequential.fit
Returns
history object details about the training history at each epoch.
Raises
ValueError In case of invalid shape for y argument. get_params View source
get_params(
**params
)
Gets parameters for this estimator.
Arguments
**params ignored (exists for API compatibility).
Returns Dictionary of parameter names mapped to their values.
predict View source
predict(
x, **kwargs
)
Returns the class predictions for the given test data.
Arguments
x array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
**kwargs dictionary arguments Legal arguments are the arguments of Sequential.predict_classes.
Returns
preds array-like, shape (n_samples,) Class predictions. predict_proba View source
predict_proba(
x, **kwargs
)
Returns class probability estimates for the given test data.
Arguments
x array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
**kwargs dictionary arguments Legal arguments are the arguments of Sequential.predict_classes.
Returns
proba array-like, shape (n_samples, n_outputs) Class probability estimates. In the case of binary classification, to match the scikit-learn API, will return an array of shape (n_samples, 2) (instead of (n_sample, 1) as in Keras). score View source
score(
x, y, **kwargs
)
Returns the mean accuracy on the given test data and labels.
Arguments
x array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
y array-like, shape (n_samples,) or (n_samples, n_outputs) True labels for x.
**kwargs dictionary arguments Legal arguments are the arguments of Sequential.evaluate.
Returns
score float Mean accuracy of predictions on x wrt. y.
Raises
ValueError If the underlying model isn't configured to compute accuracy. You should pass metrics=["accuracy"] to the .compile() method of the model. set_params View source
set_params(
**params
)
Sets the parameters of this estimator.
Arguments
**params Dictionary of parameter names mapped to their values.
Returns self | tensorflow.keras.wrappers.scikit_learn.kerasclassifier |
tf.keras.wrappers.scikit_learn.KerasRegressor View source on GitHub Implementation of the scikit-learn regressor API for Keras. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.wrappers.scikit_learn.KerasRegressor
tf.keras.wrappers.scikit_learn.KerasRegressor(
build_fn=None, **sk_params
)
Methods check_params View source
check_params(
params
)
Checks for user typos in params.
Arguments
params dictionary; the parameters to be checked
Raises
ValueError if any member of params is not a valid argument. filter_sk_params View source
filter_sk_params(
fn, override=None
)
Filters sk_params and returns those in fn's arguments.
Arguments
fn arbitrary function
override dictionary, values to override sk_params
Returns
res dictionary containing variables in both sk_params and fn's arguments. fit View source
fit(
x, y, **kwargs
)
Constructs a new model with build_fn & fit the model to (x, y).
Arguments
x array-like, shape (n_samples, n_features) Training samples where n_samples is the number of samples and n_features is the number of features.
y array-like, shape (n_samples,) or (n_samples, n_outputs) True labels for x.
**kwargs dictionary arguments Legal arguments are the arguments of Sequential.fit
Returns
history object details about the training history at each epoch. get_params View source
get_params(
**params
)
Gets parameters for this estimator.
Arguments
**params ignored (exists for API compatibility).
Returns Dictionary of parameter names mapped to their values.
predict View source
predict(
x, **kwargs
)
Returns predictions for the given test data.
Arguments
x array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
**kwargs dictionary arguments Legal arguments are the arguments of Sequential.predict.
Returns
preds array-like, shape (n_samples,) Predictions. score View source
score(
x, y, **kwargs
)
Returns the mean loss on the given test data and labels.
Arguments
x array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
y array-like, shape (n_samples,) True labels for x.
**kwargs dictionary arguments Legal arguments are the arguments of Sequential.evaluate.
Returns
score float Mean accuracy of predictions on x wrt. y. set_params View source
set_params(
**params
)
Sets the parameters of this estimator.
Arguments
**params Dictionary of parameter names mapped to their values.
Returns self | tensorflow.keras.wrappers.scikit_learn.kerasregressor |
Module: tf.linalg Operations for linear algebra. Modules experimental module: Public API for tf.linalg.experimental namespace. Classes class LinearOperator: Base class defining a [batch of] linear operator[s]. class LinearOperatorAdjoint: LinearOperator representing the adjoint of another operator. class LinearOperatorBlockDiag: Combines one or more LinearOperators in to a Block Diagonal matrix. class LinearOperatorBlockLowerTriangular: Combines LinearOperators into a blockwise lower-triangular matrix. class LinearOperatorCirculant: LinearOperator acting like a circulant matrix. class LinearOperatorCirculant2D: LinearOperator acting like a block circulant matrix. class LinearOperatorCirculant3D: LinearOperator acting like a nested block circulant matrix. class LinearOperatorComposition: Composes one or more LinearOperators. class LinearOperatorDiag: LinearOperator acting like a [batch] square diagonal matrix. class LinearOperatorFullMatrix: LinearOperator that wraps a [batch] matrix. class LinearOperatorHouseholder: LinearOperator acting like a [batch] of Householder transformations. class LinearOperatorIdentity: LinearOperator acting like a [batch] square identity matrix. class LinearOperatorInversion: LinearOperator representing the inverse of another operator. class LinearOperatorKronecker: Kronecker product between two LinearOperators. class LinearOperatorLowRankUpdate: Perturb a LinearOperator with a rank K update. class LinearOperatorLowerTriangular: LinearOperator acting like a [batch] square lower triangular matrix. class LinearOperatorPermutation: LinearOperator acting like a [batch] of permutation matrices. class LinearOperatorScaledIdentity: LinearOperator acting like a scaled [batch] identity matrix A = c I. class LinearOperatorToeplitz: LinearOperator acting like a [batch] of toeplitz matrices. class LinearOperatorTridiag: LinearOperator acting like a [batch] square tridiagonal matrix. class LinearOperatorZeros: LinearOperator acting like a [batch] zero matrix. Functions adjoint(...): Transposes the last two dimensions of and conjugates tensor matrix. band_part(...): Copy a tensor setting everything outside a central band in each innermost matrix to zero. banded_triangular_solve(...): Solve triangular systems of equations with a banded solver. cholesky(...): Computes the Cholesky decomposition of one or more square matrices. cholesky_solve(...): Solves systems of linear eqns A X = RHS, given Cholesky factorizations. cross(...): Compute the pairwise cross product. det(...): Computes the determinant of one or more square matrices. diag(...): Returns a batched diagonal tensor with given batched diagonal values. diag_part(...): Returns the batched diagonal part of a batched tensor. eig(...): Computes the eigen decomposition of a batch of matrices. eigh(...): Computes the eigen decomposition of a batch of self-adjoint matrices. eigvals(...): Computes the eigenvalues of one or more matrices. eigvalsh(...): Computes the eigenvalues of one or more self-adjoint matrices. einsum(...): Tensor contraction over specified indices and outer product. expm(...): Computes the matrix exponential of one or more square matrices. eye(...): Construct an identity matrix, or a batch of matrices. global_norm(...): Computes the global norm of multiple tensors. inv(...): Computes the inverse of one or more square invertible matrices or their adjoints (conjugate transposes). l2_normalize(...): Normalizes along dimension axis using an L2 norm. logdet(...): Computes log of the determinant of a hermitian positive definite matrix. logm(...): Computes the matrix logarithm of one or more square matrices: lstsq(...): Solves one or more linear least-squares problems. lu(...): Computes the LU decomposition of one or more square matrices. lu_matrix_inverse(...): Computes the inverse given the LU decomposition(s) of one or more matrices. lu_reconstruct(...): The reconstruct one or more matrices from their LU decomposition(s). lu_solve(...): Solves systems of linear eqns A X = RHS, given LU factorizations. matmul(...): Multiplies matrix a by matrix b, producing a * b. matrix_rank(...): Compute the matrix rank of one or more matrices. matrix_transpose(...): Transposes last two dimensions of tensor a. matvec(...): Multiplies matrix a by vector b, producing a * b. norm(...): Computes the norm of vectors, matrices, and tensors. normalize(...): Normalizes tensor along dimension axis using specified norm. pinv(...): Compute the Moore-Penrose pseudo-inverse of one or more matrices. qr(...): Computes the QR decompositions of one or more matrices. set_diag(...): Returns a batched matrix tensor with new batched diagonal values. slogdet(...): Computes the sign and the log of the absolute value of the determinant of solve(...): Solves systems of linear equations. sqrtm(...): Computes the matrix square root of one or more square matrices: svd(...): Computes the singular value decompositions of one or more matrices. tensor_diag(...): Returns a diagonal tensor with a given diagonal values. tensor_diag_part(...): Returns the diagonal part of the tensor. tensordot(...): Tensor contraction of a and b along specified axes and outer product. trace(...): Compute the trace of a tensor x. triangular_solve(...): Solve systems of linear equations with upper or lower triangular matrices. tridiagonal_matmul(...): Multiplies tridiagonal matrix by matrix. tridiagonal_solve(...): Solves tridiagonal systems of equations. | tensorflow.linalg |
tf.linalg.adjoint View source on GitHub Transposes the last two dimensions of and conjugates tensor matrix. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.adjoint
tf.linalg.adjoint(
matrix, name=None
)
For example: x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],
[4 + 4j, 5 + 5j, 6 + 6j]])
tf.linalg.adjoint(x) # [[1 - 1j, 4 - 4j],
# [2 - 2j, 5 - 5j],
# [3 - 3j, 6 - 6j]]
Args
matrix A Tensor. Must be float16, float32, float64, complex64, or complex128 with shape [..., M, M].
name A name to give this Op (optional).
Returns The adjoint (a.k.a. Hermitian transpose a.k.a. conjugate transpose) of matrix. | tensorflow.linalg.adjoint |
tf.linalg.banded_triangular_solve Solve triangular systems of equations with a banded solver.
tf.linalg.banded_triangular_solve(
bands, rhs, lower=True, adjoint=False, name=None
)
bands is a tensor of shape [..., K, M], where K represents the number of bands stored. This corresponds to a batch of M by M matrices, whose K subdiagonals (when lower is True) are stored. This operator broadcasts the batch dimensions of bands and the batch dimensions of rhs. Examples: Storing 2 bands of a 3x3 matrix. Note that first element in the second row is ignored due to the 'LEFT_RIGHT' padding.
x = [[2., 3., 4.], [1., 2., 3.]]
x2 = [[2., 3., 4.], [10000., 2., 3.]]
y = tf.zeros([3, 3])
z = tf.linalg.set_diag(y, x, align='LEFT_RIGHT', k=(-1, 0))
z
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[2., 0., 0.],
[2., 3., 0.],
[0., 3., 4.]], dtype=float32)>
soln = tf.linalg.banded_triangular_solve(x, tf.ones([3, 1]))
soln
<tf.Tensor: shape=(3, 1), dtype=float32, numpy=
array([[0.5 ],
[0. ],
[0.25]], dtype=float32)>
are_equal = soln == tf.linalg.banded_triangular_solve(x2, tf.ones([3, 1]))
tf.reduce_all(are_equal).numpy()
True
are_equal = soln == tf.linalg.triangular_solve(z, tf.ones([3, 1]))
tf.reduce_all(are_equal).numpy()
True
Storing 2 superdiagonals of a 4x4 matrix. Because of the 'LEFT_RIGHT' padding the last element of the first row is ignored.
x = [[2., 3., 4., 5.], [-1., -2., -3., -4.]]
y = tf.zeros([4, 4])
z = tf.linalg.set_diag(y, x, align='LEFT_RIGHT', k=(0, 1))
z
<tf.Tensor: shape=(4, 4), dtype=float32, numpy=
array([[-1., 2., 0., 0.],
[ 0., -2., 3., 0.],
[ 0., 0., -3., 4.],
[ 0., 0., -0., -4.]], dtype=float32)>
soln = tf.linalg.banded_triangular_solve(x, tf.ones([4, 1]), lower=False)
soln
<tf.Tensor: shape=(4, 1), dtype=float32, numpy=
array([[-4. ],
[-1.5 ],
[-0.6666667],
[-0.25 ]], dtype=float32)>
are_equal = (soln == tf.linalg.triangular_solve(
z, tf.ones([4, 1]), lower=False))
tf.reduce_all(are_equal).numpy()
True
Args
bands A Tensor describing the bands of the left hand side, with shape [..., K, M]. The K rows correspond to the diagonal to the K - 1-th diagonal (the diagonal is the top row) when lower is True and otherwise the K - 1-th superdiagonal to the diagonal (the diagonal is the bottom row) when lower is False. The bands are stored with 'LEFT_RIGHT' alignment, where the superdiagonals are padded on the right and subdiagonals are padded on the left. This is the alignment cuSPARSE uses. See tf.linalg.set_diag for more details.
rhs A Tensor of shape [..., M] or [..., M, N] and with the same dtype as diagonals. Note that if the shape of rhs and/or diags isn't known statically, rhs will be treated as a matrix rather than a vector.
lower An optional bool. Defaults to True. Boolean indicating whether bands represents a lower or upper triangular matrix.
adjoint An optional bool. Defaults to False. Boolean indicating whether to solve with the matrix's block-wise adjoint.
name A name to give this Op (optional).
Returns A Tensor of shape [..., M] or [..., M, N] containing the solutions. | tensorflow.linalg.banded_triangular_solve |
tf.linalg.band_part Copy a tensor setting everything outside a central band in each innermost matrix to zero. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.band_part, tf.compat.v1.matrix_band_part
tf.linalg.band_part(
input, num_lower, num_upper, name=None
)
The band part is computed as follows: Assume input has k dimensions [I, J, K, ..., M, N], then the output is a tensor with the same shape where band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]. The indicator function in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)) && (num_upper < 0 || (n-m) <= num_upper). For example: # if 'input' is [[ 0, 1, 2, 3]
[-1, 0, 1, 2]
[-2, -1, 0, 1]
[-3, -2, -1, 0]],
tf.matrix_band_part(input, 1, -1) ==> [[ 0, 1, 2, 3]
[-1, 0, 1, 2]
[ 0, -1, 0, 1]
[ 0, 0, -1, 0]],
tf.matrix_band_part(input, 2, 1) ==> [[ 0, 1, 0, 0]
[-1, 0, 1, 0]
[-2, -1, 0, 1]
[ 0, -2, -1, 0]]
Useful special cases: tf.matrix_band_part(input, 0, -1) ==> Upper triangular part.
tf.matrix_band_part(input, -1, 0) ==> Lower triangular part.
tf.matrix_band_part(input, 0, 0) ==> Diagonal.
Args
input A Tensor. Rank k tensor.
num_lower A Tensor. Must be one of the following types: int32, int64. 0-D tensor. Number of subdiagonals to keep. If negative, keep entire lower triangle.
num_upper A Tensor. Must have the same type as num_lower. 0-D tensor. Number of superdiagonals to keep. If negative, keep entire upper triangle.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.linalg.band_part |
tf.linalg.cholesky Computes the Cholesky decomposition of one or more square matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.cholesky, tf.compat.v1.linalg.cholesky
tf.linalg.cholesky(
input, name=None
)
The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The input has to be symmetric and positive definite. Only the lower-triangular part of the input will be used for this operation. The upper-triangular part will not be read. The output is a tensor of the same shape as the input containing the Cholesky decompositions for all input submatrices [..., :, :].
Note: The gradient computation on GPU is faster for large matrices but not for large batch dimensions when the submatrices are small. In this case it might be faster to use the CPU.
Args
input A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. Shape is [..., M, M].
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.linalg.cholesky |
tf.linalg.cholesky_solve View source on GitHub Solves systems of linear eqns A X = RHS, given Cholesky factorizations. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.cholesky_solve, tf.compat.v1.linalg.cholesky_solve
tf.linalg.cholesky_solve(
chol, rhs, name=None
)
Specifically, returns X from A X = RHS, where A = L L^T, L is the chol arg and RHS is the rhs arg. # Solve 10 separate 2x2 linear systems:
A = ... # shape 10 x 2 x 2
RHS = ... # shape 10 x 2 x 1
chol = tf.linalg.cholesky(A) # shape 10 x 2 x 2
X = tf.linalg.cholesky_solve(chol, RHS) # shape 10 x 2 x 1
# tf.matmul(A, X) ~ RHS
X[3, :, 0] # Solution to the linear system A[3, :, :] x = RHS[3, :, 0]
# Solve five linear systems (K = 5) for every member of the length 10 batch.
A = ... # shape 10 x 2 x 2
RHS = ... # shape 10 x 2 x 5
...
X[3, :, 2] # Solution to the linear system A[3, :, :] x = RHS[3, :, 2]
Args
chol A Tensor. Must be float32 or float64, shape is [..., M, M]. Cholesky factorization of A, e.g. chol = tf.linalg.cholesky(A). For that reason, only the lower triangular parts (including the diagonal) of the last two dimensions of chol are used. The strictly upper part is assumed to be zero and not accessed.
rhs A Tensor, same type as chol, shape is [..., M, K].
name A name to give this Op. Defaults to cholesky_solve.
Returns Solution to A x = rhs, shape [..., M, K]. | tensorflow.linalg.cholesky_solve |
tf.linalg.cross Compute the pairwise cross product. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.cross, tf.compat.v1.linalg.cross
tf.linalg.cross(
a, b, name=None
)
a and b must be the same shape; they can either be simple 3-element vectors, or any shape where the innermost dimension is 3. In the latter case, each pair of corresponding 3-element vectors is cross-multiplied independently.
Args
a A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. A tensor containing 3-element vectors.
b A Tensor. Must have the same type as a. Another tensor, of same type and shape as a.
name A name for the operation (optional).
Returns A Tensor. Has the same type as a. | tensorflow.linalg.cross |
tf.linalg.det Computes the determinant of one or more square matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.det, tf.compat.v1.matrix_determinant
tf.linalg.det(
input, name=None
)
The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The output is a tensor containing the determinants for all input submatrices [..., :, :].
Args
input A Tensor. Must be one of the following types: half, float32, float64, complex64, complex128. Shape is [..., M, M].
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.linalg.det |
tf.linalg.diag View source on GitHub Returns a batched diagonal tensor with given batched diagonal values. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.diag, tf.compat.v1.matrix_diag
tf.linalg.diag(
diagonal, name='diag', k=0, num_rows=-1, num_cols=-1, padding_value=0,
align='RIGHT_LEFT'
)
Returns a tensor with the contents in diagonal as k[0]-th to k[1]-th diagonals of a matrix, with everything else padded with padding. num_rows and num_cols specify the dimension of the innermost matrix of the output. If both are not specified, the op assumes the innermost matrix is square and infers its size from k and the innermost dimension of diagonal. If only one of them is specified, the op assumes the unspecified value is the smallest possible based on other criteria. Let diagonal have r dimensions [I, J, ..., L, M, N]. The output tensor has rank r+1 with shape [I, J, ..., L, M, num_rows, num_cols] when only one diagonal is given (k is an integer or k[0] == k[1]). Otherwise, it has rank r with shape [I, J, ..., L, num_rows, num_cols]. The second innermost dimension of diagonal has double meaning. When k is scalar or k[0] == k[1], M is part of the batch size [I, J, ..., M], and the output tensor is: output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper
padding_value ; otherwise
Otherwise, M is treated as the number of diagonals for the matrix in the same batch (M = k[1]-k[0]+1), and the output tensor is: output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]
padding_value ; otherwise
where d = n - m, diag_index = k[1] - d, and index_in_diag = n - max(d, 0) + offset. offset is zero except when the alignment of the diagonal is to the right. offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}
and `d >= 0`) or
(`align` in {LEFT_RIGHT, RIGHT_RIGHT}
and `d <= 0`)
0 ; otherwise
where diag_len(d) = min(cols - max(d, 0), rows + min(d, 0)). For example: # The main diagonal.
diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)
[5, 6, 7, 8]])
tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]],
[[5, 0, 0, 0],
[0, 6, 0, 0],
[0, 0, 7, 0],
[0, 0, 0, 8]]]
# A superdiagonal (per batch).
diagonal = np.array([[1, 2, 3], # Input shape: (2, 3)
[4, 5, 6]])
tf.matrix_diag(diagonal, k = 1)
==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)
[0, 0, 2, 0],
[0, 0, 0, 3],
[0, 0, 0, 0]],
[[0, 4, 0, 0],
[0, 0, 5, 0],
[0, 0, 0, 6],
[0, 0, 0, 0]]]
# A tridiagonal band (per batch).
diagonals = np.array([[[8, 9, 0], # Input shape: (2, 2, 3)
[1, 2, 3],
[0, 4, 5]],
[[2, 3, 0],
[6, 7, 9],
[0, 9, 1]]])
tf.matrix_diag(diagonals, k = (-1, 1))
==> [[[1, 8, 0], # Output shape: (2, 3, 3)
[4, 2, 9],
[0, 5, 3]],
[[6, 2, 0],
[9, 7, 3],
[0, 1, 9]]]
# RIGHT_LEFT alignment.
diagonals = np.array([[[0, 8, 9], # Input shape: (2, 2, 3)
[1, 2, 3],
[4, 5, 0]],
[[0, 2, 3],
[6, 7, 9],
[9, 1, 0]]])
tf.matrix_diag(diagonals, k = (-1, 1), align="RIGHT_LEFT")
==> [[[1, 8, 0], # Output shape: (2, 3, 3)
[4, 2, 9],
[0, 5, 3]],
[[6, 2, 0],
[9, 7, 3],
[0, 1, 9]]]
# Rectangular matrix.
diagonal = np.array([1, 2]) # Input shape: (2)
tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)
==> [[0, 0, 0, 0], # Output shape: (3, 4)
[1, 0, 0, 0],
[0, 2, 0, 0]]
# Rectangular matrix with inferred num_cols and padding_value = 9.
tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9)
==> [[9, 9], # Output shape: (3, 2)
[1, 9],
[9, 2]]
Args
diagonal A Tensor with rank k >= 1.
name A name for the operation (optional).
k Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main diagonal, and negative value means subdiagonals. k can be a single integer (for a single diagonal) or a pair of integers specifying the low and high ends of a matrix band. k[0] must not be larger than k[1].
num_rows The number of rows of the output matrix. If it is not provided, the op assumes the output matrix is a square matrix and infers the matrix size from d_lower, d_upper, and the innermost dimension of diagonal.
num_cols The number of columns of the output matrix. If it is not provided, the op assumes the output matrix is a square matrix and infers the matrix size from d_lower, d_upper, and the innermost dimension of diagonal.
padding_value The value to fill the area outside the specified diagonal band with. Default is 0.
align Some diagonals are shorter than max_diag_len and need to be padded. align is a string specifying how superdiagonals and subdiagonals should be aligned, respectively. There are four possible alignments: "RIGHT_LEFT" (default), "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" aligns superdiagonals to the right (left-pads the row) and subdiagonals to the left (right-pads the row). It is the packing format LAPACK uses. cuSPARSE uses "LEFT_RIGHT", which is the opposite alignment.
Returns A Tensor. Has the same type as diagonal. | tensorflow.linalg.diag |
tf.linalg.diag_part View source on GitHub Returns the batched diagonal part of a batched tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.diag_part, tf.compat.v1.matrix_diag_part
tf.linalg.diag_part(
input, name='diag_part', k=0, padding_value=0,
align='RIGHT_LEFT'
)
Returns a tensor with the k[0]-th to k[1]-th diagonals of the batched input. Assume input has r dimensions [I, J, ..., L, M, N]. Let max_diag_len be the maximum length among all diagonals to be extracted, max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0)) Let num_diags be the number of diagonals to extract, num_diags = k[1] - k[0] + 1. If num_diags == 1, the output tensor is of rank r - 1 with shape [I, J, ..., L, max_diag_len] and values: diagonal[i, j, ..., l, n]
= input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
padding_value ; otherwise.
where y = max(-k[1], 0), x = max(k[1], 0). Otherwise, the output tensor has rank r with dimensions [I, J, ..., L, num_diags, max_diag_len] with values: diagonal[i, j, ..., l, m, n]
= input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
padding_value ; otherwise.
where d = k[1] - m, y = max(-d, 0) - offset, and x = max(d, 0) - offset. offset is zero except when the alignment of the diagonal is to the right. offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}
and `d >= 0`) or
(`align` in {LEFT_RIGHT, RIGHT_RIGHT}
and `d <= 0`)
0 ; otherwise
where diag_len(d) = min(cols - max(d, 0), rows + min(d, 0)). The input must be at least a matrix. For example: input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)
[5, 6, 7, 8],
[9, 8, 7, 6]],
[[5, 4, 3, 2],
[1, 2, 3, 4],
[5, 6, 7, 8]]])
# A main diagonal from each batch.
tf.linalg.diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)
[5, 2, 7]]
# A superdiagonal from each batch.
tf.linalg.diag_part(input, k = 1)
==> [[2, 7, 6], # Output shape: (2, 3)
[4, 3, 8]]
# A band from each batch.
tf.linalg.diag_part(input, k = (-1, 2))
==> [[[3, 8, 0], # Output shape: (2, 4, 3)
[2, 7, 6],
[1, 6, 7],
[0, 5, 8]],
[[3, 4, 0],
[4, 3, 8],
[5, 2, 7],
[0, 1, 6]]]
# RIGHT_LEFT alignment.
tf.linalg.diag_part(input, k = (-1, 2), align="RIGHT_LEFT")
==> [[[0, 3, 8], # Output shape: (2, 4, 3)
[2, 7, 6],
[1, 6, 7],
[5, 8, 0]],
[[0, 3, 4],
[4, 3, 8],
[5, 2, 7],
[1, 6, 0]]]
# max_diag_len can be shorter than the main diagonal.
tf.linalg.diag_part(input, k = (-2, -1))
==> [[[5, 8],
[0, 9]],
[[1, 6],
[0, 5]]]
# padding_value = 9
tf.linalg.diag_part(input, k = (1, 3), padding_value = 9)
==> [[[4, 9, 9], # Output shape: (2, 3, 3)
[3, 8, 9],
[2, 7, 6]],
[[2, 9, 9],
[3, 4, 9],
[4, 3, 8]]]
Args
input A Tensor with rank k >= 2.
name A name for the operation (optional).
k Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main diagonal, and negative value means subdiagonals. k can be a single integer (for a single diagonal) or a pair of integers specifying the low and high ends of a matrix band. k[0] must not be larger than k[1].
padding_value The value to fill the area outside the specified diagonal band with. Default is 0.
align Some diagonals are shorter than max_diag_len and need to be padded. align is a string specifying how superdiagonals and subdiagonals should be aligned, respectively. There are four possible alignments: "RIGHT_LEFT" (default), "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" aligns superdiagonals to the right (left-pads the row) and subdiagonals to the left (right-pads the row). It is the packing format LAPACK uses. cuSPARSE uses "LEFT_RIGHT", which is the opposite alignment.
Returns A Tensor containing diagonals of input. Has the same type as input. | tensorflow.linalg.diag_part |
tf.linalg.eig Computes the eigen decomposition of a batch of matrices. View aliases Main aliases
tf.eig
tf.linalg.eig(
tensor, name=None
)
The eigenvalues and eigenvectors for a non-Hermitian matrix in general are complex. The eigenvectors are not guaranteed to be linearly independent. Computes the eigenvalues and right eigenvectors of the innermost N-by-N matrices in tensor such that tensor[...,:,:] * v[..., :,i] = e[..., i] * v[...,:,i], for i=0...N-1.
Args
tensor Tensor of shape [..., N, N]. Only the lower triangular part of each inner inner matrix is referenced.
name string, optional name of the operation.
Returns
e Eigenvalues. Shape is [..., N]. Sorted in non-decreasing order.
v Eigenvectors. Shape is [..., N, N]. The columns of the inner most matrices contain eigenvectors of the corresponding matrices in tensor | tensorflow.linalg.eig |
tf.linalg.eigh View source on GitHub Computes the eigen decomposition of a batch of self-adjoint matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.eigh, tf.compat.v1.self_adjoint_eig
tf.linalg.eigh(
tensor, name=None
)
Computes the eigenvalues and eigenvectors of the innermost N-by-N matrices in tensor such that tensor[...,:,:] * v[..., :,i] = e[..., i] * v[...,:,i], for i=0...N-1.
Args
tensor Tensor of shape [..., N, N]. Only the lower triangular part of each inner inner matrix is referenced.
name string, optional name of the operation.
Returns
e Eigenvalues. Shape is [..., N]. Sorted in non-decreasing order.
v Eigenvectors. Shape is [..., N, N]. The columns of the inner most matrices contain eigenvectors of the corresponding matrices in tensor | tensorflow.linalg.eigh |
tf.linalg.eigvals Computes the eigenvalues of one or more matrices. View aliases Main aliases
tf.eigvals
tf.linalg.eigvals(
tensor, name=None
)
Note: If your program backpropagates through this function, you should replace it with a call to tf.linalg.eig (possibly ignoring the second output) to avoid computing the eigen decomposition twice. This is because the eigenvectors are used to compute the gradient w.r.t. the eigenvalues. See _SelfAdjointEigV2Grad in linalg_grad.py.
Args
tensor Tensor of shape [..., N, N].
name string, optional name of the operation.
Returns
e Eigenvalues. Shape is [..., N]. The vector e[..., :] contains the N eigenvalues of tensor[..., :, :]. | tensorflow.linalg.eigvals |
tf.linalg.eigvalsh View source on GitHub Computes the eigenvalues of one or more self-adjoint matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.eigvalsh, tf.compat.v1.self_adjoint_eigvals
tf.linalg.eigvalsh(
tensor, name=None
)
Note: If your program backpropagates through this function, you should replace it with a call to tf.linalg.eigh (possibly ignoring the second output) to avoid computing the eigen decomposition twice. This is because the eigenvectors are used to compute the gradient w.r.t. the eigenvalues. See _SelfAdjointEigV2Grad in linalg_grad.py.
Args
tensor Tensor of shape [..., N, N].
name string, optional name of the operation.
Returns
e Eigenvalues. Shape is [..., N]. The vector e[..., :] contains the N eigenvalues of tensor[..., :, :]. | tensorflow.linalg.eigvalsh |
Module: tf.linalg.experimental Public API for tf.linalg.experimental namespace. Functions conjugate_gradient(...): Conjugate gradient solver. | tensorflow.linalg.experimental |
tf.linalg.experimental.conjugate_gradient Conjugate gradient solver. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.experimental.conjugate_gradient
tf.linalg.experimental.conjugate_gradient(
operator, rhs, preconditioner=None, x=None, tol=1e-05, max_iter=20,
name='conjugate_gradient'
)
Solves a linear system of equations A*x = rhs for self-adjoint, positive definite matrix A and right-hand side vector rhs, using an iterative, matrix-free algorithm where the action of the matrix A is represented by operator. The iteration terminates when either the number of iterations exceeds max_iter or when the residual norm has been reduced to tol times its initial value, i.e. \(||rhs - A x_k|| <= tol ||rhs||\).
Args
operator A LinearOperator that is self-adjoint and positive definite.
rhs A possibly batched vector of shape [..., N] containing the right-hand size vector.
preconditioner A LinearOperator that approximates the inverse of A. An efficient preconditioner could dramatically improve the rate of convergence. If preconditioner represents matrix M(M approximates A^{-1}), the algorithm uses preconditioner.apply(x) to estimate A^{-1}x. For this to be useful, the cost of applying M should be much lower than computing A^{-1} directly.
x A possibly batched vector of shape [..., N] containing the initial guess for the solution.
tol A float scalar convergence tolerance.
max_iter An integer giving the maximum number of iterations.
name A name scope for the operation.
Returns
output A namedtuple representing the final state with fields: i: A scalar int32 Tensor. Number of iterations executed. x: A rank-1 Tensor of shape [..., N] containing the computed solution. r: A rank-1 Tensor of shape [.., M] containing the residual vector. p: A rank-1 Tensor of shape [..., N]. A-conjugate basis vector. gamma: \(r \dot M \dot r\), equivalent to \(||r||_2^2\) when preconditioner=None. | tensorflow.linalg.experimental.conjugate_gradient |
tf.linalg.expm View source on GitHub Computes the matrix exponential of one or more square matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.expm
tf.linalg.expm(
input, name=None
)
$$exp(A) = \sum_{n=0}^\infty A^n/n!$$ The exponential is computed using a combination of the scaling and squaring method and the Pade approximation. Details can be found in: Nicholas J. Higham, "The scaling and squaring method for the matrix exponential revisited," SIAM J. Matrix Anal. Applic., 26:1179-1193, 2005. The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The output is a tensor of the same shape as the input containing the exponential for all input submatrices [..., :, :].
Args
input A Tensor. Must be float16, float32, float64, complex64, or complex128 with shape [..., M, M].
name A name to give this Op (optional).
Returns the matrix exponential of the input.
Raises
ValueError An unsupported type is provided as input. Scipy Compatibility Equivalent to scipy.linalg.expm | tensorflow.linalg.expm |
tf.linalg.global_norm View source on GitHub Computes the global norm of multiple tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.global_norm, tf.compat.v1.linalg.global_norm
tf.linalg.global_norm(
t_list, name=None
)
Given a tuple or list of tensors t_list, this operation returns the global norm of the elements in all tensors in t_list. The global norm is computed as: global_norm = sqrt(sum([l2norm(t)**2 for t in t_list])) Any entries in t_list that are of type None are ignored.
Args
t_list A tuple or list of mixed Tensors, IndexedSlices, or None.
name A name for the operation (optional).
Returns A 0-D (scalar) Tensor of type float.
Raises
TypeError If t_list is not a sequence. | tensorflow.linalg.global_norm |
tf.linalg.inv Computes the inverse of one or more square invertible matrices or their adjoints (conjugate transposes). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.inv, tf.compat.v1.matrix_inverse
tf.linalg.inv(
input, adjoint=False, name=None
)
The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The output is a tensor of the same shape as the input containing the inverse for all input submatrices [..., :, :]. The op uses LU decomposition with partial pivoting to compute the inverses. If a matrix is not invertible there is no guarantee what the op does. It may detect the condition and raise an exception or it may simply return a garbage result.
Args
input A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. Shape is [..., M, M].
adjoint An optional bool. Defaults to False.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.linalg.inv |
tf.linalg.LinearOperator View source on GitHub Base class defining a [batch of] linear operator[s]. Inherits From: Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperator
tf.linalg.LinearOperator(
dtype, graph_parents=None, is_non_singular=None, is_self_adjoint=None,
is_positive_definite=None, is_square=None, name=None, parameters=None
)
Subclasses of LinearOperator provide access to common methods on a (batch) matrix, without the need to materialize the matrix. This allows: Matrix free computations Operators that take advantage of special structure, while providing a consistent API to users. Subclassing To enable a public method, subclasses should implement the leading-underscore version of the method. The argument signature should be identical except for the omission of name="...". For example, to enable matmul(x, adjoint=False, name="matmul") a subclass should implement _matmul(x, adjoint=False). Performance contract Subclasses should only implement the assert methods (e.g. assert_non_singular) if they can be done in less than O(N^3) time. Class docstrings should contain an explanation of computational complexity. Since this is a high-performance library, attention should be paid to detail, and explanations can include constants as well as Big-O notation. Shape compatibility LinearOperator subclasses should operate on a [batch] matrix with compatible shape. Class docstrings should define what is meant by compatible shape. Some subclasses may not support batching. Examples: x is a batch matrix with compatible shape for matmul if operator.shape = [B1,...,Bb] + [M, N], b >= 0,
x.shape = [B1,...,Bb] + [N, R]
rhs is a batch matrix with compatible shape for solve if operator.shape = [B1,...,Bb] + [M, N], b >= 0,
rhs.shape = [B1,...,Bb] + [M, R]
Example docstring for subclasses. This operator acts like a (batch) matrix A with shape [B1,...,Bb, M, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an m x n matrix. Again, this matrix A may not be materialized, but for purposes of identifying and working with compatible arguments the shape is relevant. Examples: some_tensor = ... shape = ????
operator = MyLinOp(some_tensor)
operator.shape()
==> [2, 4, 4]
operator.log_abs_determinant()
==> Shape [2] Tensor
x = ... Shape [2, 4, 5] Tensor
operator.matmul(x)
==> Shape [2, 4, 5] Tensor
Shape compatibility This operator acts on batch matrices with compatible shape. FILL IN WHAT IS MEANT BY COMPATIBLE SHAPE Performance FILL THIS IN Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way. Initialization parameters All subclasses of LinearOperator are expected to pass a parameters argument to super().__init__(). This should be a dict containing the unadulterated arguments passed to the subclass __init__. For example, MyLinearOperator with an initializer should look like: def __init__(self, operator, is_square=False, name=None):
parameters = dict(
operator=operator,
is_square=is_square,
name=name
)
...
super().__init__(..., parameters=parameters)
```
Users can then access `my_linear_operator.parameters` to see all arguments
passed to its initializer.
<!-- Tabular view -->
<table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2"><h2 class="add-link">Args</h2></th></tr>
<tr>
<td>
`dtype`
</td>
<td>
The type of the this `LinearOperator`. Arguments to `matmul` and
`solve` will have to be this type.
</td>
</tr><tr>
<td>
`graph_parents`
</td>
<td>
(Deprecated) Python list of graph prerequisites of this
`LinearOperator` Typically tensors that are passed during initialization
</td>
</tr><tr>
<td>
`is_non_singular`
</td>
<td>
Expect that this operator is non-singular.
</td>
</tr><tr>
<td>
`is_self_adjoint`
</td>
<td>
Expect that this operator is equal to its hermitian
transpose. If `dtype` is real, this is equivalent to being symmetric.
</td>
</tr><tr>
<td>
`is_positive_definite`
</td>
<td>
Expect that this operator is positive definite,
meaning the quadratic form `x^H A x` has positive real part for all
nonzero `x`. Note that we do not require the operator to be
self-adjoint to be positive-definite. See:
<a href="https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices">https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices</a>
</td>
</tr><tr>
<td>
`is_square`
</td>
<td>
Expect that this operator acts like square [batch] matrices.
</td>
</tr><tr>
<td>
`name`
</td>
<td>
A name for this `LinearOperator`.
</td>
</tr><tr>
<td>
`parameters`
</td>
<td>
Python `dict` of parameters used to instantiate this
`LinearOperator`.
</td>
</tr>
</table>
<!-- Tabular view -->
<table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2"><h2 class="add-link">Raises</h2></th></tr>
<tr>
<td>
`ValueError`
</td>
<td>
If any member of graph_parents is `None` or not a `Tensor`.
</td>
</tr><tr>
<td>
`ValueError`
</td>
<td>
If hints are set incorrectly.
</td>
</tr>
</table>
<!-- Tabular view -->
<table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2"><h2 class="add-link">Attributes</h2></th></tr>
<tr>
<td>
`H`
</td>
<td>
Returns the adjoint of the current `LinearOperator`.
Given `A` representing this `LinearOperator`, return `A*`.
Note that calling `self.adjoint()` and `self.H` are equivalent.
</td>
</tr><tr>
<td>
`batch_shape`
</td>
<td>
`TensorShape` of batch dimensions of this `LinearOperator`.
If this operator acts like the batch matrix `A` with
`A.shape = [B1,...,Bb, M, N]`, then this returns
`TensorShape([B1,...,Bb])`, equivalent to `A.shape[:-2]`
</td>
</tr><tr>
<td>
`domain_dimension`
</td>
<td>
Dimension (in the sense of vector spaces) of the domain of this operator.
If this operator acts like the batch matrix `A` with
`A.shape = [B1,...,Bb, M, N]`, then this returns `N`.
</td>
</tr><tr>
<td>
`dtype`
</td>
<td>
The `DType` of `Tensor`s handled by this `LinearOperator`.
</td>
</tr><tr>
<td>
`graph_parents`
</td>
<td>
List of graph dependencies of this `LinearOperator`. (deprecated)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version.
Instructions for updating:
Do not call `graph_parents`.
</td>
</tr><tr>
<td>
`is_non_singular`
</td>
<td>
</td>
</tr><tr>
<td>
`is_positive_definite`
</td>
<td>
</td>
</tr><tr>
<td>
`is_self_adjoint`
</td>
<td>
</td>
</tr><tr>
<td>
`is_square`
</td>
<td>
Return `True/False` depending on if this operator is square.
</td>
</tr><tr>
<td>
`parameters`
</td>
<td>
Dictionary of parameters used to instantiate this `LinearOperator`.
</td>
</tr><tr>
<td>
`range_dimension`
</td>
<td>
Dimension (in the sense of vector spaces) of the range of this operator.
If this operator acts like the batch matrix `A` with
`A.shape = [B1,...,Bb, M, N]`, then this returns `M`.
</td>
</tr><tr>
<td>
`shape`
</td>
<td>
`TensorShape` of this `LinearOperator`.
If this operator acts like the batch matrix `A` with
`A.shape = [B1,...,Bb, M, N]`, then this returns
`TensorShape([B1,...,Bb, M, N])`, equivalent to `A.shape`.
</td>
</tr><tr>
<td>
`tensor_rank`
</td>
<td>
Rank (in the sense of tensors) of matrix corresponding to this operator.
If this operator acts like the batch matrix `A` with
`A.shape = [B1,...,Bb, M, N]`, then this returns `b + 2`.
</td>
</tr>
</table>
## Methods
<h3 id="add_to_tensor"><code>add_to_tensor</code></h3>
<a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/v2.4.0/tensorflow/python/ops/linalg/linear_operator.py#L1077-L1090">View source</a>
<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>add_to_tensor(
x, name='add_to_tensor'
)
</code></pre>
Add matrix represented by this operator to `x`. Equivalent to `A + x`.
<!-- Tabular view -->
<table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>
<tr>
<td>
`x`
</td>
<td>
`Tensor` with same `dtype` and shape broadcastable to `self.shape`.
</td>
</tr><tr>
<td>
`name`
</td>
<td>
A name to give this `Op`.
</td>
</tr>
</table>
<!-- Tabular view -->
<table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>
<tr class="alt">
<td colspan="2">
A `Tensor` with broadcast shape and same `dtype` as `self`.
</td>
</tr>
</table>
<h3 id="adjoint"><code>adjoint</code></h3>
<a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/v2.4.0/tensorflow/python/ops/linalg/linear_operator.py#L933-L948">View source</a>
<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>adjoint(
name='adjoint'
)
</code></pre>
Returns the adjoint of the current `LinearOperator`.
Given `A` representing this `LinearOperator`, return `A*`.
Note that calling `self.adjoint()` and `self.H` are equivalent.
<!-- Tabular view -->
<table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>
<tr>
<td>
`name`
</td>
<td>
A name for this `Op`.
</td>
</tr>
</table>
<!-- Tabular view -->
<table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>
<tr class="alt">
<td colspan="2">
`LinearOperator` which represents the adjoint of this `LinearOperator`.
</td>
</tr>
</table>
<h3 id="assert_non_singular"><code>assert_non_singular</code></h3>
<a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/v2.4.0/tensorflow/python/ops/linalg/linear_operator.py#L541-L559">View source</a>
<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>assert_non_singular(
name='assert_non_singular'
)
</code></pre>
Returns an `Op` that asserts this operator is non singular.
This operator is considered non-singular if
ConditionNumber < max{100, range_dimension, domain_dimension} * eps, eps := np.finfo(self.dtype.as_numpy_dtype).eps ```
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperator |
tf.linalg.LinearOperatorAdjoint View source on GitHub LinearOperator representing the adjoint of another operator. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorAdjoint
tf.linalg.LinearOperatorAdjoint(
operator, is_non_singular=None, is_self_adjoint=None, is_positive_definite=None,
is_square=None, name=None
)
This operator represents the adjoint of another operator. # Create a 2 x 2 linear operator.
operator = LinearOperatorFullMatrix([[1 - i., 3.], [0., 1. + i]])
operator_adjoint = LinearOperatorAdjoint(operator)
operator_adjoint.to_dense()
==> [[1. + i, 0.]
[3., 1 - i]]
operator_adjoint.shape
==> [2, 2]
operator_adjoint.log_abs_determinant()
==> - log(2)
x = ... Shape [2, 4] Tensor
operator_adjoint.matmul(x)
==> Shape [2, 4] Tensor, equal to operator.matmul(x, adjoint=True)
Performance The performance of LinearOperatorAdjoint depends on the underlying operators performance. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
operator LinearOperator object.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator. Default is operator.name + "_adjoint".
Raises
ValueError If operator.is_non_singular is False.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
operator The operator before taking the adjoint.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatoradjoint |
tf.linalg.LinearOperatorBlockDiag View source on GitHub Combines one or more LinearOperators in to a Block Diagonal matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorBlockDiag
tf.linalg.LinearOperatorBlockDiag(
operators, is_non_singular=None, is_self_adjoint=None,
is_positive_definite=None, is_square=True, name=None
)
This operator combines one or more linear operators [op1,...,opJ], building a new LinearOperator, whose underlying matrix representation is square and has each operator opi on the main diagonal, and zero's elsewhere. Shape compatibility If opj acts like a [batch] square matrix Aj, then op_combined acts like the [batch] square matrix formed by having each matrix Aj on the main diagonal. Each opj is required to represent a square matrix, and hence will have shape batch_shape_j + [M_j, M_j]. If opj has shape batch_shape_j + [M_j, M_j], then the combined operator has shape broadcast_batch_shape + [sum M_j, sum M_j], where broadcast_batch_shape is the mutual broadcast of batch_shape_j, j = 1,...,J, assuming the intermediate batch shapes broadcast. Even if the combined shape is well defined, the combined operator's methods may fail due to lack of broadcasting ability in the defining operators' methods. Arguments to matmul, matvec, solve, and solvevec may either be single Tensors or lists of Tensors that are interpreted as blocks. The jth element of a blockwise list of Tensors must have dimensions that match opj for the given method. If a list of blocks is input, then a list of blocks is returned as well. # Create a 4 x 4 linear operator combined of two 2 x 2 operators.
operator_1 = LinearOperatorFullMatrix([[1., 2.], [3., 4.]])
operator_2 = LinearOperatorFullMatrix([[1., 0.], [0., 1.]])
operator = LinearOperatorBlockDiag([operator_1, operator_2])
operator.to_dense()
==> [[1., 2., 0., 0.],
[3., 4., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]]
operator.shape
==> [4, 4]
operator.log_abs_determinant()
==> scalar Tensor
x1 = ... # Shape [2, 2] Tensor
x2 = ... # Shape [2, 2] Tensor
x = tf.concat([x1, x2], 0) # Shape [2, 4] Tensor
operator.matmul(x)
==> tf.concat([operator_1.matmul(x1), operator_2.matmul(x2)])
# Create a [2, 3] batch of 4 x 4 linear operators.
matrix_44 = tf.random.normal(shape=[2, 3, 4, 4])
operator_44 = LinearOperatorFullMatrix(matrix)
# Create a [1, 3] batch of 5 x 5 linear operators.
matrix_55 = tf.random.normal(shape=[1, 3, 5, 5])
operator_55 = LinearOperatorFullMatrix(matrix_55)
# Combine to create a [2, 3] batch of 9 x 9 operators.
operator_99 = LinearOperatorBlockDiag([operator_44, operator_55])
# Create a shape [2, 3, 9] vector.
x = tf.random.normal(shape=[2, 3, 9])
operator_99.matmul(x)
==> Shape [2, 3, 9] Tensor
# Create a blockwise list of vectors.
x = [tf.random.normal(shape=[2, 3, 4]), tf.random.normal(shape=[2, 3, 5])]
operator_99.matmul(x)
==> [Shape [2, 3, 4] Tensor, Shape [2, 3, 5] Tensor]
Performance The performance of LinearOperatorBlockDiag on any operation is equal to the sum of the individual operators' operations. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
operators Iterable of LinearOperator objects, each with the same dtype and composable shape.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices. This is true by default, and will raise a ValueError otherwise.
name A name for this LinearOperator. Default is the individual operators names joined with _o_.
Raises
TypeError If all operators do not have the same dtype.
ValueError If operators is empty or are non-square.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
operators
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator, Tensor with compatible shape and same dtype as self, or a blockwise iterable of LinearOperators or Tensors. See class docstring for definition of shape compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self, or if x is blockwise, a list of Tensors with shapes that concatenate to [..., M, R].
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matric A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self, or an iterable of Tensors (for blockwise operators). Tensors are treated a [batch] vectors, meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape, or a list of Tensors (for blockwise operators). Tensors are treated like a [batch] matrices meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator, or list of Tensors (for blockwise operators). Tensors are treated as [batch] vectors, meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorblockdiag |
tf.linalg.LinearOperatorBlockLowerTriangular Combines LinearOperators into a blockwise lower-triangular matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorBlockLowerTriangular
tf.linalg.LinearOperatorBlockLowerTriangular(
operators, is_non_singular=None, is_self_adjoint=None,
is_positive_definite=None, is_square=None,
name='LinearOperatorBlockLowerTriangular'
)
This operator is initialized with a nested list of linear operators, which are combined into a new LinearOperator whose underlying matrix representation is square and has each operator on or below the main diagonal, and zero's elsewhere. Each element of the outer list is a list of LinearOperators corresponding to a row-partition of the blockwise structure. The number of LinearOperators in row-partion i must be equal to i. For example, a blockwise 3 x 3 LinearOperatorBlockLowerTriangular is initialized with the list [[op_00], [op_10, op_11], [op_20, op_21, op_22]], where the op_ij, i < 3, j <= i, are LinearOperator instances. The LinearOperatorBlockLowerTriangular behaves as the following blockwise matrix, where 0 represents appropriately-sized [batch] matrices of zeros: [[op_00, 0, 0],
[op_10, op_11, 0],
[op_20, op_21, op_22]]
Each op_jj on the diagonal is required to represent a square matrix, and hence will have shape batch_shape_j + [M_j, M_j]. LinearOperators in row j of the blockwise structure must have range_dimension equal to that of op_jj, and LinearOperators in column j must have domain_dimension equal to that of op_jj. If each op_jj on the diagonal has shape batch_shape_j + [M_j, M_j], then the combined operator has shape broadcast_batch_shape + [sum M_j, sum M_j], where broadcast_batch_shape is the mutual broadcast of batch_shape_j, j = 0, 1, ..., J, assuming the intermediate batch shapes broadcast. Even if the combined shape is well defined, the combined operator's methods may fail due to lack of broadcasting ability in the defining operators' methods. For example, to create a 4 x 4 linear operator combined of three 2 x 2 operators: >>> operator_0 = tf.linalg.LinearOperatorFullMatrix([[1., 2.], [3., 4.]])
>>> operator_1 = tf.linalg.LinearOperatorFullMatrix([[1., 0.], [0., 1.]])
>>> operator_2 = tf.linalg.LinearOperatorLowerTriangular([[5., 6.], [7., 8]])
>>> operator = LinearOperatorBlockLowerTriangular(
... [[operator_0], [operator_1, operator_2]])
operator.to_dense()
<tf.Tensor: shape=(4, 4), dtype=float32, numpy=
array([[1., 2., 0., 0.],
[3., 4., 0., 0.],
[1., 0., 5., 0.],
[0., 1., 7., 8.]], dtype=float32)>
operator.shape
TensorShape([4, 4])
operator.log_abs_determinant()
<tf.Tensor: shape=(), dtype=float32, numpy=4.3820267>
x0 = [[1., 6.], [-3., 4.]]
x1 = [[0., 2.], [4., 0.]]
x = tf.concat([x0, x1], 0) # Shape [2, 4] Tensor
operator.matmul(x)
<tf.Tensor: shape=(4, 2), dtype=float32, numpy=
array([[-5., 14.],
[-9., 34.],
[ 1., 16.],
[29., 18.]], dtype=float32)>
The above matmul is equivalent to: >>> tf.concat([operator_0.matmul(x0),
... operator_1.matmul(x0) + operator_2.matmul(x1)], axis=0)
<tf.Tensor: shape=(4, 2), dtype=float32, numpy=
array([[-5., 14.],
[-9., 34.],
[ 1., 16.],
[29., 18.]], dtype=float32)>
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [M, N], with b >= 0
x.shape = [B1,...,Bb] + [N, R], with R >= 0.
For example: Create a [2, 3] batch of 4 x 4 linear operators: >>> matrix_44 = tf.random.normal(shape=[2, 3, 4, 4])
>>> operator_44 = tf.linalg.LinearOperatorFullMatrix(matrix_44)
Create a [1, 3] batch of 5 x 4 linear operators: >>> matrix_54 = tf.random.normal(shape=[1, 3, 5, 4])
>>> operator_54 = tf.linalg.LinearOperatorFullMatrix(matrix_54)
Create a [1, 3] batch of 5 x 5 linear operators: >>> matrix_55 = tf.random.normal(shape=[1, 3, 5, 5])
>>> operator_55 = tf.linalg.LinearOperatorFullMatrix(matrix_55)
Combine to create a [2, 3] batch of 9 x 9 operators: >>> operator_99 = LinearOperatorBlockLowerTriangular(
... [[operator_44], [operator_54, operator_55]])
>>> operator_99.shape
TensorShape([2, 3, 9, 9])
Create a shape [2, 1, 9] batch of vectors and apply the operator to it. >>> x = tf.random.normal(shape=[2, 1, 9])
>>> y = operator_99.matvec(x)
>>> y.shape
TensorShape([2, 3, 9])
Create a blockwise list of vectors and apply the operator to it. A blockwise list is returned. >>> x4 = tf.random.normal(shape=[2, 1, 4])
>>> x5 = tf.random.normal(shape=[2, 3, 5])
>>> y_blockwise = operator_99.matvec([x4, x5])
>>> y_blockwise[0].shape
TensorShape([2, 3, 4])
>>> y_blockwise[1].shape
TensorShape([2, 3, 5])
Performance Suppose operator is a LinearOperatorBlockLowerTriangular consisting of D row-partitions and D column-partitions, such that the total number of operators is N = D * (D + 1) // 2.
operator.matmul has complexity equal to the sum of the matmul complexities of the individual operators.
operator.solve has complexity equal to the sum of the solve complexities of the operators on the diagonal and the matmul complexities of the operators off the diagonal.
operator.determinant has complexity equal to the sum of the determinant complexities of the operators on the diagonal. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
operators Iterable of iterables of LinearOperator objects, each with the same dtype. Each element of operators corresponds to a row- partition, in top-to-bottom order. The operators in each row-partition are filled in left-to-right. For example, operators = [[op_0], [op_1, op_2], [op_3, op_4, op_5]] creates a LinearOperatorBlockLowerTriangular with full block structure [[op_0, 0, 0], [op_1, op_2, 0], [op_3, op_4, op_5]]. The number of operators in the ith row must be equal to i, such that each operator falls on or below the diagonal of the blockwise structure. LinearOperators that fall on the diagonal (the last elements of each row) must be square. The other LinearOperators must have domain dimension equal to the domain dimension of the LinearOperators in the same column-partition, and range dimension equal to the range dimension of the LinearOperators in the same row-partition.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices. This will raise a ValueError if set to False.
name A name for this LinearOperator.
Raises
TypeError If all operators do not have the same dtype.
ValueError If operators is empty, contains an erroneous number of elements, or contains operators with incompatible shapes.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
operators
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator, Tensor with compatible shape and same dtype as self, or a blockwise iterable of LinearOperators or Tensors. See class docstring for definition of shape compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self, or if x is blockwise, a list of Tensors with shapes that concatenate to [..., M, R].
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self, or an iterable of Tensors. Tensors are treated a [batch] vectors, meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Given the blockwise n + 1-by-n + 1 linear operator: op = [[A_00 0 ... 0 ... 0], [A_10 A_11 ... 0 ... 0], ... [A_k0 A_k1 ... A_kk ... 0], ... [A_n0 A_n1 ... A_nk ... A_nn]] we find x = op.solve(y) by observing that y_k = A_k0.matmul(x_0) + A_k1.matmul(x_1) + ... + A_kk.matmul(x_k) and therefore x_k = A_kk.solve(y_k - A_k0.matmul(x_0) - ... - A_k(k-1).matmul(x_(k-1))) where x_k and y_k are the kth blocks obtained by decomposing x and y along their appropriate axes. We first solve x_0 = A_00.solve(y_0). Proceeding inductively, we solve for x_k, k = 1..n, given x_0..x_(k-1). The adjoint case is solved similarly, beginning with x_n = A_nn.solve(y_n, adjoint=True) and proceeding backwards. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape, or a list of Tensors. Tensors are treated like a [batch] matrices meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator, or list of Tensors (for blockwise operators). Tensors are treated as [batch] vectors, meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorblocklowertriangular |
tf.linalg.LinearOperatorCirculant View source on GitHub LinearOperator acting like a circulant matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorCirculant
tf.linalg.LinearOperatorCirculant(
spectrum, input_output_dtype=tf.dtypes.complex64, is_non_singular=None,
is_self_adjoint=None, is_positive_definite=None, is_square=True,
name='LinearOperatorCirculant'
)
This operator acts like a circulant matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. Description in terms of circulant matrices Circulant means the entries of A are generated by a single vector, the convolution kernel h: A_{mn} := h_{m-n mod N}. With h = [w, x, y, z], A = |w z y x|
|x w z y|
|y x w z|
|z y x w|
This means that the result of matrix multiplication v = Au has Lth column given circular convolution between h with the Lth column of u. Description in terms of the frequency spectrum There is an equivalent description in terms of the [batch] spectrum H and Fourier transforms. Here we consider A.shape = [N, N] and ignore batch dimensions. Define the discrete Fourier transform (DFT) and its inverse by DFT[ h[n] ] = H[k] := sum_{n = 0}^{N - 1} h_n e^{-i 2pi k n / N}
IDFT[ H[k] ] = h[n] = N^{-1} sum_{k = 0}^{N - 1} H_k e^{i 2pi k n / N}
From these definitions, we see that H[0] = sum_{n = 0}^{N - 1} h_n
H[1] = "the first positive frequency"
H[N - 1] = "the first negative frequency"
Loosely speaking, with * element-wise multiplication, matrix multiplication is equal to the action of a Fourier multiplier: A u = IDFT[ H * DFT[u] ]. Precisely speaking, given [N, R] matrix u, let DFT[u] be the [N, R] matrix with rth column equal to the DFT of the rth column of u. Define the IDFT similarly. Matrix multiplication may be expressed columnwise: (A u)_r = IDFT[ H * (DFT[u])_r ] Operator properties deduced from the spectrum. Letting U be the kth Euclidean basis vector, and U = IDFT[u]. The above formulas show thatA U = H_k * U. We conclude that the elements of H are the eigenvalues of this operator. Therefore This operator is positive definite if and only if Real{H} > 0. A general property of Fourier transforms is the correspondence between Hermitian functions and real valued transforms. Suppose H.shape = [B1,...,Bb, N]. We say that H is a Hermitian spectrum if, with % meaning modulus division, H[..., n % N] = ComplexConjugate[ H[..., (-n) % N] ] This operator corresponds to a real matrix if and only if H is Hermitian. This operator is self-adjoint if and only if H is real. See e.g. "Discrete-Time Signal Processing", Oppenheim and Schafer. Example of a self-adjoint positive definite operator # spectrum is real ==> operator is self-adjoint
# spectrum is positive ==> operator is positive definite
spectrum = [6., 4, 2]
operator = LinearOperatorCirculant(spectrum)
# IFFT[spectrum]
operator.convolution_kernel()
==> [4 + 0j, 1 + 0.58j, 1 - 0.58j]
operator.to_dense()
==> [[4 + 0.0j, 1 - 0.6j, 1 + 0.6j],
[1 + 0.6j, 4 + 0.0j, 1 - 0.6j],
[1 - 0.6j, 1 + 0.6j, 4 + 0.0j]]
Example of defining in terms of a real convolution kernel # convolution_kernel is real ==> spectrum is Hermitian.
convolution_kernel = [1., 2., 1.]]
spectrum = tf.signal.fft(tf.cast(convolution_kernel, tf.complex64))
# spectrum is Hermitian ==> operator is real.
# spectrum is shape [3] ==> operator is shape [3, 3]
# We force the input/output type to be real, which allows this to operate
# like a real matrix.
operator = LinearOperatorCirculant(spectrum, input_output_dtype=tf.float32)
operator.to_dense()
==> [[ 1, 1, 2],
[ 2, 1, 1],
[ 1, 2, 1]]
Example of Hermitian spectrum # spectrum is shape [3] ==> operator is shape [3, 3]
# spectrum is Hermitian ==> operator is real.
spectrum = [1, 1j, -1j]
operator = LinearOperatorCirculant(spectrum)
operator.to_dense()
==> [[ 0.33 + 0j, 0.91 + 0j, -0.24 + 0j],
[-0.24 + 0j, 0.33 + 0j, 0.91 + 0j],
[ 0.91 + 0j, -0.24 + 0j, 0.33 + 0j]
Example of forcing real dtype when spectrum is Hermitian # spectrum is shape [4] ==> operator is shape [4, 4]
# spectrum is real ==> operator is self-adjoint
# spectrum is Hermitian ==> operator is real
# spectrum has positive real part ==> operator is positive-definite.
spectrum = [6., 4, 2, 4]
# Force the input dtype to be float32.
# Cast the output to float32. This is fine because the operator will be
# real due to Hermitian spectrum.
operator = LinearOperatorCirculant(spectrum, input_output_dtype=tf.float32)
operator.shape
==> [4, 4]
operator.to_dense()
==> [[4, 1, 0, 1],
[1, 4, 1, 0],
[0, 1, 4, 1],
[1, 0, 1, 4]]
# convolution_kernel = tf.signal.ifft(spectrum)
operator.convolution_kernel()
==> [4, 1, 0, 1]
Performance Suppose operator is a LinearOperatorCirculant of shape [N, N], and x.shape = [N, R]. Then
operator.matmul(x) is O(R*N*Log[N])
operator.solve(x) is O(R*N*Log[N])
operator.determinant() involves a size N reduce_prod. If instead operator and x have shape [B1,...,Bb, N, N] and [B1,...,Bb, N, R], every operation increases in complexity by B1*...*Bb. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way. References: Toeplitz and Circulant Matrices - A Review: Gray, 2006 (pdf)
Args
spectrum Shape [B1,...,Bb, N] Tensor. Allowed dtypes: float16, float32, float64, complex64, complex128. Type can be different than input_output_dtype
input_output_dtype dtype for input/output.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. If spectrum is real, this will always be true.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix\ Extension_for_non_symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name to prepend to all ops created by this class.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
block_depth Depth of recursively defined circulant blocks defining this Operator. With A the dense representation of this Operator, block_depth = 1 means A is symmetric circulant. For example, A = |w z y x|
|x w z y|
|y x w z|
|z y x w|
block_depth = 2 means A is block symmetric circulant with symmetric circulant blocks. For example, with W, X, Y, Z symmetric circulant, A = |W Z Y X|
|X W Z Y|
|Y X W Z|
|Z Y X W|
block_depth = 3 means A is block symmetric circulant with block symmetric circulant blocks.
block_shape
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
spectrum
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_hermitian_spectrum View source
assert_hermitian_spectrum(
name='assert_hermitian_spectrum'
)
Returns an Op that asserts this operator has Hermitian spectrum. This operator corresponds to a real-valued matrix if and only if its spectrum is Hermitian.
Args
name A name to give this Op.
Returns An Op that asserts this operator has Hermitian spectrum.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
block_shape_tensor View source
block_shape_tensor()
Shape of the block dimensions of self.spectrum. cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
convolution_kernel View source
convolution_kernel(
name='convolution_kernel'
)
Convolution kernel corresponding to self.spectrum. The D dimensional DFT of this kernel is the frequency domain spectrum of this operator.
Args
name A name to give this Op.
Returns Tensor with dtype self.dtype.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorcirculant |
tf.linalg.LinearOperatorCirculant2D View source on GitHub LinearOperator acting like a block circulant matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorCirculant2D
tf.linalg.LinearOperatorCirculant2D(
spectrum, input_output_dtype=tf.dtypes.complex64, is_non_singular=None,
is_self_adjoint=None, is_positive_definite=None, is_square=True,
name='LinearOperatorCirculant2D'
)
This operator acts like a block circulant matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. Description in terms of block circulant matrices If A is block circulant, with block sizes N0, N1 (N0 * N1 = N): A has a block circulant structure, composed of N0 x N0 blocks, with each block an N1 x N1 circulant matrix. For example, with W, X, Y, Z each circulant, A = |W Z Y X|
|X W Z Y|
|Y X W Z|
|Z Y X W|
Note that A itself will not in general be circulant. Description in terms of the frequency spectrum There is an equivalent description in terms of the [batch] spectrum H and Fourier transforms. Here we consider A.shape = [N, N] and ignore batch dimensions. If H.shape = [N0, N1], (N0 * N1 = N): Loosely speaking, matrix multiplication is equal to the action of a Fourier multiplier: A u = IDFT2[ H DFT2[u] ]. Precisely speaking, given [N, R] matrix u, let DFT2[u] be the [N0, N1, R] Tensor defined by re-shaping u to [N0, N1, R] and taking a two dimensional DFT across the first two dimensions. Let IDFT2 be the inverse of DFT2. Matrix multiplication may be expressed columnwise: (A u)_r = IDFT2[ H * (DFT2[u])_r ] Operator properties deduced from the spectrum. This operator is positive definite if and only if Real{H} > 0. A general property of Fourier transforms is the correspondence between Hermitian functions and real valued transforms. Suppose H.shape = [B1,...,Bb, N0, N1], we say that H is a Hermitian spectrum if, with % indicating modulus division, H[..., n0 % N0, n1 % N1] = ComplexConjugate[ H[..., (-n0) % N0, (-n1) % N1 ].
This operator corresponds to a real matrix if and only if H is Hermitian. This operator is self-adjoint if and only if H is real. See e.g. "Discrete-Time Signal Processing", Oppenheim and Schafer. Example of a self-adjoint positive definite operator # spectrum is real ==> operator is self-adjoint
# spectrum is positive ==> operator is positive definite
spectrum = [[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]]
operator = LinearOperatorCirculant2D(spectrum)
# IFFT[spectrum]
operator.convolution_kernel()
==> [[5.0+0.0j, -0.5-.3j, -0.5+.3j],
[-1.5-.9j, 0, 0],
[-1.5+.9j, 0, 0]]
operator.to_dense()
==> Complex self adjoint 9 x 9 matrix.
Example of defining in terms of a real convolution kernel, # convolution_kernel is real ==> spectrum is Hermitian.
convolution_kernel = [[1., 2., 1.], [5., -1., 1.]]
spectrum = tf.signal.fft2d(tf.cast(convolution_kernel, tf.complex64))
# spectrum is shape [2, 3] ==> operator is shape [6, 6]
# spectrum is Hermitian ==> operator is real.
operator = LinearOperatorCirculant2D(spectrum, input_output_dtype=tf.float32)
Performance Suppose operator is a LinearOperatorCirculant of shape [N, N], and x.shape = [N, R]. Then
operator.matmul(x) is O(R*N*Log[N])
operator.solve(x) is O(R*N*Log[N])
operator.determinant() involves a size N reduce_prod. If instead operator and x have shape [B1,...,Bb, N, N] and [B1,...,Bb, N, R], every operation increases in complexity by B1*...*Bb. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
spectrum Shape [B1,...,Bb, N] Tensor. Allowed dtypes: float16, float32, float64, complex64, complex128. Type can be different than input_output_dtype
input_output_dtype dtype for input/output.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. If spectrum is real, this will always be true.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix\ Extension_for_non_symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name to prepend to all ops created by this class.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
block_depth Depth of recursively defined circulant blocks defining this Operator. With A the dense representation of this Operator, block_depth = 1 means A is symmetric circulant. For example, A = |w z y x|
|x w z y|
|y x w z|
|z y x w|
block_depth = 2 means A is block symmetric circulant with symmetric circulant blocks. For example, with W, X, Y, Z symmetric circulant, A = |W Z Y X|
|X W Z Y|
|Y X W Z|
|Z Y X W|
block_depth = 3 means A is block symmetric circulant with block symmetric circulant blocks.
block_shape
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
spectrum
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_hermitian_spectrum View source
assert_hermitian_spectrum(
name='assert_hermitian_spectrum'
)
Returns an Op that asserts this operator has Hermitian spectrum. This operator corresponds to a real-valued matrix if and only if its spectrum is Hermitian.
Args
name A name to give this Op.
Returns An Op that asserts this operator has Hermitian spectrum.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
block_shape_tensor View source
block_shape_tensor()
Shape of the block dimensions of self.spectrum. cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
convolution_kernel View source
convolution_kernel(
name='convolution_kernel'
)
Convolution kernel corresponding to self.spectrum. The D dimensional DFT of this kernel is the frequency domain spectrum of this operator.
Args
name A name to give this Op.
Returns Tensor with dtype self.dtype.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorcirculant2d |
tf.linalg.LinearOperatorCirculant3D View source on GitHub LinearOperator acting like a nested block circulant matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorCirculant3D
tf.linalg.LinearOperatorCirculant3D(
spectrum, input_output_dtype=tf.dtypes.complex64, is_non_singular=None,
is_self_adjoint=None, is_positive_definite=None, is_square=True,
name='LinearOperatorCirculant3D'
)
This operator acts like a block circulant matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. Description in terms of block circulant matrices If A is nested block circulant, with block sizes N0, N1, N2 (N0 * N1 * N2 = N): A has a block structure, composed of N0 x N0 blocks, with each block an N1 x N1 block circulant matrix. For example, with W, X, Y, Z each block circulant, A = |W Z Y X|
|X W Z Y|
|Y X W Z|
|Z Y X W|
Note that A itself will not in general be circulant. Description in terms of the frequency spectrum There is an equivalent description in terms of the [batch] spectrum H and Fourier transforms. Here we consider A.shape = [N, N] and ignore batch dimensions. If H.shape = [N0, N1, N2], (N0 * N1 * N2 = N): Loosely speaking, matrix multiplication is equal to the action of a Fourier multiplier: A u = IDFT3[ H DFT3[u] ]. Precisely speaking, given [N, R] matrix u, let DFT3[u] be the [N0, N1, N2, R] Tensor defined by re-shaping u to [N0, N1, N2, R] and taking a three dimensional DFT across the first three dimensions. Let IDFT3 be the inverse of DFT3. Matrix multiplication may be expressed columnwise: (A u)_r = IDFT3[ H * (DFT3[u])_r ] Operator properties deduced from the spectrum. This operator is positive definite if and only if Real{H} > 0. A general property of Fourier transforms is the correspondence between Hermitian functions and real valued transforms. Suppose H.shape = [B1,...,Bb, N0, N1, N2], we say that H is a Hermitian spectrum if, with % meaning modulus division, H[..., n0 % N0, n1 % N1, n2 % N2]
= ComplexConjugate[ H[..., (-n0) % N0, (-n1) % N1, (-n2) % N2] ].
This operator corresponds to a real matrix if and only if H is Hermitian. This operator is self-adjoint if and only if H is real. See e.g. "Discrete-Time Signal Processing", Oppenheim and Schafer. Examples See LinearOperatorCirculant and LinearOperatorCirculant2D for examples. Performance Suppose operator is a LinearOperatorCirculant of shape [N, N], and x.shape = [N, R]. Then
operator.matmul(x) is O(R*N*Log[N])
operator.solve(x) is O(R*N*Log[N])
operator.determinant() involves a size N reduce_prod. If instead operator and x have shape [B1,...,Bb, N, N] and [B1,...,Bb, N, R], every operation increases in complexity by B1*...*Bb. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
spectrum Shape [B1,...,Bb, N] Tensor. Allowed dtypes: float16, float32, float64, complex64, complex128. Type can be different than input_output_dtype
input_output_dtype dtype for input/output.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. If spectrum is real, this will always be true.
is_positive_definite Expect that this operator is positive definite, meaning the real part of all eigenvalues is positive. We do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix Extension_for_non_symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name to prepend to all ops created by this class.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
block_depth Depth of recursively defined circulant blocks defining this Operator. With A the dense representation of this Operator, block_depth = 1 means A is symmetric circulant. For example, A = |w z y x|
|x w z y|
|y x w z|
|z y x w|
block_depth = 2 means A is block symmetric circulant with symmetric circulant blocks. For example, with W, X, Y, Z symmetric circulant, A = |W Z Y X|
|X W Z Y|
|Y X W Z|
|Z Y X W|
block_depth = 3 means A is block symmetric circulant with block symmetric circulant blocks.
block_shape
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
spectrum
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_hermitian_spectrum View source
assert_hermitian_spectrum(
name='assert_hermitian_spectrum'
)
Returns an Op that asserts this operator has Hermitian spectrum. This operator corresponds to a real-valued matrix if and only if its spectrum is Hermitian.
Args
name A name to give this Op.
Returns An Op that asserts this operator has Hermitian spectrum.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
block_shape_tensor View source
block_shape_tensor()
Shape of the block dimensions of self.spectrum. cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
convolution_kernel View source
convolution_kernel(
name='convolution_kernel'
)
Convolution kernel corresponding to self.spectrum. The D dimensional DFT of this kernel is the frequency domain spectrum of this operator.
Args
name A name to give this Op.
Returns Tensor with dtype self.dtype.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorcirculant3d |
tf.linalg.LinearOperatorComposition View source on GitHub Composes one or more LinearOperators. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorComposition
tf.linalg.LinearOperatorComposition(
operators, is_non_singular=None, is_self_adjoint=None,
is_positive_definite=None, is_square=None, name=None
)
This operator composes one or more linear operators [op1,...,opJ], building a new LinearOperator with action defined by: op_composed(x) := op1(op2(...(opJ(x)...))
If opj acts like [batch] matrix Aj, then op_composed acts like the [batch] matrix formed with the multiplication A1 A2...AJ. If opj has shape batch_shape_j + [M_j, N_j], then we must have N_j = M_{j+1}, in which case the composed operator has shape equal to broadcast_batch_shape + [M_1, N_J], where broadcast_batch_shape is the mutual broadcast of batch_shape_j, j = 1,...,J, assuming the intermediate batch shapes broadcast. Even if the composed shape is well defined, the composed operator's methods may fail due to lack of broadcasting ability in the defining operators' methods. # Create a 2 x 2 linear operator composed of two 2 x 2 operators.
operator_1 = LinearOperatorFullMatrix([[1., 2.], [3., 4.]])
operator_2 = LinearOperatorFullMatrix([[1., 0.], [0., 1.]])
operator = LinearOperatorComposition([operator_1, operator_2])
operator.to_dense()
==> [[1., 2.]
[3., 4.]]
operator.shape
==> [2, 2]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> Shape [2, 4] Tensor
# Create a [2, 3] batch of 4 x 5 linear operators.
matrix_45 = tf.random.normal(shape=[2, 3, 4, 5])
operator_45 = LinearOperatorFullMatrix(matrix)
# Create a [2, 3] batch of 5 x 6 linear operators.
matrix_56 = tf.random.normal(shape=[2, 3, 5, 6])
operator_56 = LinearOperatorFullMatrix(matrix_56)
# Compose to create a [2, 3] batch of 4 x 6 operators.
operator_46 = LinearOperatorComposition([operator_45, operator_56])
# Create a shape [2, 3, 6, 2] vector.
x = tf.random.normal(shape=[2, 3, 6, 2])
operator.matmul(x)
==> Shape [2, 3, 4, 2] Tensor
Performance The performance of LinearOperatorComposition on any operation is equal to the sum of the individual operators' operations. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
operators Iterable of LinearOperator objects, each with the same dtype and composable shape.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator. Default is the individual operators names joined with _o_.
Raises
TypeError If all operators do not have the same dtype.
ValueError If operators is empty.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
operators
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorcomposition |
tf.linalg.LinearOperatorDiag View source on GitHub LinearOperator acting like a [batch] square diagonal matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorDiag
tf.linalg.LinearOperatorDiag(
diag, is_non_singular=None, is_self_adjoint=None, is_positive_definite=None,
is_square=None, name='LinearOperatorDiag'
)
This operator acts like a [batch] diagonal matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. LinearOperatorDiag is initialized with a (batch) vector. # Create a 2 x 2 diagonal linear operator.
diag = [1., -1.]
operator = LinearOperatorDiag(diag)
operator.to_dense()
==> [[1., 0.]
[0., -1.]]
operator.shape
==> [2, 2]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> Shape [2, 4] Tensor
# Create a [2, 3] batch of 4 x 4 linear operators.
diag = tf.random.normal(shape=[2, 3, 4])
operator = LinearOperatorDiag(diag)
# Create a shape [2, 1, 4, 2] vector. Note that this shape is compatible
# since the batch dimensions, [2, 1], are broadcast to
# operator.batch_shape = [2, 3].
y = tf.random.normal(shape=[2, 1, 4, 2])
x = operator.solve(y)
==> operator.matmul(x) = y
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [C1,...,Cc] + [N, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]
Performance Suppose operator is a LinearOperatorDiag of shape [N, N], and x.shape = [N, R]. Then
operator.matmul(x) involves N * R multiplications.
operator.solve(x) involves N divisions and N * R multiplications.
operator.determinant() involves a size N reduce_prod. If instead operator and x have shape [B1,...,Bb, N, N] and [B1,...,Bb, N, R], every operation increases in complexity by B1*...*Bb. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
diag Shape [B1,...,Bb, N] Tensor with b >= 0 N >= 0. The diagonal of the operator. Allowed dtypes: float16, float32, float64, complex64, complex128.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. If diag.dtype is real, this is auto-set to True.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator.
Raises
TypeError If diag.dtype is not an allowed type.
ValueError If diag.dtype is real, and is_self_adjoint is not True.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
diag
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatordiag |
tf.linalg.LinearOperatorFullMatrix View source on GitHub LinearOperator that wraps a [batch] matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorFullMatrix
tf.linalg.LinearOperatorFullMatrix(
matrix, is_non_singular=None, is_self_adjoint=None, is_positive_definite=None,
is_square=None, name='LinearOperatorFullMatrix'
)
This operator wraps a [batch] matrix A (which is a Tensor) with shape [B1,...,Bb, M, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an M x N matrix. # Create a 2 x 2 linear operator.
matrix = [[1., 2.], [3., 4.]]
operator = LinearOperatorFullMatrix(matrix)
operator.to_dense()
==> [[1., 2.]
[3., 4.]]
operator.shape
==> [2, 2]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> Shape [2, 4] Tensor
# Create a [2, 3] batch of 4 x 4 linear operators.
matrix = tf.random.normal(shape=[2, 3, 4, 4])
operator = LinearOperatorFullMatrix(matrix)
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [M, N], with b >= 0
x.shape = [B1,...,Bb] + [N, R], with R >= 0.
Performance LinearOperatorFullMatrix has exactly the same performance as would be achieved by using standard TensorFlow matrix ops. Intelligent choices are made based on the following initialization hints. If dtype is real, and is_self_adjoint and is_positive_definite, a Cholesky factorization is used for the determinant and solve. In all cases, suppose operator is a LinearOperatorFullMatrix of shape [M, N], and x.shape = [N, R]. Then
operator.matmul(x) is O(M * N * R). If M=N, operator.solve(x) is O(N^3 * R). If M=N, operator.determinant() is O(N^3). If instead operator and x have shape [B1,...,Bb, M, N] and [B1,...,Bb, N, R], every operation increases in complexity by B1*...*Bb. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
matrix Shape [B1,...,Bb, M, N] with b >= 0, M, N >= 0. Allowed dtypes: float16, float32, float64, complex64, complex128.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator.
Raises
TypeError If diag.dtype is not an allowed type.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorfullmatrix |
tf.linalg.LinearOperatorHouseholder View source on GitHub LinearOperator acting like a [batch] of Householder transformations. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorHouseholder
tf.linalg.LinearOperatorHouseholder(
reflection_axis, is_non_singular=None, is_self_adjoint=None,
is_positive_definite=None, is_square=None,
name='LinearOperatorHouseholder'
)
This operator acts like a [batch] of householder reflections with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. LinearOperatorHouseholder is initialized with a (batch) vector. A Householder reflection, defined via a vector v, which reflects points in R^n about the hyperplane orthogonal to v and through the origin. # Create a 2 x 2 householder transform.
vec = [1 / np.sqrt(2), 1. / np.sqrt(2)]
operator = LinearOperatorHouseholder(vec)
operator.to_dense()
==> [[0., -1.]
[-1., -0.]]
operator.shape
==> [2, 2]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> Shape [2, 4] Tensor
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [C1,...,Cc] + [N, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]
Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
reflection_axis Shape [B1,...,Bb, N] Tensor with b >= 0 N >= 0. The vector defining the hyperplane to reflect about. Allowed dtypes: float16, float32, float64, complex64, complex128.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. This is autoset to true
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices This is autoset to false.
is_square Expect that this operator acts like square [batch] matrices. This is autoset to true.
name A name for this LinearOperator.
Raises
ValueError is_self_adjoint is not True, is_positive_definite is not False or is_square is not True.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
reflection_axis
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorhouseholder |
tf.linalg.LinearOperatorIdentity View source on GitHub LinearOperator acting like a [batch] square identity matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorIdentity
tf.linalg.LinearOperatorIdentity(
num_rows, batch_shape=None, dtype=None, is_non_singular=True,
is_self_adjoint=True, is_positive_definite=True, is_square=True,
assert_proper_shapes=False, name='LinearOperatorIdentity'
)
This operator acts like a [batch] identity matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. LinearOperatorIdentity is initialized with num_rows, and optionally batch_shape, and dtype arguments. If batch_shape is None, this operator efficiently passes through all arguments. If batch_shape is provided, broadcasting may occur, which will require making copies. # Create a 2 x 2 identity matrix.
operator = LinearOperatorIdentity(num_rows=2, dtype=tf.float32)
operator.to_dense()
==> [[1., 0.]
[0., 1.]]
operator.shape
==> [2, 2]
operator.log_abs_determinant()
==> 0.
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> Shape [2, 4] Tensor, same as x.
y = tf.random.normal(shape=[3, 2, 4])
# Note that y.shape is compatible with operator.shape because operator.shape
# is broadcast to [3, 2, 2].
# This broadcast does NOT require copying data, since we can infer that y
# will be passed through without changing shape. We are always able to infer
# this if the operator has no batch_shape.
x = operator.solve(y)
==> Shape [3, 2, 4] Tensor, same as y.
# Create a 2-batch of 2x2 identity matrices
operator = LinearOperatorIdentity(num_rows=2, batch_shape=[2])
operator.to_dense()
==> [[[1., 0.]
[0., 1.]],
[[1., 0.]
[0., 1.]]]
# Here, even though the operator has a batch shape, the input is the same as
# the output, so x can be passed through without a copy. The operator is able
# to detect that no broadcast is necessary because both x and the operator
# have statically defined shape.
x = ... Shape [2, 2, 3]
operator.matmul(x)
==> Shape [2, 2, 3] Tensor, same as x
# Here the operator and x have different batch_shape, and are broadcast.
# This requires a copy, since the output is different size than the input.
x = ... Shape [1, 2, 3]
operator.matmul(x)
==> Shape [2, 2, 3] Tensor, equal to [x, x]
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [C1,...,Cc] + [N, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]
Performance If batch_shape initialization arg is None:
operator.matmul(x) is O(1)
operator.solve(x) is O(1)
operator.determinant() is O(1)
If batch_shape initialization arg is provided, and static checks cannot rule out the need to broadcast:
operator.matmul(x) is O(D1*...*Dd*N*R)
operator.solve(x) is O(D1*...*Dd*N*R)
operator.determinant() is O(B1*...*Bb)
Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
num_rows Scalar non-negative integer Tensor. Number of rows in the corresponding identity matrix.
batch_shape Optional 1-D integer Tensor. The shape of the leading dimensions. If None, this operator has no leading dimensions.
dtype Data type of the matrix that this operator represents.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
assert_proper_shapes Python bool. If False, only perform static checks that initialization and method arguments have proper shape. If True, and static checks are inconclusive, add asserts to the graph.
name A name for this LinearOperator
Raises
ValueError If num_rows is determined statically to be non-scalar, or negative.
ValueError If batch_shape is determined statically to not be 1-D, or negative.
ValueError If any of the following is not True: {is_self_adjoint, is_non_singular, is_positive_definite}.
TypeError If num_rows or batch_shape is ref-type (e.g. Variable).
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
mat, name='add_to_tensor'
)
Add matrix represented by this operator to mat. Equiv to I + mat.
Args
mat Tensor with same dtype and shape broadcastable to self.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatoridentity |
tf.linalg.LinearOperatorInversion View source on GitHub LinearOperator representing the inverse of another operator. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorInversion
tf.linalg.LinearOperatorInversion(
operator, is_non_singular=None, is_self_adjoint=None, is_positive_definite=None,
is_square=None, name=None
)
This operator represents the inverse of another operator. # Create a 2 x 2 linear operator.
operator = LinearOperatorFullMatrix([[1., 0.], [0., 2.]])
operator_inv = LinearOperatorInversion(operator)
operator_inv.to_dense()
==> [[1., 0.]
[0., 0.5]]
operator_inv.shape
==> [2, 2]
operator_inv.log_abs_determinant()
==> - log(2)
x = ... Shape [2, 4] Tensor
operator_inv.matmul(x)
==> Shape [2, 4] Tensor, equal to operator.solve(x)
Performance The performance of LinearOperatorInversion depends on the underlying operators performance: solve and matmul are swapped, and determinant is inverted. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
operator LinearOperator object. If operator.is_non_singular == False, an exception is raised. We do allow operator.is_non_singular == None, in which case this operator will have is_non_singular == None. Similarly for is_self_adjoint and is_positive_definite.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator. Default is operator.name + "_inv".
Raises
ValueError If operator.is_non_singular is False.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
operator The operator before inversion.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorinversion |
tf.linalg.LinearOperatorKronecker View source on GitHub Kronecker product between two LinearOperators. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorKronecker
tf.linalg.LinearOperatorKronecker(
operators, is_non_singular=None, is_self_adjoint=None,
is_positive_definite=None, is_square=None, name=None
)
This operator composes one or more linear operators [op1,...,opJ], building a new LinearOperator representing the Kronecker product: op1 x op2 x .. opJ (we omit parentheses as the Kronecker product is associative). If opj has shape batch_shape_j + [M_j, N_j], then the composed operator will have shape equal to broadcast_batch_shape + [prod M_j, prod N_j], where the product is over all operators. # Create a 4 x 4 linear operator composed of two 2 x 2 operators.
operator_1 = LinearOperatorFullMatrix([[1., 2.], [3., 4.]])
operator_2 = LinearOperatorFullMatrix([[1., 0.], [2., 1.]])
operator = LinearOperatorKronecker([operator_1, operator_2])
operator.to_dense()
==> [[1., 0., 2., 0.],
[2., 1., 4., 2.],
[3., 0., 4., 0.],
[6., 3., 8., 4.]]
operator.shape
==> [4, 4]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [4, 2] Tensor
operator.matmul(x)
==> Shape [4, 2] Tensor
# Create a [2, 3] batch of 4 x 5 linear operators.
matrix_45 = tf.random.normal(shape=[2, 3, 4, 5])
operator_45 = LinearOperatorFullMatrix(matrix)
# Create a [2, 3] batch of 5 x 6 linear operators.
matrix_56 = tf.random.normal(shape=[2, 3, 5, 6])
operator_56 = LinearOperatorFullMatrix(matrix_56)
# Compose to create a [2, 3] batch of 20 x 30 operators.
operator_large = LinearOperatorKronecker([operator_45, operator_56])
# Create a shape [2, 3, 20, 2] vector.
x = tf.random.normal(shape=[2, 3, 6, 2])
operator_large.matmul(x)
==> Shape [2, 3, 30, 2] Tensor
Performance The performance of LinearOperatorKronecker on any operation is equal to the sum of the individual operators' operations. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
operators Iterable of LinearOperator objects, each with the same dtype and composable shape, representing the Kronecker factors.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix\ Extension_for_non_symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator. Default is the individual operators names joined with _x_.
Raises
TypeError If all operators do not have the same dtype.
ValueError If operators is empty.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
operators
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorkronecker |
tf.linalg.LinearOperatorLowerTriangular View source on GitHub LinearOperator acting like a [batch] square lower triangular matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorLowerTriangular
tf.linalg.LinearOperatorLowerTriangular(
tril, is_non_singular=None, is_self_adjoint=None, is_positive_definite=None,
is_square=None, name='LinearOperatorLowerTriangular'
)
This operator acts like a [batch] lower triangular matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. LinearOperatorLowerTriangular is initialized with a Tensor having dimensions [B1,...,Bb, N, N]. The upper triangle of the last two dimensions is ignored. # Create a 2 x 2 lower-triangular linear operator.
tril = [[1., 2.], [3., 4.]]
operator = LinearOperatorLowerTriangular(tril)
# The upper triangle is ignored.
operator.to_dense()
==> [[1., 0.]
[3., 4.]]
operator.shape
==> [2, 2]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> Shape [2, 4] Tensor
# Create a [2, 3] batch of 4 x 4 linear operators.
tril = tf.random.normal(shape=[2, 3, 4, 4])
operator = LinearOperatorLowerTriangular(tril)
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [B1,...,Bb] + [N, R], with R >= 0.
Performance Suppose operator is a LinearOperatorLowerTriangular of shape [N, N], and x.shape = [N, R]. Then
operator.matmul(x) involves N^2 * R multiplications.
operator.solve(x) involves N * R size N back-substitutions.
operator.determinant() involves a size N reduce_prod. If instead operator and x have shape [B1,...,Bb, N, N] and [B1,...,Bb, N, R], every operation increases in complexity by B1*...*Bb. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
tril Shape [B1,...,Bb, N, N] with b >= 0, N >= 0. The lower triangular part of tril defines this operator. The strictly upper triangle is ignored.
is_non_singular Expect that this operator is non-singular. This operator is non-singular if and only if its diagonal elements are all non-zero.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. This operator is self-adjoint only if it is diagonal with real-valued diagonal entries. In this case it is advised to use LinearOperatorDiag.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator.
Raises
ValueError If is_square is False.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorlowertriangular |
tf.linalg.LinearOperatorLowRankUpdate View source on GitHub Perturb a LinearOperator with a rank K update. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorLowRankUpdate
tf.linalg.LinearOperatorLowRankUpdate(
base_operator, u, diag_update=None, v=None, is_diag_update_positive=None,
is_non_singular=None, is_self_adjoint=None, is_positive_definite=None,
is_square=None, name='LinearOperatorLowRankUpdate'
)
This operator acts like a [batch] matrix A with shape [B1,...,Bb, M, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an M x N matrix. LinearOperatorLowRankUpdate represents A = L + U D V^H, where L, is a LinearOperator representing [batch] M x N matrices
U, is a [batch] M x K matrix. Typically K << M.
D, is a [batch] K x K matrix.
V, is a [batch] N x K matrix. Typically K << N.
V^H is the Hermitian transpose (adjoint) of V.
If M = N, determinants and solves are done using the matrix determinant lemma and Woodbury identities, and thus require L and D to be non-singular. Solves and determinants will be attempted unless the "is_non_singular" property of L and D is False. In the event that L and D are positive-definite, and U = V, solves and determinants can be done using a Cholesky factorization. # Create a 3 x 3 diagonal linear operator.
diag_operator = LinearOperatorDiag(
diag_update=[1., 2., 3.], is_non_singular=True, is_self_adjoint=True,
is_positive_definite=True)
# Perturb with a rank 2 perturbation
operator = LinearOperatorLowRankUpdate(
operator=diag_operator,
u=[[1., 2.], [-1., 3.], [0., 0.]],
diag_update=[11., 12.],
v=[[1., 2.], [-1., 3.], [10., 10.]])
operator.shape
==> [3, 3]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [3, 4] Tensor
operator.matmul(x)
==> Shape [3, 4] Tensor
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [M, N], with b >= 0
x.shape = [B1,...,Bb] + [N, R], with R >= 0.
Performance Suppose operator is a LinearOperatorLowRankUpdate of shape [M, N], made from a rank K update of base_operator which performs .matmul(x) on x having x.shape = [N, R] with O(L_matmul*N*R) complexity (and similarly for solve, determinant. Then, if x.shape = [N, R],
operator.matmul(x) is O(L_matmul*N*R + K*N*R)
and if M = N,
operator.solve(x) is O(L_matmul*N*R + N*K*R + K^2*R + K^3)
operator.determinant() is O(L_determinant + L_solve*N*K + K^2*N + K^3)
If instead operator and x have shape [B1,...,Bb, M, N] and [B1,...,Bb, N, R], every operation increases in complexity by B1*...*Bb. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, diag_update_positive and square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
base_operator Shape [B1,...,Bb, M, N].
u Shape [B1,...,Bb, M, K] Tensor of same dtype as base_operator. This is U above.
diag_update Optional shape [B1,...,Bb, K] Tensor with same dtype as base_operator. This is the diagonal of D above. Defaults to D being the identity operator.
v Optional Tensor of same dtype as u and shape [B1,...,Bb, N, K] Defaults to v = u, in which case the perturbation is symmetric. If M != N, then v must be set since the perturbation is not square.
is_diag_update_positive Python bool. If True, expect diag_update > 0.
is_non_singular Expect that this operator is non-singular. Default is None, unless is_positive_definite is auto-set to be True (see below).
is_self_adjoint Expect that this operator is equal to its hermitian transpose. Default is None, unless base_operator is self-adjoint and v = None (meaning u=v), in which case this defaults to True.
is_positive_definite Expect that this operator is positive definite. Default is None, unless base_operator is positive-definite v = None (meaning u=v), and is_diag_update_positive, in which case this defaults to True. Note that we say an operator is positive definite when the quadratic form x^H A x has positive real part for all nonzero x.
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator.
Raises
ValueError If is_X flags are set in an inconsistent way.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
base_operator If this operator is A = L + U D V^H, this is the L.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
diag_operator If this operator is A = L + U D V^H, this is D.
diag_update If this operator is A = L + U D V^H, this is the diagonal of D.
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_diag_update_positive If this operator is A = L + U D V^H, this hints D > 0 elementwise.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
u If this operator is A = L + U D V^H, this is the U.
v If this operator is A = L + U D V^H, this is the V. Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorlowrankupdate |
tf.linalg.LinearOperatorPermutation LinearOperator acting like a [batch] of permutation matrices. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorPermutation
tf.linalg.LinearOperatorPermutation(
perm, dtype=tf.dtypes.float32, is_non_singular=None, is_self_adjoint=None,
is_positive_definite=None, is_square=None,
name='LinearOperatorPermutation'
)
This operator acts like a [batch] of permutations with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. LinearOperatorPermutation is initialized with a (batch) vector. A permutation, is defined by an integer vector v whose values are unique and are in the range [0, ... n]. Applying the permutation on an input matrix has the folllowing meaning: the value of v at index i says to move the v[i]-th row of the input matrix to the i-th row. Because all values are unique, this will result in a permutation of the rows the input matrix. Note, that the permutation vector v has the same semantics as tf.transpose. # Create a 3 x 3 permutation matrix that swaps the last two columns.
vec = [0, 2, 1]
operator = LinearOperatorPermutation(vec)
operator.to_dense()
==> [[1., 0., 0.]
[0., 0., 1.]
[0., 1., 0.]]
operator.shape
==> [3, 3]
# This will be zero.
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [3, 4] Tensor
operator.matmul(x)
==> Shape [3, 4] Tensor
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [C1,...,Cc] + [N, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]
Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
perm Shape [B1,...,Bb, N] Integer Tensor with b >= 0 N >= 0. An integer vector that represents the permutation to apply. Note that this argument is same as tf.transpose. However, this permutation is applied on the rows, while the permutation in tf.transpose is applied on the dimensions of the Tensor. perm is required to have unique entries from {0, 1, ... N-1}.
dtype The dtype of arguments to this operator. Default: float32. Allowed dtypes: float16, float32, float64, complex64, complex128.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. This is autoset to true
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices This is autoset to false.
is_square Expect that this operator acts like square [batch] matrices. This is autoset to true.
name A name for this LinearOperator.
Raises
ValueError is_self_adjoint is not True, is_positive_definite is not False or is_square is not True.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
perm
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorpermutation |
tf.linalg.LinearOperatorScaledIdentity View source on GitHub LinearOperator acting like a scaled [batch] identity matrix A = c I. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorScaledIdentity
tf.linalg.LinearOperatorScaledIdentity(
num_rows, multiplier, is_non_singular=None, is_self_adjoint=None,
is_positive_definite=None, is_square=True, assert_proper_shapes=False,
name='LinearOperatorScaledIdentity'
)
This operator acts like a scaled [batch] identity matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is a scaled version of the N x N identity matrix. LinearOperatorIdentity is initialized with num_rows, and a multiplier (a Tensor) of shape [B1,...,Bb]. N is set to num_rows, and the multiplier determines the scale for each batch member. # Create a 2 x 2 scaled identity matrix.
operator = LinearOperatorIdentity(num_rows=2, multiplier=3.)
operator.to_dense()
==> [[3., 0.]
[0., 3.]]
operator.shape
==> [2, 2]
operator.log_abs_determinant()
==> 2 * Log[3]
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> 3 * x
y = tf.random.normal(shape=[3, 2, 4])
# Note that y.shape is compatible with operator.shape because operator.shape
# is broadcast to [3, 2, 2].
x = operator.solve(y)
==> 3 * x
# Create a 2-batch of 2x2 identity matrices
operator = LinearOperatorIdentity(num_rows=2, multiplier=5.)
operator.to_dense()
==> [[[5., 0.]
[0., 5.]],
[[5., 0.]
[0., 5.]]]
x = ... Shape [2, 2, 3]
operator.matmul(x)
==> 5 * x
# Here the operator and x have different batch_shape, and are broadcast.
x = ... Shape [1, 2, 3]
operator.matmul(x)
==> 5 * x
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [C1,...,Cc] + [N, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]
Performance
operator.matmul(x) is O(D1*...*Dd*N*R)
operator.solve(x) is O(D1*...*Dd*N*R)
operator.determinant() is O(D1*...*Dd)
Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
num_rows Scalar non-negative integer Tensor. Number of rows in the corresponding identity matrix.
multiplier Tensor of shape [B1,...,Bb], or [] (a scalar).
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
assert_proper_shapes Python bool. If False, only perform static checks that initialization and method arguments have proper shape. If True, and static checks are inconclusive, add asserts to the graph.
name A name for this LinearOperator
Raises
ValueError If num_rows is determined statically to be non-scalar, or negative.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
multiplier The [batch] scalar Tensor, c in cI.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
mat, name='add_to_tensor'
)
Add matrix represented by this operator to mat. Equiv to I + mat.
Args
mat Tensor with same dtype and shape broadcastable to self.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorscaledidentity |
tf.linalg.LinearOperatorToeplitz View source on GitHub LinearOperator acting like a [batch] of toeplitz matrices. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorToeplitz
tf.linalg.LinearOperatorToeplitz(
col, row, is_non_singular=None, is_self_adjoint=None, is_positive_definite=None,
is_square=None, name='LinearOperatorToeplitz'
)
This operator acts like a [batch] Toeplitz matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x N matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. Description in terms of toeplitz matrices Toeplitz means that A has constant diagonals. Hence, A can be generated with two vectors. One represents the first column of the matrix, and the other represents the first row. Below is a 4 x 4 example: A = |a b c d|
|e a b c|
|f e a b|
|g f e a|
Example of a Toeplitz operator. # Create a 3 x 3 Toeplitz operator.
col = [1., 2., 3.]
row = [1., 4., -9.]
operator = LinearOperatorToeplitz(col, row)
operator.to_dense()
==> [[1., 4., -9.],
[2., 1., 4.],
[3., 2., 1.]]
operator.shape
==> [3, 3]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [3, 4] Tensor
operator.matmul(x)
==> Shape [3, 4] Tensor
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [C1,...,Cc] + [N, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]
Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
col Shape [B1,...,Bb, N] Tensor with b >= 0 N >= 0. The first column of the operator. Allowed dtypes: float16, float32, float64, complex64, complex128. Note that the first entry of col is assumed to be the same as the first entry of row.
row Shape [B1,...,Bb, N] Tensor with b >= 0 N >= 0. The first row of the operator. Allowed dtypes: float16, float32, float64, complex64, complex128. Note that the first entry of row is assumed to be the same as the first entry of col.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. If diag.dtype is real, this is auto-set to True.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
col
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
row
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatortoeplitz |
tf.linalg.LinearOperatorTridiag LinearOperator acting like a [batch] square tridiagonal matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorTridiag
tf.linalg.LinearOperatorTridiag(
diagonals, diagonals_format=_COMPACT, is_non_singular=None,
is_self_adjoint=None, is_positive_definite=None, is_square=None,
name='LinearOperatorTridiag'
)
This operator acts like a [batch] square tridiagonal matrix A with shape [B1,...,Bb, N, N] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x M matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. Example usage: Create a 3 x 3 tridiagonal linear operator.
superdiag = [3., 4., 5.]
diag = [1., -1., 2.]
subdiag = [6., 7., 8]
operator = tf.linalg.LinearOperatorTridiag(
[superdiag, diag, subdiag],
diagonals_format='sequence')
operator.to_dense()
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[ 1., 3., 0.],
[ 7., -1., 4.],
[ 0., 8., 2.]], dtype=float32)>
operator.shape
TensorShape([3, 3])
Scalar Tensor output.
operator.log_abs_determinant()
<tf.Tensor: shape=(), dtype=float32, numpy=4.3307333>
Create a [2, 3] batch of 4 x 4 linear operators.
diagonals = tf.random.normal(shape=[2, 3, 3, 4])
operator = tf.linalg.LinearOperatorTridiag(
diagonals,
diagonals_format='compact')
Create a shape [2, 1, 4, 2] vector. Note that this shape is compatible since the batch dimensions, [2, 1], are broadcast to operator.batch_shape = [2, 3].
y = tf.random.normal(shape=[2, 1, 4, 2])
x = operator.solve(y)
x
<tf.Tensor: shape=(2, 3, 4, 2), dtype=float32, numpy=...,
dtype=float32)>
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [C1,...,Cc] + [N, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb].
Performance Suppose operator is a LinearOperatorTridiag of shape [N, N], and x.shape = [N, R]. Then
operator.matmul(x) will take O(N * R) time.
operator.solve(x) will take O(N * R) time. If instead operator and x have shape [B1,...,Bb, N, N] and [B1,...,Bb, N, R], every operation increases in complexity by B1*...*Bb. Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
diagonals Tensor or list of Tensors depending on diagonals_format. If diagonals_format=sequence, this is a list of three Tensor's each with shape [B1, ..., Bb, N], b >= 0, N >= 0, representing the superdiagonal, diagonal and subdiagonal in that order. Note the superdiagonal is padded with an element in the last position, and the subdiagonal is padded with an element in the front. If diagonals_format=matrix this is a [B1, ... Bb, N, N] shaped Tensor representing the full tridiagonal matrix. If diagonals_format=compact this is a [B1, ... Bb, 3, N] shaped Tensor with the second to last dimension indexing the superdiagonal, diagonal and subdiagonal in that order. Note the superdiagonal is padded with an element in the last position, and the subdiagonal is padded with an element in the front. In every case, these Tensors are all floating dtype.
diagonals_format one of matrix, sequence, or compact. Default is compact.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose. If diag.dtype is real, this is auto-set to True.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
name A name for this LinearOperator.
Raises
TypeError If diag.dtype is not an allowed type.
ValueError If diag.dtype is real, and is_self_adjoint is not True.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
diagonals
diagonals_format
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
x, name='add_to_tensor'
)
Add matrix represented by this operator to x. Equivalent to A + x.
Args
x Tensor with same dtype and shape broadcastable to self.shape.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatortridiag |
tf.linalg.LinearOperatorZeros View source on GitHub LinearOperator acting like a [batch] zero matrix. Inherits From: LinearOperator, Module View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.LinearOperatorZeros
tf.linalg.LinearOperatorZeros(
num_rows, num_columns=None, batch_shape=None, dtype=None, is_non_singular=False,
is_self_adjoint=True, is_positive_definite=False, is_square=True,
assert_proper_shapes=False, name='LinearOperatorZeros'
)
This operator acts like a [batch] zero matrix A with shape [B1,...,Bb, N, M] for some b >= 0. The first b indices index a batch member. For every batch index (i1,...,ib), A[i1,...,ib, : :] is an N x M matrix. This matrix A is not materialized, but for purposes of broadcasting this shape will be relevant. LinearOperatorZeros is initialized with num_rows, and optionally num_columns,batch_shape, anddtypearguments. Ifnum_columnsisNone, then this operator will be initialized as a square matrix. Ifbatch_shapeisNone, this operator efficiently passes through all arguments. Ifbatch_shape` is provided, broadcasting may occur, which will require making copies. # Create a 2 x 2 zero matrix.
operator = LinearOperatorZero(num_rows=2, dtype=tf.float32)
operator.to_dense()
==> [[0., 0.]
[0., 0.]]
operator.shape
==> [2, 2]
operator.determinant()
==> 0.
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> Shape [2, 4] Tensor, same as x.
# Create a 2-batch of 2x2 zero matrices
operator = LinearOperatorZeros(num_rows=2, batch_shape=[2])
operator.to_dense()
==> [[[0., 0.]
[0., 0.]],
[[0., 0.]
[0., 0.]]]
# Here, even though the operator has a batch shape, the input is the same as
# the output, so x can be passed through without a copy. The operator is able
# to detect that no broadcast is necessary because both x and the operator
# have statically defined shape.
x = ... Shape [2, 2, 3]
operator.matmul(x)
==> Shape [2, 2, 3] Tensor, same as tf.zeros_like(x)
# Here the operator and x have different batch_shape, and are broadcast.
# This requires a copy, since the output is different size than the input.
x = ... Shape [1, 2, 3]
operator.matmul(x)
==> Shape [2, 2, 3] Tensor, equal to tf.zeros_like([x, x])
Shape compatibility This operator acts on [batch] matrix with compatible shape. x is a batch matrix with compatible shape for matmul and solve if operator.shape = [B1,...,Bb] + [N, M], with b >= 0
x.shape = [C1,...,Cc] + [M, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]
Matrix property hints This LinearOperator is initialized with boolean flags of the form is_X, for X = non_singular, self_adjoint, positive_definite, square. These have the following meaning: If is_X == True, callers should expect the operator to have the property X. This is a promise that should be fulfilled, but is not a runtime assert. For example, finite floating point precision may result in these promises being violated. If is_X == False, callers should expect the operator to not have X. If is_X == None (the default), callers should have no expectation either way.
Args
num_rows Scalar non-negative integer Tensor. Number of rows in the corresponding zero matrix.
num_columns Scalar non-negative integer Tensor. Number of columns in the corresponding zero matrix. If None, defaults to the value of num_rows.
batch_shape Optional 1-D integer Tensor. The shape of the leading dimensions. If None, this operator has no leading dimensions.
dtype Data type of the matrix that this operator represents.
is_non_singular Expect that this operator is non-singular.
is_self_adjoint Expect that this operator is equal to its hermitian transpose.
is_positive_definite Expect that this operator is positive definite, meaning the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive-definite. See: https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square Expect that this operator acts like square [batch] matrices.
assert_proper_shapes Python bool. If False, only perform static checks that initialization and method arguments have proper shape. If True, and static checks are inconclusive, add asserts to the graph.
name A name for this LinearOperator
Raises
ValueError If num_rows is determined statically to be non-scalar, or negative.
ValueError If num_columns is determined statically to be non-scalar, or negative.
ValueError If batch_shape is determined statically to not be 1-D, or negative.
ValueError If any of the following is not True: {is_self_adjoint, is_non_singular, is_positive_definite}.
Attributes
H Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
batch_shape TensorShape of batch dimensions of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb]), equivalent to A.shape[:-2]
domain_dimension Dimension (in the sense of vector spaces) of the domain of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
dtype The DType of Tensors handled by this LinearOperator.
graph_parents List of graph dependencies of this LinearOperator. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Do not call graph_parents.
is_non_singular
is_positive_definite
is_self_adjoint
is_square Return True/False depending on if this operator is square.
parameters Dictionary of parameters used to instantiate this LinearOperator.
range_dimension Dimension (in the sense of vector spaces) of the range of this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
shape TensorShape of this LinearOperator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns TensorShape([B1,...,Bb, M, N]), equivalent to A.shape.
tensor_rank Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Methods add_to_tensor View source
add_to_tensor(
mat, name='add_to_tensor'
)
Add matrix represented by this operator to mat. Equiv to I + mat.
Args
mat Tensor with same dtype and shape broadcastable to self.
name A name to give this Op.
Returns A Tensor with broadcast shape and same dtype as self.
adjoint View source
adjoint(
name='adjoint'
)
Returns the adjoint of the current LinearOperator. Given A representing this LinearOperator, return A*. Note that calling self.adjoint() and self.H are equivalent.
Args
name A name for this Op.
Returns LinearOperator which represents the adjoint of this LinearOperator.
assert_non_singular View source
assert_non_singular(
name='assert_non_singular'
)
Returns an Op that asserts this operator is non singular. This operator is considered non-singular if ConditionNumber < max{100, range_dimension, domain_dimension} * eps,
eps := np.finfo(self.dtype.as_numpy_dtype).eps
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is singular.
assert_positive_definite View source
assert_positive_definite(
name='assert_positive_definite'
)
Returns an Op that asserts this operator is positive definite. Here, positive definite means that the quadratic form x^H A x has positive real part for all nonzero x. Note that we do not require the operator to be self-adjoint to be positive definite.
Args
name A name to give this Op.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not positive definite.
assert_self_adjoint View source
assert_self_adjoint(
name='assert_self_adjoint'
)
Returns an Op that asserts this operator is self-adjoint. Here we check that this operator is exactly equal to its hermitian transpose.
Args
name A string name to prepend to created ops.
Returns An Assert Op, that, when run, will raise an InvalidArgumentError if the operator is not self-adjoint.
batch_shape_tensor View source
batch_shape_tensor(
name='batch_shape_tensor'
)
Shape of batch dimensions of this operator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb].
Args
name A name for this Op.
Returns int32 Tensor
cholesky View source
cholesky(
name='cholesky'
)
Returns a Cholesky factor as a LinearOperator. Given A representing this LinearOperator, if A is positive definite self-adjoint, return L, where A = L L^T, i.e. the cholesky decomposition.
Args
name A name for this Op.
Returns LinearOperator which represents the lower triangular matrix in the Cholesky decomposition.
Raises
ValueError When the LinearOperator is not hinted to be positive definite and self adjoint. cond View source
cond(
name='cond'
)
Returns the condition number of this linear operator.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
determinant View source
determinant(
name='det'
)
Determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. diag_part View source
diag_part(
name='diag_part'
)
Efficiently get the [batch] diagonal part of this operator. If this operator has shape [B1,...,Bb, M, N], this returns a Tensor diagonal, of shape [B1,...,Bb, min(M, N)], where diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]. my_operator = LinearOperatorDiag([1., 2.])
# Efficiently get the diagonal
my_operator.diag_part()
==> [1., 2.]
# Equivalent, but inefficient method
tf.linalg.diag_part(my_operator.to_dense())
==> [1., 2.]
Args
name A name for this Op.
Returns
diag_part A Tensor of same dtype as self. domain_dimension_tensor View source
domain_dimension_tensor(
name='domain_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the domain of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns N.
Args
name A name for this Op.
Returns int32 Tensor
eigvals View source
eigvals(
name='eigvals'
)
Returns the eigenvalues of this linear operator. If the operator is marked as self-adjoint (via is_self_adjoint) this computation can be more efficient.
Note: This currently only supports self-adjoint operators.
Args
name A name for this Op.
Returns Shape [B1,...,Bb, N] Tensor of same dtype as self.
inverse View source
inverse(
name='inverse'
)
Returns the Inverse of this LinearOperator. Given A representing this LinearOperator, return a LinearOperator representing A^-1.
Args
name A name scope to use for ops added by this method.
Returns LinearOperator representing inverse of this matrix.
Raises
ValueError When the LinearOperator is not hinted to be non_singular. log_abs_determinant View source
log_abs_determinant(
name='log_abs_det'
)
Log absolute value of determinant for every batch member.
Args
name A name for this Op.
Returns Tensor with shape self.batch_shape and same dtype as self.
Raises
NotImplementedError If self.is_square is False. matmul View source
matmul(
x, adjoint=False, adjoint_arg=False, name='matmul'
)
Transform [batch] matrix x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
X = ... # shape [..., N, R], batch matrix, R > 0.
Y = operator.matmul(X)
Y.shape
==> [..., M, R]
Y[..., :, r] = sum_j A[..., :, j] X[j, r]
Args
x LinearOperator or Tensor with compatible shape and same dtype as self. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
adjoint_arg Python bool. If True, compute A x^H where x^H is the hermitian transpose (transposition and complex conjugation).
name A name for this Op.
Returns A LinearOperator or Tensor with shape [..., M, R] and same dtype as self.
matvec View source
matvec(
x, adjoint=False, name='matvec'
)
Transform [batch] vector x with left multiplication: x --> Ax. # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
X = ... # shape [..., N], batch vector
Y = operator.matvec(X)
Y.shape
==> [..., M]
Y[..., :] = sum_j A[..., :, j] X[..., j]
Args
x Tensor with compatible shape and same dtype as self. x is treated as a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility.
adjoint Python bool. If True, left multiply by the adjoint: A^H x.
name A name for this Op.
Returns A Tensor with shape [..., M] and same dtype as self.
range_dimension_tensor View source
range_dimension_tensor(
name='range_dimension_tensor'
)
Dimension (in the sense of vector spaces) of the range of this operator. Determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns M.
Args
name A name for this Op.
Returns int32 Tensor
shape_tensor View source
shape_tensor(
name='shape_tensor'
)
Shape of this LinearOperator, determined at runtime. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns a Tensor holding [B1,...,Bb, M, N], equivalent to tf.shape(A).
Args
name A name for this Op.
Returns int32 Tensor
solve View source
solve(
rhs, adjoint=False, adjoint_arg=False, name='solve'
)
Solve (exact or approx) R (batch) systems of equations: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve R > 0 linear systems for every member of the batch.
RHS = ... # shape [..., M, R]
X = operator.solve(RHS)
# X[..., :, r] is the solution to the r'th linear system
# sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r]
operator.matmul(X)
==> RHS
Args
rhs Tensor with same dtype as this operator and compatible shape. rhs is treated like a [batch] matrix meaning for every set of leading dimensions, the last two dimensions defines a matrix. See class docstring for definition of compatibility.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
adjoint_arg Python bool. If True, solve A X = rhs^H where rhs^H is the hermitian transpose (transposition and complex conjugation).
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N, R] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. solvevec View source
solvevec(
rhs, adjoint=False, name='solve'
)
Solve single equation with best effort: A X = rhs. The returned Tensor will be close to an exact solution if A is well conditioned. Otherwise closeness will vary. See class docstring for details. Examples: # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]
operator = LinearOperator(...)
operator.shape = [..., M, N]
# Solve one linear system for every member of the batch.
RHS = ... # shape [..., M]
X = operator.solvevec(RHS)
# X is the solution to the linear system
# sum_j A[..., :, j] X[..., j] = RHS[..., :]
operator.matvec(X)
==> RHS
Args
rhs Tensor with same dtype as this operator. rhs is treated like a [batch] vector meaning for every set of leading dimensions, the last dimension defines a vector. See class docstring for definition of compatibility regarding batch dimensions.
adjoint Python bool. If True, solve the system involving the adjoint of this LinearOperator: A^H X = rhs.
name A name scope to use for ops added by this method.
Returns Tensor with shape [...,N] and same dtype as rhs.
Raises
NotImplementedError If self.is_non_singular or is_square is False. tensor_rank_tensor View source
tensor_rank_tensor(
name='tensor_rank_tensor'
)
Rank (in the sense of tensors) of matrix corresponding to this operator. If this operator acts like the batch matrix A with A.shape = [B1,...,Bb, M, N], then this returns b + 2.
Args
name A name for this Op.
Returns int32 Tensor, determined at runtime.
to_dense View source
to_dense(
name='to_dense'
)
Return a dense (batch) matrix representing this operator. trace View source
trace(
name='trace'
)
Trace of the linear operator, equal to sum of self.diag_part(). If the operator is square, this is also the sum of the eigenvalues.
Args
name A name for this Op.
Returns Shape [B1,...,Bb] Tensor of same dtype as self.
__matmul__ View source
__matmul__(
other
) | tensorflow.linalg.linearoperatorzeros |
tf.linalg.logdet View source on GitHub Computes log of the determinant of a hermitian positive definite matrix. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.logdet
tf.linalg.logdet(
matrix, name=None
)
# Compute the determinant of a matrix while reducing the chance of over- or
underflow:
A = ... # shape 10 x 10
det = tf.exp(tf.linalg.logdet(A)) # scalar
Args
matrix A Tensor. Must be float16, float32, float64, complex64, or complex128 with shape [..., M, M].
name A name to give this Op. Defaults to logdet.
Returns The natural log of the determinant of matrix.
Numpy Compatibility Equivalent to numpy.linalg.slogdet, although no sign is returned since only hermitian positive definite matrices are supported. | tensorflow.linalg.logdet |
tf.linalg.logm Computes the matrix logarithm of one or more square matrices: View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.logm
tf.linalg.logm(
input, name=None
)
\(log(exp(A)) = A\) This op is only defined for complex matrices. If A is positive-definite and real, then casting to a complex matrix, taking the logarithm and casting back to a real matrix will give the correct result. This function computes the matrix logarithm using the Schur-Parlett algorithm. Details of the algorithm can be found in Section 11.6.2 of: Nicholas J. Higham, Functions of Matrices: Theory and Computation, SIAM 2008. ISBN 978-0-898716-46-7. The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The output is a tensor of the same shape as the input containing the exponential for all input submatrices [..., :, :].
Args
input A Tensor. Must be one of the following types: complex64, complex128. Shape is [..., M, M].
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.linalg.logm |
tf.linalg.lstsq View source on GitHub Solves one or more linear least-squares problems. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.lstsq, tf.compat.v1.matrix_solve_ls
tf.linalg.lstsq(
matrix, rhs, l2_regularizer=0.0, fast=True, name=None
)
matrix is a tensor of shape [..., M, N] whose inner-most 2 dimensions form M-by-N matrices. Rhs is a tensor of shape [..., M, K] whose inner-most 2 dimensions form M-by-K matrices. The computed output is a Tensor of shape [..., N, K] whose inner-most 2 dimensions form M-by-K matrices that solve the equations matrix[..., :, :] * output[..., :, :] = rhs[..., :, :] in the least squares sense. Below we will use the following notation for each pair of matrix and right-hand sides in the batch: matrix=\(A \in \Re^{m \times n}\), rhs=\(B \in \Re^{m \times k}\), output=\(X \in \Re^{n \times k}\), l2_regularizer=\(\lambda\). If fast is True, then the solution is computed by solving the normal equations using Cholesky decomposition. Specifically, if \(m \ge n\) then \(X = (A^T A + \lambda I)^{-1} A^T B\), which solves the least-squares problem \(X = \mathrm{argmin}_{Z \in \Re^{n \times k} } ||A Z - B||_F^2 + \lambda ||Z||_F^2\). If \(m \lt n\) then output is computed as \(X = A^T (A A^T + \lambda I)^{-1} B\), which (for \(\lambda = 0\)) is the minimum-norm solution to the under-determined linear system, i.e. \(X = \mathrm{argmin}_{Z \in \Re^{n \times k} } ||Z||_F^2 \), subject to \(A Z = B\). Notice that the fast path is only numerically stable when \(A\) is numerically full rank and has a condition number \(\mathrm{cond}(A) \lt \frac{1}{\sqrt{\epsilon_{mach} } }\) or\(\lambda\) is sufficiently large. If fast is False an algorithm based on the numerically robust complete orthogonal decomposition is used. This computes the minimum-norm least-squares solution, even when \(A\) is rank deficient. This path is typically 6-7 times slower than the fast path. If fast is False then l2_regularizer is ignored.
Args
matrix Tensor of shape [..., M, N].
rhs Tensor of shape [..., M, K].
l2_regularizer 0-D double Tensor. Ignored if fast=False.
fast bool. Defaults to True.
name string, optional name of the operation.
Returns
output Tensor of shape [..., N, K] whose inner-most 2 dimensions form M-by-K matrices that solve the equations matrix[..., :, :] * output[..., :, :] = rhs[..., :, :] in the least squares sense.
Raises
NotImplementedError linalg.lstsq is currently disabled for complex128 and l2_regularizer != 0 due to poor accuracy. | tensorflow.linalg.lstsq |
tf.linalg.lu Computes the LU decomposition of one or more square matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.lu
tf.linalg.lu(
input, output_idx_type=tf.dtypes.int32, name=None
)
The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The input has to be invertible. The output consists of two tensors LU and P containing the LU decomposition of all input submatrices [..., :, :]. LU encodes the lower triangular and upper triangular factors. For each input submatrix of shape [M, M], L is a lower triangular matrix of shape [M, M] with unit diagonal whose entries correspond to the strictly lower triangular part of LU. U is a upper triangular matrix of shape [M, M] whose entries correspond to the upper triangular part, including the diagonal, of LU. P represents a permutation matrix encoded as a list of indices each between 0 and M-1, inclusive. If P_mat denotes the permutation matrix corresponding to P, then the L, U and P satisfies P_mat * input = L * U.
Args
input A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. A tensor of shape [..., M, M] whose inner-most 2 dimensions form matrices of size [M, M].
output_idx_type An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int32.
name A name for the operation (optional).
Returns A tuple of Tensor objects (lu, p). lu A Tensor. Has the same type as input.
p A Tensor of type output_idx_type. | tensorflow.linalg.lu |
tf.linalg.lu_matrix_inverse Computes the inverse given the LU decomposition(s) of one or more matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.lu_matrix_inverse
tf.linalg.lu_matrix_inverse(
lower_upper, perm, validate_args=False, name=None
)
This op is conceptually identical to, inv_X = tf.lu_matrix_inverse(*tf.linalg.lu(X))
tf.assert_near(tf.matrix_inverse(X), inv_X)
# ==> True
Note: this function does not verify the implied matrix is actually invertible nor is this condition checked even when validate_args=True.
Args
lower_upper lu as returned by tf.linalg.lu, i.e., if matmul(P, matmul(L, U)) = X then lower_upper = L + U - eye.
perm p as returned by tf.linag.lu, i.e., if matmul(P, matmul(L, U)) = X then perm = argmax(P).
validate_args Python bool indicating whether arguments should be checked for correctness. Note: this function does not verify the implied matrix is actually invertible, even when validate_args=True. Default value: False (i.e., don't validate arguments).
name Python str name given to ops managed by this object. Default value: None (i.e., 'lu_matrix_inverse').
Returns
inv_x The matrix_inv, i.e., tf.matrix_inverse(tf.linalg.lu_reconstruct(lu, perm)). Examples import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
x = [[[3., 4], [1, 2]],
[[7., 8], [3, 4]]]
inv_x = tf.linalg.lu_matrix_inverse(*tf.linalg.lu(x))
tf.assert_near(tf.matrix_inverse(x), inv_x)
# ==> True | tensorflow.linalg.lu_matrix_inverse |
tf.linalg.lu_reconstruct The reconstruct one or more matrices from their LU decomposition(s). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.lu_reconstruct
tf.linalg.lu_reconstruct(
lower_upper, perm, validate_args=False, name=None
)
Args
lower_upper lu as returned by tf.linalg.lu, i.e., if matmul(P, matmul(L, U)) = X then lower_upper = L + U - eye.
perm p as returned by tf.linag.lu, i.e., if matmul(P, matmul(L, U)) = X then perm = argmax(P).
validate_args Python bool indicating whether arguments should be checked for correctness. Default value: False (i.e., don't validate arguments).
name Python str name given to ops managed by this object. Default value: None (i.e., 'lu_reconstruct').
Returns
x The original input to tf.linalg.lu, i.e., x as in, lu_reconstruct(*tf.linalg.lu(x)). Examples import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
x = [[[3., 4], [1, 2]],
[[7., 8], [3, 4]]]
x_reconstructed = tf.linalg.lu_reconstruct(*tf.linalg.lu(x))
tf.assert_near(x, x_reconstructed)
# ==> True | tensorflow.linalg.lu_reconstruct |
tf.linalg.lu_solve Solves systems of linear eqns A X = RHS, given LU factorizations. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.lu_solve
tf.linalg.lu_solve(
lower_upper, perm, rhs, validate_args=False, name=None
)
Note: this function does not verify the implied matrix is actually invertible nor is this condition checked even when validate_args=True.
Args
lower_upper lu as returned by tf.linalg.lu, i.e., if matmul(P, matmul(L, U)) = X then lower_upper = L + U - eye.
perm p as returned by tf.linag.lu, i.e., if matmul(P, matmul(L, U)) = X then perm = argmax(P).
rhs Matrix-shaped float Tensor representing targets for which to solve; A X = RHS. To handle vector cases, use: lu_solve(..., rhs[..., tf.newaxis])[..., 0].
validate_args Python bool indicating whether arguments should be checked for correctness. Note: this function does not verify the implied matrix is actually invertible, even when validate_args=True. Default value: False (i.e., don't validate arguments).
name Python str name given to ops managed by this object. Default value: None (i.e., 'lu_solve').
Returns
x The X in A @ X = RHS. Examples import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
x = [[[1., 2],
[3, 4]],
[[7, 8],
[3, 4]]]
inv_x = tf.linalg.lu_solve(*tf.linalg.lu(x), rhs=tf.eye(2))
tf.assert_near(tf.matrix_inverse(x), inv_x)
# ==> True | tensorflow.linalg.lu_solve |
tf.linalg.matmul View source on GitHub Multiplies matrix a by matrix b, producing a * b. View aliases Main aliases
tf.matmul Compat aliases for migration See Migration guide for more details. tf.compat.v1.linalg.matmul, tf.compat.v1.matmul
tf.linalg.matmul(
a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False,
a_is_sparse=False, b_is_sparse=False, name=None
)
The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication dimensions, and any further outer dimensions specify matching batch size. Both matrices must be of the same type. The supported types are: float16, float32, float64, int32, complex64, complex128. Either matrix can be transposed or adjointed (conjugated and transposed) on the fly by setting one of the corresponding flag to True. These are False by default. If one or both of the matrices contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding a_is_sparse or b_is_sparse flag to True. These are False by default. This optimization is only available for plain matrices (rank-2 tensors) with datatypes bfloat16 or float32. A simple 2-D tensor matrix multiplication:
a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
a # 2-D tensor
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]], dtype=int32)>
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
b # 2-D tensor
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[ 7, 8],
[ 9, 10],
[11, 12]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 58, 64],
[139, 154]], dtype=int32)>
A batch matrix multiplication with batch shape [2]:
a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3])
a # 3-D tensor
<tf.Tensor: shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]], dtype=int32)>
b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2])
b # 3-D tensor
<tf.Tensor: shape=(2, 3, 2), dtype=int32, numpy=
array([[[13, 14],
[15, 16],
[17, 18]],
[[19, 20],
[21, 22],
[23, 24]]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2, 2), dtype=int32, numpy=
array([[[ 94, 100],
[229, 244]],
[[508, 532],
[697, 730]]], dtype=int32)>
Since python >= 3.5 the @ operator is supported (see PEP 465). In TensorFlow, it simply calls the tf.matmul() function, so the following lines are equivalent:
d = a @ b @ [[10], [11]]
d = tf.matmul(tf.matmul(a, b), [[10], [11]])
Args
a tf.Tensor of type float16, float32, float64, int32, complex64, complex128 and rank > 1.
b tf.Tensor with same type and rank as a.
transpose_a If True, a is transposed before multiplication.
transpose_b If True, b is transposed before multiplication.
adjoint_a If True, a is conjugated and transposed before multiplication.
adjoint_b If True, b is conjugated and transposed before multiplication.
a_is_sparse If True, a is treated as a sparse matrix. Notice, this does not support tf.sparse.SparseTensor, it just makes optimizations that assume most values in a are zero. See tf.sparse.sparse_dense_matmul for some support for tf.sparse.SparseTensor multiplication.
b_is_sparse If True, b is treated as a sparse matrix. Notice, this does not support tf.sparse.SparseTensor, it just makes optimizations that assume most values in a are zero. See tf.sparse.sparse_dense_matmul for some support for tf.sparse.SparseTensor multiplication.
name Name for the operation (optional).
Returns A tf.Tensor of the same type as a and b where each inner-most matrix is the product of the corresponding matrices in a and b, e.g. if all transpose or adjoint attributes are False: output[..., i, j] = sum_k (a[..., i, k] * b[..., k, j]), for all indices i, j.
Note This is matrix product, not element-wise product.
Raises
ValueError If transpose_a and adjoint_a, or transpose_b and adjoint_b are both set to True. | tensorflow.linalg.matmul |
tf.linalg.matrix_rank View source on GitHub Compute the matrix rank of one or more matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.matrix_rank
tf.linalg.matrix_rank(
a, tol=None, validate_args=False, name=None
)
Arguments
a (Batch of) float-like matrix-shaped Tensor(s) which are to be pseudo-inverted.
tol Threshold below which the singular value is counted as 'zero'. Default value: None (i.e., eps * max(rows, cols) * max(singular_val)).
validate_args When True, additional assertions might be embedded in the graph. Default value: False (i.e., no graph assertions are added).
name Python str prefixed to ops created by this function. Default value: 'matrix_rank'.
Returns
matrix_rank (Batch of) int32 scalars representing the number of non-zero singular values. | tensorflow.linalg.matrix_rank |
tf.linalg.matrix_transpose View source on GitHub Transposes last two dimensions of tensor a. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.matrix_transpose, tf.compat.v1.linalg.transpose, tf.compat.v1.matrix_transpose
tf.linalg.matrix_transpose(
a, name='matrix_transpose', conjugate=False
)
For example: x = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.linalg.matrix_transpose(x) # [[1, 4],
# [2, 5],
# [3, 6]]
x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],
[4 + 4j, 5 + 5j, 6 + 6j]])
tf.linalg.matrix_transpose(x, conjugate=True) # [[1 - 1j, 4 - 4j],
# [2 - 2j, 5 - 5j],
# [3 - 3j, 6 - 6j]]
# Matrix with two batch dimensions.
# x.shape is [1, 2, 3, 4]
# tf.linalg.matrix_transpose(x) is shape [1, 2, 4, 3]
Note that tf.matmul provides kwargs allowing for transpose of arguments. This is done with minimal cost, and is preferable to using this function. E.g. # Good! Transpose is taken at minimal additional cost.
tf.matmul(matrix, b, transpose_b=True)
# Inefficient!
tf.matmul(matrix, tf.linalg.matrix_transpose(b))
Args
a A Tensor with rank >= 2.
name A name for the operation (optional).
conjugate Optional bool. Setting it to True is mathematically equivalent to tf.math.conj(tf.linalg.matrix_transpose(input)).
Returns A transposed batch matrix Tensor.
Raises
ValueError If a is determined statically to have rank < 2. Numpy Compatibility In numpy transposes are memory-efficient constant time operations as they simply return a new view of the same data with adjusted strides. TensorFlow does not support strides, linalg.matrix_transpose returns a new tensor with the items permuted. | tensorflow.linalg.matrix_transpose |
tf.linalg.matvec View source on GitHub Multiplies matrix a by vector b, producing a * b. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.matvec
tf.linalg.matvec(
a, b, transpose_a=False, adjoint_a=False, a_is_sparse=False, b_is_sparse=False,
name=None
)
The matrix a must, following any transpositions, be a tensor of rank >= 2, with shape(a)[-1] == shape(b)[-1], and shape(a)[:-2] able to broadcast with shape(b)[:-1]. Both a and b must be of the same type. The supported types are: float16, float32, float64, int32, complex64, complex128. Matrix a can be transposed or adjointed (conjugated and transposed) on the fly by setting one of the corresponding flag to True. These are False by default. If one or both of the inputs contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding a_is_sparse or b_is_sparse flag to True. These are False by default. This optimization is only available for plain matrices/vectors (rank-2/1 tensors) with datatypes bfloat16 or float32. For example: # 2-D tensor `a`
# [[1, 2, 3],
# [4, 5, 6]]
a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
# 1-D tensor `b`
# [7, 9, 11]
b = tf.constant([7, 9, 11], shape=[3])
# `a` * `b`
# [ 58, 64]
c = tf.linalg.matvec(a, b)
# 3-D tensor `a`
# [[[ 1, 2, 3],
# [ 4, 5, 6]],
# [[ 7, 8, 9],
# [10, 11, 12]]]
a = tf.constant(np.arange(1, 13, dtype=np.int32),
shape=[2, 2, 3])
# 2-D tensor `b`
# [[13, 14, 15],
# [16, 17, 18]]
b = tf.constant(np.arange(13, 19, dtype=np.int32),
shape=[2, 3])
# `a` * `b`
# [[ 86, 212],
# [410, 563]]
c = tf.linalg.matvec(a, b)
Args
a Tensor of type float16, float32, float64, int32, complex64, complex128 and rank > 1.
b Tensor with same type as a and compatible dimensions.
transpose_a If True, a is transposed before multiplication.
adjoint_a If True, a is conjugated and transposed before multiplication.
a_is_sparse If True, a is treated as a sparse matrix.
b_is_sparse If True, b is treated as a sparse matrix.
name Name for the operation (optional).
Returns A Tensor of the same type as a and b where each inner-most vector is the product of the corresponding matrices in a and vectors in b, e.g. if all transpose or adjoint attributes are False: output[..., i] = sum_k (a[..., i, k] * b[..., k]), for all indices i.
Note This is matrix-vector product, not element-wise product.
Raises
ValueError If transpose_a and adjoint_a are both set to True. | tensorflow.linalg.matvec |
tf.linalg.normalize View source on GitHub Normalizes tensor along dimension axis using specified norm. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.normalize
tf.linalg.normalize(
tensor, ord='euclidean', axis=None, name=None
)
This uses tf.linalg.norm to compute the norm along axis. This function can compute several different vector norms (the 1-norm, the Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0) and matrix norms (Frobenius, 1-norm, 2-norm and inf-norm).
Args
tensor Tensor of types float32, float64, complex64, complex128
ord Order of the norm. Supported values are 'fro', 'euclidean', 1, 2, np.inf and any positive real number yielding the corresponding p-norm. Default is 'euclidean' which is equivalent to Frobenius norm if tensor is a matrix and equivalent to 2-norm for vectors. Some restrictions apply: a) The Frobenius norm 'fro' is not defined for vectors, b) If axis is a 2-tuple (matrix norm), only 'euclidean', 'fro', 1, 2, np.inf are supported. See the description of axis on how to compute norms for a batch of vectors or matrices stored in a tensor.
axis If axis is None (the default), the input is considered a vector and a single vector norm is computed over the entire set of values in the tensor, i.e. norm(tensor, ord=ord) is equivalent to norm(reshape(tensor, [-1]), ord=ord). If axis is a Python integer, the input is considered a batch of vectors, and axis determines the axis in tensor over which to compute vector norms. If axis is a 2-tuple of Python integers it is considered a batch of matrices and axis determines the axes in tensor over which to compute a matrix norm. Negative indices are supported. Example: If you are passing a tensor that can be either a matrix or a batch of matrices at runtime, pass axis=[-2,-1] instead of axis=None to make sure that matrix norms are computed.
name The name of the op.
Returns
normalized A normalized Tensor with the same shape as tensor.
norm The computed norms with the same shape and dtype tensor but the final axis is 1 instead. Same as running tf.cast(tf.linalg.norm(tensor, ord, axis keepdims=True), tensor.dtype).
Raises
ValueError If ord or axis is invalid. | tensorflow.linalg.normalize |
tf.linalg.pinv View source on GitHub Compute the Moore-Penrose pseudo-inverse of one or more matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.pinv
tf.linalg.pinv(
a, rcond=None, validate_args=False, name=None
)
Calculate the generalized inverse of a matrix using its singular-value decomposition (SVD) and including all large singular values. The pseudo-inverse of a matrix A, is defined as: 'the matrix that 'solves' [the least-squares problem] A @ x = b,' i.e., if x_hat is a solution, then A_pinv is the matrix such that x_hat = A_pinv @ b. It can be shown that if U @ Sigma @ V.T = A is the singular value decomposition of A, then A_pinv = V @ inv(Sigma) U^T. [(Strang, 1980)][1] This function is analogous to numpy.linalg.pinv. It differs only in default value of rcond. In numpy.linalg.pinv, the default rcond is 1e-15. Here the default is 10. * max(num_rows, num_cols) * np.finfo(dtype).eps.
Args
a (Batch of) float-like matrix-shaped Tensor(s) which are to be pseudo-inverted.
rcond Tensor of small singular value cutoffs. Singular values smaller (in modulus) than rcond * largest_singular_value (again, in modulus) are set to zero. Must broadcast against tf.shape(a)[:-2]. Default value: 10. * max(num_rows, num_cols) * np.finfo(a.dtype).eps.
validate_args When True, additional assertions might be embedded in the graph. Default value: False (i.e., no graph assertions are added).
name Python str prefixed to ops created by this function. Default value: 'pinv'.
Returns
a_pinv (Batch of) pseudo-inverse of input a. Has same shape as a except rightmost two dimensions are transposed.
Raises
TypeError if input a does not have float-like dtype.
ValueError if input a has fewer than 2 dimensions. Examples import tensorflow as tf
import tensorflow_probability as tfp
a = tf.constant([[1., 0.4, 0.5],
[0.4, 0.2, 0.25],
[0.5, 0.25, 0.35]])
tf.matmul(tf.linalg..pinv(a), a)
# ==> array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]], dtype=float32)
a = tf.constant([[1., 0.4, 0.5, 1.],
[0.4, 0.2, 0.25, 2.],
[0.5, 0.25, 0.35, 3.]])
tf.matmul(tf.linalg..pinv(a), a)
# ==> array([[ 0.76, 0.37, 0.21, -0.02],
[ 0.37, 0.43, -0.33, 0.02],
[ 0.21, -0.33, 0.81, 0.01],
[-0.02, 0.02, 0.01, 1. ]], dtype=float32)
References [1]: G. Strang. 'Linear Algebra and Its Applications, 2nd Ed.' Academic Press, Inc., 1980, pp. 139-142. | tensorflow.linalg.pinv |
tf.linalg.qr Computes the QR decompositions of one or more matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.qr, tf.compat.v1.qr
tf.linalg.qr(
input, full_matrices=False, name=None
)
Computes the QR decomposition of each inner matrix in tensor such that tensor[..., :, :] = q[..., :, :] * r[..., :,:]) Currently, the gradient for the QR decomposition is well-defined only when the first P columns of the inner matrix are linearly independent, where P is the minimum of M and N, the 2 inner-most dimmensions of tensor. # a is a tensor.
# q is a tensor of orthonormal matrices.
# r is a tensor of upper triangular matrices.
q, r = qr(a)
q_full, r_full = qr(a, full_matrices=True)
Args
input A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. A tensor of shape [..., M, N] whose inner-most 2 dimensions form matrices of size [M, N]. Let P be the minimum of M and N.
full_matrices An optional bool. Defaults to False. If true, compute full-sized q and r. If false (the default), compute only the leading P columns of q.
name A name for the operation (optional).
Returns A tuple of Tensor objects (q, r). q A Tensor. Has the same type as input.
r A Tensor. Has the same type as input. | tensorflow.linalg.qr |
tf.linalg.set_diag View source on GitHub Returns a batched matrix tensor with new batched diagonal values. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.set_diag, tf.compat.v1.matrix_set_diag
tf.linalg.set_diag(
input, diagonal, name='set_diag', k=0, align='RIGHT_LEFT'
)
Given input and diagonal, this operation returns a tensor with the same shape and values as input, except for the specified diagonals of the innermost matrices. These will be overwritten by the values in diagonal. input has r+1 dimensions [I, J, ..., L, M, N]. When k is scalar or k[0] == k[1], diagonal has r dimensions [I, J, ..., L, max_diag_len]. Otherwise, it has r+1 dimensions [I, J, ..., L, num_diags, max_diag_len]. num_diags is the number of diagonals, num_diags = k[1] - k[0] + 1. max_diag_len is the longest diagonal in the range [k[0], k[1]], max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0)) The output is a tensor of rank k+1 with dimensions [I, J, ..., L, M, N]. If k is scalar or k[0] == k[1]: output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1]
input[i, j, ..., l, m, n] ; otherwise
Otherwise, output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]
input[i, j, ..., l, m, n] ; otherwise
where d = n - m, diag_index = k[1] - d, and index_in_diag = n - max(d, 0) + offset. offset is zero except when the alignment of the diagonal is to the right. offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}
and `d >= 0`) or
(`align` in {LEFT_RIGHT, RIGHT_RIGHT}
and `d <= 0`)
0 ; otherwise
where diag_len(d) = min(cols - max(d, 0), rows + min(d, 0)). For example: # The main diagonal.
input = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4)
[7, 7, 7, 7],
[7, 7, 7, 7]],
[[7, 7, 7, 7],
[7, 7, 7, 7],
[7, 7, 7, 7]]])
diagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3)
[4, 5, 6]])
tf.matrix_set_diag(input, diagonal)
==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)
[7, 2, 7, 7],
[7, 7, 3, 7]],
[[4, 7, 7, 7],
[7, 5, 7, 7],
[7, 7, 6, 7]]]
# A superdiagonal (per batch).
tf.matrix_set_diag(input, diagonal, k = 1)
==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4)
[7, 7, 2, 7],
[7, 7, 7, 3]],
[[7, 4, 7, 7],
[7, 7, 5, 7],
[7, 7, 7, 6]]]
# A band of diagonals.
diagonals = np.array([[[9, 1, 0], # Diagonal shape: (2, 4, 3)
[6, 5, 8],
[1, 2, 3],
[0, 4, 5]],
[[1, 2, 0],
[5, 6, 4],
[6, 1, 2],
[0, 3, 4]]])
tf.matrix_set_diag(input, diagonals, k = (-1, 2))
==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)
[4, 2, 5, 1],
[7, 5, 3, 8]],
[[6, 5, 1, 7],
[3, 1, 6, 2],
[7, 4, 2, 4]]]
# RIGHT_LEFT alignment.
diagonals = np.array([[[0, 9, 1], # Diagonal shape: (2, 4, 3)
[6, 5, 8],
[1, 2, 3],
[4, 5, 0]],
[[0, 1, 2],
[5, 6, 4],
[6, 1, 2],
[3, 4, 0]]])
tf.matrix_set_diag(input, diagonals, k = (-1, 2), align="RIGHT_LEFT")
==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)
[4, 2, 5, 1],
[7, 5, 3, 8]],
[[6, 5, 1, 7],
[3, 1, 6, 2],
[7, 4, 2, 4]]]
Args
input A Tensor with rank k + 1, where k >= 1.
diagonal A Tensor with rank k, when d_lower == d_upper, or k + 1, otherwise. k >= 1.
name A name for the operation (optional).
k Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main diagonal, and negative value means subdiagonals. k can be a single integer (for a single diagonal) or a pair of integers specifying the low and high ends of a matrix band. k[0] must not be larger than k[1].
align Some diagonals are shorter than max_diag_len and need to be padded. align is a string specifying how superdiagonals and subdiagonals should be aligned, respectively. There are four possible alignments: "RIGHT_LEFT" (default), "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" aligns superdiagonals to the right (left-pads the row) and subdiagonals to the left (right-pads the row). It is the packing format LAPACK uses. cuSPARSE uses "LEFT_RIGHT", which is the opposite alignment. | tensorflow.linalg.set_diag |
tf.linalg.slogdet Computes the sign and the log of the absolute value of the determinant of View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.slogdet
tf.linalg.slogdet(
input, name=None
)
one or more square matrices. The input is a tensor of shape [N, M, M] whose inner-most 2 dimensions form square matrices. The outputs are two tensors containing the signs and absolute values of the log determinants for all N input submatrices [..., :, :] such that determinant = sign*exp(log_abs_determinant). The log_abs_determinant is computed as det(P)*sum(log(diag(LU))) where LU is the LU decomposition of the input and P is the corresponding permutation matrix.
Args
input A Tensor. Must be one of the following types: half, float32, float64, complex64, complex128. Shape is [N, M, M].
name A name for the operation (optional).
Returns A tuple of Tensor objects (sign, log_abs_determinant). sign A Tensor. Has the same type as input.
log_abs_determinant A Tensor. Has the same type as input. | tensorflow.linalg.slogdet |
tf.linalg.solve Solves systems of linear equations. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.solve, tf.compat.v1.matrix_solve
tf.linalg.solve(
matrix, rhs, adjoint=False, name=None
)
Matrix is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. Rhs is a tensor of shape [..., M, K]. The output is a tensor shape [..., M, K]. If adjoint is False then each output matrix satisfies matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]. If adjoint is True then each output matrix satisfies adjoint(matrix[..., :, :]) * output[..., :, :] = rhs[..., :, :].
Args
matrix A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. Shape is [..., M, M].
rhs A Tensor. Must have the same type as matrix. Shape is [..., M, K].
adjoint An optional bool. Defaults to False. Boolean indicating whether to solve with matrix or its (block-wise) adjoint.
name A name for the operation (optional).
Returns A Tensor. Has the same type as matrix. | tensorflow.linalg.solve |
tf.linalg.sqrtm Computes the matrix square root of one or more square matrices: View aliases Main aliases
tf.matrix_square_root Compat aliases for migration See Migration guide for more details. tf.compat.v1.linalg.sqrtm, tf.compat.v1.matrix_square_root
tf.linalg.sqrtm(
input, name=None
)
matmul(sqrtm(A), sqrtm(A)) = A The input matrix should be invertible. If the input matrix is real, it should have no eigenvalues which are real and negative (pairs of complex conjugate eigenvalues are allowed). The matrix square root is computed by first reducing the matrix to quasi-triangular form with the real Schur decomposition. The square root of the quasi-triangular matrix is then computed directly. Details of the algorithm can be found in: Nicholas J. Higham, "Computing real square roots of a real matrix", Linear Algebra Appl., 1987. The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The output is a tensor of the same shape as the input containing the matrix square root for all input submatrices [..., :, :].
Args
input A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. Shape is [..., M, M].
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.linalg.sqrtm |
tf.linalg.svd View source on GitHub Computes the singular value decompositions of one or more matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.svd, tf.compat.v1.svd
tf.linalg.svd(
tensor, full_matrices=False, compute_uv=True, name=None
)
Computes the SVD of each inner matrix in tensor such that tensor[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(conj(v[..., :, :])) # a is a tensor.
# s is a tensor of singular values.
# u is a tensor of left singular vectors.
# v is a tensor of right singular vectors.
s, u, v = svd(a)
s = svd(a, compute_uv=False)
Args
tensor Tensor of shape [..., M, N]. Let P be the minimum of M and N.
full_matrices If true, compute full-sized u and v. If false (the default), compute only the leading P singular vectors. Ignored if compute_uv is False.
compute_uv If True then left and right singular vectors will be computed and returned in u and v, respectively. Otherwise, only the singular values will be computed, which can be significantly faster.
name string, optional name of the operation.
Returns
s Singular values. Shape is [..., P]. The values are sorted in reverse order of magnitude, so s[..., 0] is the largest value, s[..., 1] is the second largest, etc.
u Left singular vectors. If full_matrices is False (default) then shape is [..., M, P]; if full_matrices is True then shape is [..., M, M]. Not returned if compute_uv is False.
v Right singular vectors. If full_matrices is False (default) then shape is [..., N, P]. If full_matrices is True then shape is [..., N, N]. Not returned if compute_uv is False. Numpy Compatibility Mostly equivalent to numpy.linalg.svd, except that The order of output arguments here is s, u, v when compute_uv is True, as opposed to u, s, v for numpy.linalg.svd. full_matrices is False by default as opposed to True for numpy.linalg.svd. tf.linalg.svd uses the standard definition of the SVD \(A = U \Sigma V^H\), such that the left singular vectors of a are the columns of u, while the right singular vectors of a are the columns of v. On the other hand, numpy.linalg.svd returns the adjoint \(V^H\) as the third output argument. import tensorflow as tf
import numpy as np
s, u, v = tf.linalg.svd(a)
tf_a_approx = tf.matmul(u, tf.matmul(tf.linalg.diag(s), v, adjoint_b=True))
u, s, v_adj = np.linalg.svd(a, full_matrices=False)
np_a_approx = np.dot(u, np.dot(np.diag(s), v_adj))
# tf_a_approx and np_a_approx should be numerically close. | tensorflow.linalg.svd |
tf.linalg.tensor_diag Returns a diagonal tensor with a given diagonal values. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.diag, tf.compat.v1.linalg.tensor_diag
tf.linalg.tensor_diag(
diagonal, name=None
)
Given a diagonal, this operation returns a tensor with the diagonal and everything else padded with zeros. The diagonal is computed as follows: Assume diagonal has dimensions [D1,..., Dk], then the output is a tensor of rank 2k with dimensions [D1,..., Dk, D1,..., Dk] where: output[i1,..., ik, i1,..., ik] = diagonal[i1, ..., ik] and 0 everywhere else. For example: # 'diagonal' is [1, 2, 3, 4]
tf.diag(diagonal) ==> [[1, 0, 0, 0]
[0, 2, 0, 0]
[0, 0, 3, 0]
[0, 0, 0, 4]]
Args
diagonal A Tensor. Must be one of the following types: bfloat16, half, float32, float64, int32, int64, complex64, complex128. Rank k tensor where k is at most 1.
name A name for the operation (optional).
Returns A Tensor. Has the same type as diagonal. | tensorflow.linalg.tensor_diag |
tf.linalg.tensor_diag_part View source on GitHub Returns the diagonal part of the tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.diag_part, tf.compat.v1.linalg.tensor_diag_part
tf.linalg.tensor_diag_part(
input, name=None
)
This operation returns a tensor with the diagonal part of the input. The diagonal part is computed as follows: Assume input has dimensions [D1,..., Dk, D1,..., Dk], then the output is a tensor of rank k with dimensions [D1,..., Dk] where: diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]. For a rank 2 tensor, linalg.diag_part and linalg.tensor_diag_part produce the same result. For rank 3 and higher, linalg.diag_part extracts the diagonal of each inner-most matrix in the tensor. An example where they differ is given below.
x = [[[[1111,1112],[1121,1122]],
[[1211,1212],[1221,1222]]],
[[[2111, 2112], [2121, 2122]],
[[2211, 2212], [2221, 2222]]]
]
tf.linalg.tensor_diag_part(x)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1111, 1212],
[2121, 2222]], dtype=int32)>
tf.linalg.diag_part(x).shape
TensorShape([2, 2, 2])
Args
input A Tensor with rank 2k.
name A name for the operation (optional).
Returns A Tensor containing diagonals of input. Has the same type as input, and rank k. | tensorflow.linalg.tensor_diag_part |
tf.linalg.trace View source on GitHub Compute the trace of a tensor x. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.trace, tf.compat.v1.trace
tf.linalg.trace(
x, name=None
)
trace(x) returns the sum along the main diagonal of each inner-most matrix in x. If x is of rank k with shape [I, J, K, ..., L, M, N], then output is a tensor of rank k-2 with dimensions [I, J, K, ..., L] where output[i, j, k, ..., l] = trace(x[i, j, k, ..., l, :, :]) For example: x = tf.constant([[1, 2], [3, 4]])
tf.linalg.trace(x) # 5
x = tf.constant([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
tf.linalg.trace(x) # 15
x = tf.constant([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[-1, -2, -3],
[-4, -5, -6],
[-7, -8, -9]]])
tf.linalg.trace(x) # [15, -15]
Args
x tensor.
name A name for the operation (optional).
Returns The trace of input tensor. | tensorflow.linalg.trace |
tf.linalg.triangular_solve View source on GitHub Solve systems of linear equations with upper or lower triangular matrices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.triangular_solve, tf.compat.v1.matrix_triangular_solve
tf.linalg.triangular_solve(
matrix, rhs, lower=True, adjoint=False, name=None
)
matrix is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. If lower is True then the strictly upper triangular part of each inner-most matrix is assumed to be zero and not accessed. If lower is False then the strictly lower triangular part of each inner-most matrix is assumed to be zero and not accessed. rhs is a tensor of shape [..., M, N]. The output is a tensor of shape [..., M, N]. If adjoint is True then the innermost matrices in output satisfy matrix equations sum_k matrix[..., i, k] * output[..., k, j] = rhs[..., i, j]. If adjoint is False then the innermost matrices in output satisfy matrix equations sum_k adjoint(matrix[..., i, k]) * output[..., k, j] = rhs[..., i, j]. Example:
a = tf.constant([[3, 0, 0, 0],
[2, 1, 0, 0],
[1, 0, 1, 0],
[1, 1, 1, 1]], dtype=tf.float32)
b = tf.constant([[4], [2], [4], [2]], dtype=tf.float32)
x = tf.linalg.triangular_solve(a, b, lower=True)
x
<tf.Tensor: shape=(4, 1), dtype=float32, numpy=
array([[ 1.3333334 ],
[-0.66666675],
[ 2.6666665 ],
[-1.3333331 ]], dtype=float32)>
tf.matmul(a, x)
<tf.Tensor: shape=(4, 1), dtype=float32, numpy=
array([[4.],
[2.],
[4.],
[2.]], dtype=float32)>
Args
matrix A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. Shape is [..., M, M].
rhs A Tensor. Must have the same type as matrix. Shape is [..., M, N].
lower An optional bool. Defaults to True. Boolean indicating whether the innermost matrices in matrix are lower or upper triangular.
adjoint An optional bool. Defaults to False. Boolean indicating whether to solve with matrix or its (block-wise) adjoint.
name A name for the operation (optional).
Returns A Tensor. Has the same type as matrix, and shape is [..., M, N]. | tensorflow.linalg.triangular_solve |
tf.linalg.tridiagonal_matmul View source on GitHub Multiplies tridiagonal matrix by matrix. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.tridiagonal_matmul
tf.linalg.tridiagonal_matmul(
diagonals, rhs, diagonals_format='compact', name=None
)
diagonals is representation of 3-diagonal NxN matrix, which depends on diagonals_format. In matrix format, diagonals must be a tensor of shape [..., M, M], with two inner-most dimensions representing the square tridiagonal matrices. Elements outside of the three diagonals will be ignored. If sequence format, diagonals is list or tuple of three tensors: [superdiag, maindiag, subdiag], each having shape [..., M]. Last element of superdiag first element of subdiag are ignored. In compact format the three diagonals are brought together into one tensor of shape [..., 3, M], with last two dimensions containing superdiagonals, diagonals, and subdiagonals, in order. Similarly to sequence format, elements diagonals[..., 0, M-1] and diagonals[..., 2, 0] are ignored. The sequence format is recommended as the one with the best performance. rhs is matrix to the right of multiplication. It has shape [..., M, N]. Example: superdiag = tf.constant([-1, -1, 0], dtype=tf.float64)
maindiag = tf.constant([2, 2, 2], dtype=tf.float64)
subdiag = tf.constant([0, -1, -1], dtype=tf.float64)
diagonals = [superdiag, maindiag, subdiag]
rhs = tf.constant([[1, 1], [1, 1], [1, 1]], dtype=tf.float64)
x = tf.linalg.tridiagonal_matmul(diagonals, rhs, diagonals_format='sequence')
Args
diagonals A Tensor or tuple of Tensors describing left-hand sides. The shape depends of diagonals_format, see description above. Must be float32, float64, complex64, or complex128.
rhs A Tensor of shape [..., M, N] and with the same dtype as diagonals.
diagonals_format one of sequence, or compact. Default is compact.
name A name to give this Op (optional).
Returns A Tensor of shape [..., M, N] containing the result of multiplication.
Raises
ValueError An unsupported type is provided as input, or when the input tensors have incorrect shapes. | tensorflow.linalg.tridiagonal_matmul |
tf.linalg.tridiagonal_solve View source on GitHub Solves tridiagonal systems of equations. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.tridiagonal_solve
tf.linalg.tridiagonal_solve(
diagonals, rhs, diagonals_format='compact', transpose_rhs=False,
conjugate_rhs=False, name=None, partial_pivoting=True
)
The input can be supplied in various formats: matrix, sequence and compact, specified by the diagonals_format arg. In matrix format, diagonals must be a tensor of shape [..., M, M], with two inner-most dimensions representing the square tridiagonal matrices. Elements outside of the three diagonals will be ignored. In sequence format, diagonals are supplied as a tuple or list of three tensors of shapes [..., N], [..., M], [..., N] representing superdiagonals, diagonals, and subdiagonals, respectively. N can be either M-1 or M; in the latter case, the last element of superdiagonal and the first element of subdiagonal will be ignored. In compact format the three diagonals are brought together into one tensor of shape [..., 3, M], with last two dimensions containing superdiagonals, diagonals, and subdiagonals, in order. Similarly to sequence format, elements diagonals[..., 0, M-1] and diagonals[..., 2, 0] are ignored. The compact format is recommended as the one with best performance. In case you need to cast a tensor into a compact format manually, use tf.gather_nd. An example for a tensor of shape [m, m]: rhs = tf.constant([...])
matrix = tf.constant([[...]])
m = matrix.shape[0]
dummy_idx = [0, 0] # An arbitrary element to use as a dummy
indices = [[[i, i + 1] for i in range(m - 1)] + [dummy_idx], # Superdiagonal
[[i, i] for i in range(m)], # Diagonal
[dummy_idx] + [[i + 1, i] for i in range(m - 1)]] # Subdiagonal
diagonals=tf.gather_nd(matrix, indices)
x = tf.linalg.tridiagonal_solve(diagonals, rhs)
Regardless of the diagonals_format, rhs is a tensor of shape [..., M] or [..., M, K]. The latter allows to simultaneously solve K systems with the same left-hand sides and K different right-hand sides. If transpose_rhs is set to True the expected shape is [..., M] or [..., K, M]. The batch dimensions, denoted as ..., must be the same in diagonals and rhs. The output is a tensor of the same shape as rhs: either [..., M] or [..., M, K]. The op isn't guaranteed to raise an error if the input matrix is not invertible. tf.debugging.check_numerics can be applied to the output to detect invertibility problems.
Note: with large batch sizes, the computation on the GPU may be slow, if either partial_pivoting=True or there are multiple right-hand sides (K > 1). If this issue arises, consider if it's possible to disable pivoting and have K = 1, or, alternatively, consider using CPU.
On CPU, solution is computed via Gaussian elimination with or without partial pivoting, depending on partial_pivoting parameter. On GPU, Nvidia's cuSPARSE library is used: https://docs.nvidia.com/cuda/cusparse/index.html#gtsv
Args
diagonals A Tensor or tuple of Tensors describing left-hand sides. The shape depends of diagonals_format, see description above. Must be float32, float64, complex64, or complex128.
rhs A Tensor of shape [..., M] or [..., M, K] and with the same dtype as diagonals. Note that if the shape of rhs and/or diags isn't known statically, rhs will be treated as a matrix rather than a vector.
diagonals_format one of matrix, sequence, or compact. Default is compact.
transpose_rhs If True, rhs is transposed before solving (has no effect if the shape of rhs is [..., M]).
conjugate_rhs If True, rhs is conjugated before solving.
name A name to give this Op (optional).
partial_pivoting whether to perform partial pivoting. True by default. Partial pivoting makes the procedure more stable, but slower. Partial pivoting is unnecessary in some cases, including diagonally dominant and symmetric positive definite matrices (see e.g. theorem 9.12 in [1]).
Returns A Tensor of shape [..., M] or [..., M, K] containing the solutions.
Raises
ValueError An unsupported type is provided as input, or when the input tensors have incorrect shapes.
UnimplementedError Whenever partial_pivoting is true and the backend is XLA. [1] Nicholas J. Higham (2002). Accuracy and Stability of Numerical Algorithms: Second Edition. SIAM. p. 175. ISBN 978-0-89871-802-7. | tensorflow.linalg.tridiagonal_solve |
tf.linspace View source on GitHub Generates evenly-spaced values in an interval along a given axis. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lin_space, tf.compat.v1.linspace
tf.linspace(
start, stop, num, name=None, axis=0
)
A sequence of num evenly-spaced values are generated beginning at start along a given axis. If num > 1, the values in the sequence increase by stop - start / num - 1, so that the last one is exactly stop. If num <= 0, ValueError is raised. Matches np.linspace's behaviour except when num == 0. For example: tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0 11.0 12.0]
Start and stop can be tensors of arbitrary size:
tf.linspace([0., 5.], [10., 40.], 5, axis=0)
<tf.Tensor: shape=(5, 2), dtype=float32, numpy=
array([[ 0. , 5. ],
[ 2.5 , 13.75],
[ 5. , 22.5 ],
[ 7.5 , 31.25],
[10. , 40. ]], dtype=float32)>
Axis is where the values will be generated (the dimension in the returned tensor which corresponds to the axis will be equal to num)
tf.linspace([0., 5.], [10., 40.], 5, axis=-1)
<tf.Tensor: shape=(2, 5), dtype=float32, numpy=
array([[ 0. , 2.5 , 5. , 7.5 , 10. ],
[ 5. , 13.75, 22.5 , 31.25, 40. ]], dtype=float32)>
Args
start A Tensor. Must be one of the following types: bfloat16, float32, float64. N-D tensor. First entry in the range.
stop A Tensor. Must have the same type and shape as start. N-D tensor. Last entry in the range.
num A Tensor. Must be one of the following types: int32, int64. 0-D tensor. Number of values to generate.
name A name for the operation (optional).
axis Axis along which the operation is performed (used only when N-D tensors are provided).
Returns A Tensor. Has the same type as start. | tensorflow.linspace |
Module: tf.lite Public API for tf.lite namespace. Modules experimental module: Public API for tf.lite.experimental namespace. Classes class Interpreter: Interpreter interface for TensorFlow Lite Models. class OpsSet: Enum class defining the sets of ops available to generate TFLite models. class Optimize: Enum defining the optimizations to apply when generating tflite graphs. class RepresentativeDataset: Representative dataset to evaluate optimizations. class TFLiteConverter: Converts a TensorFlow model into TensorFlow Lite model. class TargetSpec: Specification of target device. | tensorflow.lite |
Module: tf.lite.experimental Public API for tf.lite.experimental namespace. Functions load_delegate(...): Returns loaded Delegate object. | tensorflow.lite.experimental |
tf.lite.experimental.load_delegate View source on GitHub Returns loaded Delegate object. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lite.experimental.load_delegate
tf.lite.experimental.load_delegate(
library, options=None
)
Args
library Name of shared library containing the TfLiteDelegate.
options Dictionary of options that are required to load the delegate. All keys and values in the dictionary should be convertible to str. Consult the documentation of the specific delegate for required and legal options. (default None)
Returns Delegate object.
Raises
ValueError Delegate failed to load.
RuntimeError If delegate loading is used on unsupported platform. | tensorflow.lite.experimental.load_delegate |
tf.lite.Interpreter View source on GitHub Interpreter interface for TensorFlow Lite Models. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lite.Interpreter
tf.lite.Interpreter(
model_path=None, model_content=None, experimental_delegates=None,
num_threads=None
)
This makes the TensorFlow Lite interpreter accessible in Python. It is possible to use this interpreter in a multithreaded Python environment, but you must be sure to call functions of a particular instance from only one thread at a time. So if you want to have 4 threads running different inferences simultaneously, create an interpreter for each one as thread-local data. Similarly, if you are calling invoke() in one thread on a single interpreter but you want to use tensor() on another thread once it is done, you must use a synchronization primitive between the threads to ensure invoke has returned before calling tensor().
Args
model_path Path to TF-Lite Flatbuffer file.
model_content Content of model.
experimental_delegates Experimental. Subject to change. List of TfLiteDelegate objects returned by lite.load_delegate().
num_threads Sets the number of threads used by the interpreter and available to CPU kernels. If not set, the interpreter will use an implementation-dependent default number of threads. Currently, only a subset of kernels, such as conv, support multi-threading.
Raises
ValueError If the interpreter was unable to create. Methods allocate_tensors View source
allocate_tensors()
get_input_details View source
get_input_details()
Gets model input details.
Returns A list of input details.
get_output_details View source
get_output_details()
Gets model output details.
Returns A list of output details.
get_tensor View source
get_tensor(
tensor_index
)
Gets the value of the input tensor (get a copy). If you wish to avoid the copy, use tensor(). This function cannot be used to read intermediate results.
Args
tensor_index Tensor index of tensor to get. This value can be gotten from the 'index' field in get_output_details.
Returns a numpy array.
get_tensor_details View source
get_tensor_details()
Gets tensor details for every tensor with valid tensor details. Tensors where required information about the tensor is not found are not added to the list. This includes temporary tensors without a name.
Returns A list of dictionaries containing tensor information.
invoke View source
invoke()
Invoke the interpreter. Be sure to set the input sizes, allocate tensors and fill values before calling this. Also, note that this function releases the GIL so heavy computation can be done in the background while the Python interpreter continues. No other function on this object should be called while the invoke() call has not finished.
Raises
ValueError When the underlying interpreter fails raise ValueError. reset_all_variables View source
reset_all_variables()
resize_tensor_input View source
resize_tensor_input(
input_index, tensor_size, strict=False
)
Resizes an input tensor. interpreter = Interpreter(model_content=tflite_model)
interpreter.resize_tensor_input(0, [1, 224, 224, 3], strict=True)
interpreter.allocate_tensors()
interpreter.invoke()
Args
input_index Tensor index of input to set. This value can be gotten from the 'index' field in get_input_details.
tensor_size The tensor_shape to resize the input to.
strict Only unknown dimensions can be resized when strict is True. Unknown dimensions are indicated as -1 in the shape_signature attribute of a given tensor. (default False)
Raises
ValueError If the interpreter could not resize the input tensor. set_tensor View source
set_tensor(
tensor_index, value
)
Sets the value of the input tensor. Note this copies data in value. If you want to avoid copying, you can use the tensor() function to get a numpy buffer pointing to the input buffer in the tflite interpreter.
Args
tensor_index Tensor index of tensor to set. This value can be gotten from the 'index' field in get_input_details.
value Value of tensor to set.
Raises
ValueError If the interpreter could not set the tensor. tensor View source
tensor(
tensor_index
)
Returns function that gives a numpy view of the current tensor buffer. This allows reading and writing to this tensors w/o copies. This more closely mirrors the C++ Interpreter class interface's tensor() member, hence the name. Be careful to not hold these output references through calls to allocate_tensors() and invoke(). This function cannot be used to read intermediate results. Usage: interpreter.allocate_tensors()
input = interpreter.tensor(interpreter.get_input_details()[0]["index"])
output = interpreter.tensor(interpreter.get_output_details()[0]["index"])
for i in range(10):
input().fill(3.)
interpreter.invoke()
print("inference %s" % output())
Notice how this function avoids making a numpy array directly. This is because it is important to not hold actual numpy views to the data longer than necessary. If you do, then the interpreter can no longer be invoked, because it is possible the interpreter would resize and invalidate the referenced tensors. The NumPy API doesn't allow any mutability of the the underlying buffers. WRONG: input = interpreter.tensor(interpreter.get_input_details()[0]["index"])()
output = interpreter.tensor(interpreter.get_output_details()[0]["index"])()
interpreter.allocate_tensors() # This will throw RuntimeError
for i in range(10):
input.fill(3.)
interpreter.invoke() # this will throw RuntimeError since input,output
Args
tensor_index Tensor index of tensor to get. This value can be gotten from the 'index' field in get_output_details.
Returns A function that can return a new numpy array pointing to the internal TFLite tensor state at any point. It is safe to hold the function forever, but it is not safe to hold the numpy array forever. | tensorflow.lite.interpreter |
tf.lite.OpsSet View source on GitHub Enum class defining the sets of ops available to generate TFLite models. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lite.OpsSet Warning: Experimental interface, subject to change.
Class Variables
EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8 tf.lite.OpsSet
SELECT_TF_OPS tf.lite.OpsSet
TFLITE_BUILTINS tf.lite.OpsSet
TFLITE_BUILTINS_INT8 tf.lite.OpsSet | tensorflow.lite.opsset |
tf.lite.Optimize View source on GitHub Enum defining the optimizations to apply when generating tflite graphs. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lite.Optimize Some optimizations may come at the cost of accuracy. DEFAULT Default optimization strategy. Converter will do its best to improve size and latency based on the
information provided.
Enhanced optimizations are gained by providing a representative_dataset.
This is recommended, and is currently equivalent to the modes below.
Currently, weights will be quantized and if representative_dataset is
provided, activations for quantizable operations will also be quantized.
OPTIMIZE_FOR_SIZE Deprecated. Does the same as DEFAULT. OPTIMIZE_FOR_LATENCY Deprecated. Does the same as DEFAULT.
Class Variables
DEFAULT tf.lite.Optimize
OPTIMIZE_FOR_LATENCY tf.lite.Optimize
OPTIMIZE_FOR_SIZE tf.lite.Optimize | tensorflow.lite.optimize |
tf.lite.RepresentativeDataset View source on GitHub Representative dataset to evaluate optimizations. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lite.RepresentativeDataset
tf.lite.RepresentativeDataset(
input_gen
)
A representative dataset that can be used to evaluate optimizations by the converter. E.g. converter can use these examples to estimate (min, max) ranges by calibrating the model on inputs. This can allow converter to quantize a converted floating point model.
Args
input_gen an input generator that can be used to generate input samples for the model. This must be a callable object that returns an object that supports the iter() protocol (e.g. a generator function). The elements generated must have same type and shape as inputs to the model. | tensorflow.lite.representativedataset |
tf.lite.TargetSpec View source on GitHub Specification of target device. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lite.TargetSpec
tf.lite.TargetSpec(
supported_ops=None, supported_types=None
)
Details about target device. Converter optimizes the generated model for specific device.
Attributes
supported_ops Experimental flag, subject to change. Set of OpsSet options supported by the device. (default set([OpsSet.TFLITE_BUILTINS]))
supported_types List of types for constant values on the target device. Frequently, an optimization choice is driven by the most compact (i.e. smallest) type in this list (default [tf.float32]) | tensorflow.lite.targetspec |
tf.lite.TFLiteConverter View source on GitHub Converts a TensorFlow model into TensorFlow Lite model.
tf.lite.TFLiteConverter(
funcs, trackable_obj=None
)
Example usage: # Converting a SavedModel to a TensorFlow Lite model.
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()
# Converting a tf.Keras model to a TensorFlow Lite model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Converting ConcreteFunctions to a TensorFlow Lite model.
converter = tf.lite.TFLiteConverter.from_concrete_functions([func])
tflite_model = converter.convert()
Args
funcs List of TensorFlow ConcreteFunctions. The list should not contain duplicate elements.
trackable_obj tf.AutoTrackable object associated with funcs. A reference to this object needs to be maintained so that Variables do not get garbage collected since functions have a weak reference to Variables. This is only required when the tf.AutoTrackable object is not maintained by the user (e.g. from_saved_model).
Attributes
allow_custom_ops Boolean indicating whether to allow custom operations. When False, any unknown operation is an error. When True, custom ops are created for any op that is unknown. The developer needs to provide these to the TensorFlow Lite runtime with a custom resolver. (default False)
optimizations Experimental flag, subject to change. A list of optimizations to apply when converting the model. E.g. [Optimize.DEFAULT]
representative_dataset A representative dataset that can be used to generate input and output samples for the model. The converter can use the dataset to evaluate different optimizations. Note that this is an optional attribute but it is necessary if INT8 is the only support builtin ops in target ops.
target_spec Experimental flag, subject to change. Specification of target device.
inference_input_type Data type of the input layer. Note that integer types (tf.int8 and tf.uint8) are currently only supported for post training integer quantization and quantization aware training. (default tf.float32, must be in {tf.float32, tf.int8, tf.uint8})
inference_output_type Data type of the output layer. Note that integer types (tf.int8 and tf.uint8) are currently only supported for post training integer quantization and quantization aware training. (default tf.float32, must be in {tf.float32, tf.int8, tf.uint8})
experimental_new_converter Experimental flag, subject to change. Enables MLIR-based conversion instead of TOCO conversion. (default True) Methods convert View source
convert()
Converts a TensorFlow GraphDef based on instance variables.
Returns The converted data in serialized format.
Raises
ValueError No concrete functions is specified. Multiple concrete functions are specified. Input shape is not specified. Invalid quantization parameters. from_concrete_functions View source
@classmethod
from_concrete_functions(
funcs
)
Creates a TFLiteConverter object from ConcreteFunctions.
Args
funcs List of TensorFlow ConcreteFunctions. The list should not contain duplicate elements. Currently converter can only convert a single ConcreteFunction. Converting multiple functions is under development.
Returns TFLiteConverter object.
Raises Invalid input type.
from_keras_model View source
@classmethod
from_keras_model(
model
)
Creates a TFLiteConverter object from a Keras model.
Args
model tf.Keras.Model
Returns TFLiteConverter object.
from_saved_model View source
@classmethod
from_saved_model(
saved_model_dir, signature_keys=None, tags=None
)
Creates a TFLiteConverter object from a SavedModel directory.
Args
saved_model_dir SavedModel directory to convert.
signature_keys List of keys identifying SignatureDef containing inputs and outputs. Elements should not be duplicated. By default the signatures attribute of the MetaGraphdef is used. (default saved_model.signatures)
tags Set of tags identifying the MetaGraphDef within the SavedModel to analyze. All tags in the tag set must be present. (default set(SERVING))
Returns TFLiteConverter object.
Raises Invalid signature keys. | tensorflow.lite.tfliteconverter |
tf.load_library View source on GitHub Loads a TensorFlow plugin. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.load_library
tf.load_library(
library_location
)
"library_location" can be a path to a specific shared object, or a folder. If it is a folder, all shared objects that are named "libtfkernel*" will be loaded. When the library is loaded, kernels registered in the library via the REGISTER_* macros are made available in the TensorFlow process.
Args
library_location Path to the plugin or the folder of plugins. Relative or absolute filesystem path to a dynamic library file or folder.
Returns None
Raises
OSError When the file to be loaded is not found.
RuntimeError when unable to load the library. | tensorflow.load_library |
tf.load_op_library View source on GitHub Loads a TensorFlow plugin, containing custom ops and kernels. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.load_op_library
tf.load_op_library(
library_filename
)
Pass "library_filename" to a platform-specific mechanism for dynamically loading a library. The rules for determining the exact location of the library are platform-specific and are not documented here. When the library is loaded, ops and kernels registered in the library via the REGISTER_* macros are made available in the TensorFlow process. Note that ops with the same name as an existing op are rejected and not registered with the process.
Args
library_filename Path to the plugin. Relative or absolute filesystem path to a dynamic library file.
Returns A python module containing the Python wrappers for Ops defined in the plugin.
Raises
RuntimeError when unable to load the library or get the python wrappers. | tensorflow.load_op_library |
Module: tf.lookup Public API for tf.lookup namespace. Modules experimental module: Public API for tf.lookup.experimental namespace. Classes class KeyValueTensorInitializer: Table initializers given keys and values tensors. class StaticHashTable: A generic hash table that is immutable once initialized. class StaticVocabularyTable: String to Id table that assigns out-of-vocabulary keys to hash buckets. class TextFileIndex: The key and value content to get from each line. class TextFileInitializer: Table initializers from a text file. | tensorflow.lookup |
Module: tf.lookup.experimental Public API for tf.lookup.experimental namespace. Classes class DatasetInitializer: Creates a table initializer from a tf.data.Dataset. class DenseHashTable: A generic mutable hash table implementation using tensors as backing store. | tensorflow.lookup.experimental |
tf.lookup.experimental.DatasetInitializer Creates a table initializer from a tf.data.Dataset. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lookup.experimental.DatasetInitializer
tf.lookup.experimental.DatasetInitializer(
dataset
)
Sample usage:
keys = tf.data.Dataset.range(100)
values = tf.data.Dataset.range(100).map(
lambda x: string_ops.as_string(x * 2))
ds = tf.data.Dataset.zip((keys, values))
init = tf.lookup.experimental.DatasetInitializer(ds)
table = tf.lookup.StaticHashTable(init, "")
table.lookup(tf.constant([0, 1, 2], dtype=tf.int64)).numpy()
array([b'0', b'2', b'4'], dtype=object)
Raises: ValueError if dataset doesn't conform to specifications.
Args
dataset A tf.data.Dataset object that produces tuples of scalars. The first scalar is treated as a key and the second as value.
Attributes
dataset A tf.data.Dataset object that produces tuples of scalars. The first scalar is treated as a key and the second as value.
key_dtype The expected table key dtype.
value_dtype The expected table value dtype. Methods initialize View source
initialize(
table
)
Returns the table initialization op. | tensorflow.lookup.experimental.datasetinitializer |
tf.lookup.experimental.DenseHashTable View source on GitHub A generic mutable hash table implementation using tensors as backing store. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lookup.experimental.DenseHashTable
tf.lookup.experimental.DenseHashTable(
key_dtype, value_dtype, default_value, empty_key, deleted_key,
initial_num_buckets=None, name='MutableDenseHashTable',
checkpoint=True
)
Data can be inserted by calling the insert method and removed by calling the remove method. It does not support initialization via the init method. It uses "open addressing" with quadratic reprobing to resolve collisions. Compared to MutableHashTable the insert, remove and lookup operations in a DenseHashTable are typically faster, but memory usage can be higher. However, DenseHashTable does not require additional memory for temporary tensors created during checkpointing and restore operations. Example usage:
table = tf.lookup.experimental.DenseHashTable(
key_dtype=tf.string,
value_dtype=tf.int64,
default_value=-1,
empty_key='',
deleted_key='$')
keys = tf.constant(['a', 'b', 'c'])
values = tf.constant([0, 1, 2], dtype=tf.int64)
table.insert(keys, values)
table.remove(tf.constant(['c']))
table.lookup(tf.constant(['a', 'b', 'c','d'])).numpy()
array([ 0, 1, -1, -1])
Args
key_dtype the type of the key tensors.
value_dtype the type of the value tensors.
default_value The value to use if a key is missing in the table.
empty_key the key to use to represent empty buckets internally. Must not be used in insert, remove or lookup operations.
deleted_key the key to use to represent deleted buckets internally. Must not be used in insert, remove or lookup operations and be different from the empty_key.
initial_num_buckets the initial number of buckets.
name A name for the operation (optional).
checkpoint if True, the contents of the table are saved to and restored from checkpoints. If shared_name is empty for a checkpointed table, it is shared using the table node name.
Raises
ValueError If checkpoint is True and no name was specified.
Attributes
key_dtype The table key dtype.
name The name of the table.
resource_handle Returns the resource handle associated with this Resource.
value_dtype The table value dtype. Methods erase View source
erase(
keys, name=None
)
Removes keys and its associated values from the table. If a key is not present in the table, it is silently ignored.
Args
keys Keys to remove. Can be a tensor of any shape. Must match the table's key type.
name A name for the operation (optional).
Returns The created Operation.
Raises
TypeError when keys do not match the table data types. export View source
export(
name=None
)
Returns tensors of all keys and values in the table.
Args
name A name for the operation (optional).
Returns A pair of tensors with the first tensor containing all keys and the second tensors containing all values in the table.
insert View source
insert(
keys, values, name=None
)
Associates keys with values.
Args
keys Keys to insert. Can be a tensor of any shape. Must match the table's key type.
values Values to be associated with keys. Must be a tensor of the same shape as keys and match the table's value type.
name A name for the operation (optional).
Returns The created Operation.
Raises
TypeError when keys or values doesn't match the table data types. insert_or_assign View source
insert_or_assign(
keys, values, name=None
)
Associates keys with values.
Args
keys Keys to insert. Can be a tensor of any shape. Must match the table's key type.
values Values to be associated with keys. Must be a tensor of the same shape as keys and match the table's value type.
name A name for the operation (optional).
Returns The created Operation.
Raises
TypeError when keys or values doesn't match the table data types. lookup View source
lookup(
keys, name=None
)
Looks up keys in a table, outputs the corresponding values. The default_value is used for keys not present in the table.
Args
keys Keys to look up. Can be a tensor of any shape. Must match the table's key_dtype.
name A name for the operation (optional).
Returns A tensor containing the values in the same shape as keys using the table's value type.
Raises
TypeError when keys do not match the table data types. remove View source
remove(
keys, name=None
)
Removes keys and its associated values from the table. If a key is not present in the table, it is silently ignored.
Args
keys Keys to remove. Can be a tensor of any shape. Must match the table's key type.
name A name for the operation (optional).
Returns The created Operation.
Raises
TypeError when keys do not match the table data types. size View source
size(
name=None
)
Compute the number of elements in this table.
Args
name A name for the operation (optional).
Returns A scalar tensor containing the number of elements in this table.
__getitem__ View source
__getitem__(
keys
)
Looks up keys in a table, outputs the corresponding values. | tensorflow.lookup.experimental.densehashtable |
tf.lookup.KeyValueTensorInitializer View source on GitHub Table initializers given keys and values tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lookup.KeyValueTensorInitializer
tf.lookup.KeyValueTensorInitializer(
keys, values, key_dtype=None, value_dtype=None, name=None
)
keys_tensor = tf.constant(['a', 'b', 'c'])
vals_tensor = tf.constant([7, 8, 9])
input_tensor = tf.constant(['a', 'f'])
init = tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor)
table = tf.lookup.StaticHashTable(
init,
default_value=-1)
table.lookup(input_tensor).numpy()
array([ 7, -1], dtype=int32)
Args
keys The tensor for the keys.
values The tensor for the values.
key_dtype The keys data type. Used when keys is a python array.
value_dtype The values data type. Used when values is a python array.
name A name for the operation (optional).
Attributes
key_dtype The expected table key dtype.
value_dtype The expected table value dtype. Methods initialize View source
initialize(
table
)
Initializes the given table with keys and values tensors.
Args
table The table to initialize.
Returns The operation that initializes the table.
Raises
TypeError when the keys and values data types do not match the table key and value data types. | tensorflow.lookup.keyvaluetensorinitializer |
tf.lookup.StaticHashTable View source on GitHub A generic hash table that is immutable once initialized.
tf.lookup.StaticHashTable(
initializer, default_value, name=None
)
Example usage:
keys_tensor = tf.constant(['a', 'b', 'c'])
vals_tensor = tf.constant([7, 8, 9])
input_tensor = tf.constant(['a', 'f'])
table = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor),
default_value=-1)
table.lookup(input_tensor).numpy()
array([ 7, -1], dtype=int32)
Or for more pythonic code:
table[input_tensor].numpy()
array([ 7, -1], dtype=int32)
The result of a lookup operation has the same shape as the argument:
input_tensor = tf.constant([['a', 'b'], ['c', 'd']])
table[input_tensor].numpy()
array([[ 7, 8],
[ 9, -1]], dtype=int32)
Args
initializer The table initializer to use. See HashTable kernel for supported key and value types.
default_value The value to use if a key is missing in the table.
name A name for the operation (optional).
Attributes
default_value The default value of the table.
key_dtype The table key dtype.
name The name of the table.
resource_handle Returns the resource handle associated with this Resource.
value_dtype The table value dtype. Methods export View source
export(
name=None
)
Returns tensors of all keys and values in the table.
Args
name A name for the operation (optional).
Returns A pair of tensors with the first tensor containing all keys and the second tensors containing all values in the table.
lookup View source
lookup(
keys, name=None
)
Looks up keys in a table, outputs the corresponding values. The default_value is used for keys not present in the table.
Args
keys Keys to look up. May be either a SparseTensor or dense Tensor.
name A name for the operation (optional).
Returns A SparseTensor if keys are sparse, a RaggedTensor if keys are ragged, otherwise a dense Tensor.
Raises
TypeError when keys or default_value doesn't match the table data types. size View source
size(
name=None
)
Compute the number of elements in this table.
Args
name A name for the operation (optional).
Returns A scalar tensor containing the number of elements in this table.
__getitem__ View source
__getitem__(
keys
)
Looks up keys in a table, outputs the corresponding values. | tensorflow.lookup.statichashtable |
tf.lookup.StaticVocabularyTable View source on GitHub String to Id table that assigns out-of-vocabulary keys to hash buckets.
tf.lookup.StaticVocabularyTable(
initializer, num_oov_buckets, lookup_key_dtype=None, name=None
)
For example, if an instance of StaticVocabularyTable is initialized with a string-to-id initializer that maps:
init = tf.lookup.KeyValueTensorInitializer(
keys=tf.constant(['emerson', 'lake', 'palmer']),
values=tf.constant([0, 1, 2], dtype=tf.int64))
table = tf.lookup.StaticVocabularyTable(
init,
num_oov_buckets=5)
The Vocabulary object will performs the following mapping: emerson -> 0 lake -> 1 palmer -> 2
<other term> -> bucket_id, where bucket_id will be between 3 and 3 + num_oov_buckets - 1 = 7, calculated by: hash(<term>) % num_oov_buckets + vocab_size
If input_tensor is:
input_tensor = tf.constant(["emerson", "lake", "palmer",
"king", "crimson"])
table[input_tensor].numpy()
array([0, 1, 2, 6, 7])
If initializer is None, only out-of-vocabulary buckets are used. Example usage:
num_oov_buckets = 3
vocab = ["emerson", "lake", "palmer", "crimnson"]
import tempfile
f = tempfile.NamedTemporaryFile(delete=False)
f.write('\n'.join(vocab).encode('utf-8'))
f.close()
init = tf.lookup.TextFileInitializer(
f.name,
key_dtype=tf.string, key_index=tf.lookup.TextFileIndex.WHOLE_LINE,
value_dtype=tf.int64, value_index=tf.lookup.TextFileIndex.LINE_NUMBER)
table = tf.lookup.StaticVocabularyTable(init, num_oov_buckets)
table.lookup(tf.constant(["palmer", "crimnson" , "king",
"tarkus", "black", "moon"])).numpy()
array([2, 3, 5, 6, 6, 4])
The hash function used for generating out-of-vocabulary buckets ID is Fingerprint64.
Args
initializer A TableInitializerBase object that contains the data used to initialize the table. If None, then we only use out-of-vocab buckets.
num_oov_buckets Number of buckets to use for out-of-vocabulary keys. Must be greater than zero.
lookup_key_dtype Data type of keys passed to lookup. Defaults to initializer.key_dtype if initializer is specified, otherwise tf.string. Must be string or integer, and must be castable to initializer.key_dtype.
name A name for the operation (optional).
Raises
ValueError when num_oov_buckets is not positive.
TypeError when lookup_key_dtype or initializer.key_dtype are not integer or string. Also when initializer.value_dtype != int64.
Attributes
key_dtype The table key dtype.
name The name of the table.
resource_handle Returns the resource handle associated with this Resource.
value_dtype The table value dtype. Methods lookup View source
lookup(
keys, name=None
)
Looks up keys in the table, outputs the corresponding values. It assigns out-of-vocabulary keys to buckets based in their hashes.
Args
keys Keys to look up. May be either a SparseTensor or dense Tensor.
name Optional name for the op.
Returns A SparseTensor if keys are sparse, a RaggedTensor if keys are ragged, otherwise a dense Tensor.
Raises
TypeError when keys doesn't match the table key data type. size View source
size(
name=None
)
Compute the number of elements in this table. __getitem__ View source
__getitem__(
keys
)
Looks up keys in a table, outputs the corresponding values. | tensorflow.lookup.staticvocabularytable |
tf.lookup.TextFileIndex View source on GitHub The key and value content to get from each line. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lookup.TextFileIndex This class defines the key and value used for tf.lookup.TextFileInitializer. The key and value content to get from each line is specified either by the following, or a value >=0.
TextFileIndex.LINE_NUMBER means use the line number starting from zero, expects data type int64.
TextFileIndex.WHOLE_LINE means use the whole line content, expects data type string. A value >=0 means use the index (starting at zero) of the split line based on delimiter.
Class Variables
LINE_NUMBER -1
WHOLE_LINE -2 | tensorflow.lookup.textfileindex |
tf.lookup.TextFileInitializer View source on GitHub Table initializers from a text file. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.lookup.TextFileInitializer
tf.lookup.TextFileInitializer(
filename, key_dtype, key_index, value_dtype, value_index, vocab_size=None,
delimiter='\t', name=None
)
This initializer assigns one entry in the table for each line in the file. The key and value type of the table to initialize is given by key_dtype and value_dtype. The key and value content to get from each line is specified by the key_index and value_index.
TextFileIndex.LINE_NUMBER means use the line number starting from zero, expects data type int64.
TextFileIndex.WHOLE_LINE means use the whole line content, expects data type string. A value >=0 means use the index (starting at zero) of the split line based on delimiter. For example if we have a file with the following content:
import tempfile
f = tempfile.NamedTemporaryFile(delete=False)
content='\n'.join(["emerson 10", "lake 20", "palmer 30",])
f.file.write(content.encode('utf-8'))
f.file.close()
The following snippet initializes a table with the first column as keys and second column as values: emerson -> 10 lake -> 20 palmer -> 30
init= tf.lookup.TextFileInitializer(
filename=f.name,
key_dtype=tf.string, key_index=0,
value_dtype=tf.int64, value_index=1,
delimiter=" ")
table = tf.lookup.StaticHashTable(init, default_value=-1)
table.lookup(tf.constant(['palmer','lake','tarkus'])).numpy()
Similarly to initialize the whole line as keys and the line number as values. emerson 10 -> 0 lake 20 -> 1 palmer 30 -> 2
init = tf.lookup.TextFileInitializer(
filename=f.name,
key_dtype=tf.string, key_index=tf.lookup.TextFileIndex.WHOLE_LINE,
value_dtype=tf.int64, value_index=tf.lookup.TextFileIndex.LINE_NUMBER,
delimiter=" ")
table = tf.lookup.StaticHashTable(init, -1)
table.lookup(tf.constant('palmer 30')).numpy()
2
Args
filename The filename of the text file to be used for initialization. The path must be accessible from wherever the graph is initialized (eg. trainer or eval workers). The filename may be a scalar Tensor.
key_dtype The key data type.
key_index the index that represents information of a line to get the table 'key' values from.
value_dtype The value data type.
value_index the index that represents information of a line to get the table 'value' values from.'
vocab_size The number of elements in the file, if known.
delimiter The delimiter to separate fields in a line.
name A name for the operation (optional).
Raises
ValueError when the filename is empty, or when the table key and value data types do not match the expected data types.
Attributes
key_dtype The expected table key dtype.
value_dtype The expected table value dtype. Methods initialize View source
initialize(
table
)
Initializes the table from a text file.
Args
table The table to be initialized.
Returns The operation that initializes the table.
Raises
TypeError when the keys and values data types do not match the table key and value data types. | tensorflow.lookup.textfileinitializer |
tf.make_ndarray View source on GitHub Create a numpy ndarray from a tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.make_ndarray
tf.make_ndarray(
tensor
)
Create a numpy ndarray with the same shape and data as the tensor. For example: # Tensor a has shape (2,3)
a = tf.constant([[1,2,3],[4,5,6]])
proto_tensor = tf.make_tensor_proto(a) # convert `tensor a` to a proto tensor
tf.make_ndarray(proto_tensor) # output: array([[1, 2, 3],
# [4, 5, 6]], dtype=int32)
# output has shape (2,3)
Args
tensor A TensorProto.
Returns A numpy array with the tensor contents.
Raises
TypeError if tensor has unsupported type. | tensorflow.make_ndarray |
tf.make_tensor_proto View source on GitHub Create a TensorProto. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.make_tensor_proto
tf.make_tensor_proto(
values, dtype=None, shape=None, verify_shape=False, allow_broadcast=False
)
In TensorFlow 2.0, representing tensors as protos should no longer be a common workflow. That said, this utility function is still useful for generating TF Serving request protos: request = tensorflow_serving.apis.predict_pb2.PredictRequest()
request.model_spec.name = "my_model"
request.model_spec.signature_name = "serving_default"
request.inputs["images"].CopyFrom(tf.make_tensor_proto(X_new))
make_tensor_proto accepts "values" of a python scalar, a python list, a numpy ndarray, or a numpy scalar. If "values" is a python scalar or a python list, make_tensor_proto first convert it to numpy ndarray. If dtype is None, the conversion tries its best to infer the right numpy data type. Otherwise, the resulting numpy array has a compatible data type with the given dtype. In either case above, the numpy ndarray (either the caller provided or the auto-converted) must have the compatible type with dtype. make_tensor_proto then converts the numpy array to a tensor proto. If "shape" is None, the resulting tensor proto represents the numpy array precisely. Otherwise, "shape" specifies the tensor's shape and the numpy array can not have more elements than what "shape" specifies.
Args
values Values to put in the TensorProto.
dtype Optional tensor_pb2 DataType value.
shape List of integers representing the dimensions of tensor.
verify_shape Boolean that enables verification of a shape of values.
allow_broadcast Boolean that enables allowing scalars and 1 length vector broadcasting. Cannot be true when verify_shape is true.
Returns A TensorProto. Depending on the type, it may contain data in the "tensor_content" attribute, which is not directly useful to Python programs. To access the values you should convert the proto back to a numpy ndarray with tf.make_ndarray(proto). If values is a TensorProto, it is immediately returned; dtype and shape are ignored.
Raises
TypeError if unsupported types are provided.
ValueError if arguments have inappropriate values or if verify_shape is True and shape of values is not equals to a shape from the argument. | tensorflow.make_tensor_proto |
tf.map_fn View source on GitHub Transforms elems by applying fn to each element unstacked on axis 0. (deprecated arguments)
tf.map_fn(
fn, elems, dtype=None, parallel_iterations=None, back_prop=True,
swap_memory=False, infer_shape=True, name=None, fn_output_signature=None
)
Warning: SOME ARGUMENTS ARE DEPRECATED: (dtype). They will be removed in a future version. Instructions for updating: Use fn_output_signature instead See also tf.scan. map_fn unstacks elems on axis 0 to obtain a sequence of elements; calls fn to transform each element; and then stacks the transformed values back together. Mapping functions with single-Tensor inputs and outputs If elems is a single tensor and fn's signature is tf.Tensor->tf.Tensor, then map_fn(fn, elems) is equivalent to tf.stack([fn(elem) for elem in tf.unstack(elems)]). E.g.:
tf.map_fn(fn=lambda t: tf.range(t, t + 3), elems=tf.constant([3, 5, 2]))
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[3, 4, 5],
[5, 6, 7],
[2, 3, 4]], dtype=int32)>
map_fn(fn, elems).shape = [elems.shape[0]] + fn(elems[0]).shape. Mapping functions with multi-arity inputs and outputs map_fn also supports functions with multi-arity inputs and outputs: If elems is a tuple (or nested structure) of tensors, then those tensors must all have the same outer-dimension size (num_elems); and fn is used to transform each tuple (or structure) of corresponding slices from elems. E.g., if elems is a tuple (t1, t2, t3), then fn is used to transform each tuple of slices (t1[i], t2[i], t3[i]) (where 0 <= i < num_elems). If fn returns a tuple (or nested structure) of tensors, then the result is formed by stacking corresponding elements from those structures. Specifying fn's output signature If fn's input and output signatures are different, then the output signature must be specified using fn_output_signature. (The input and output signatures are differ if their structures, dtypes, or tensor types do not match). E.g.:
tf.map_fn(fn=tf.strings.length, # input & output have different dtypes
elems=tf.constant(["hello", "moon"]),
fn_output_signature=tf.int32)
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([5, 4], dtype=int32)>
tf.map_fn(fn=tf.strings.join, # input & output have different structures
elems=[tf.constant(['The', 'A']), tf.constant(['Dog', 'Cat'])],
fn_output_signature=tf.string)
<tf.Tensor: shape=(2,), dtype=string,
numpy=array([b'TheDog', b'ACat'], dtype=object)>
fn_output_signature can be specified using any of the following: A tf.DType or tf.TensorSpec (to describe a tf.Tensor) A tf.RaggedTensorSpec (to describe a tf.RaggedTensor) A tf.SparseTensorSpec (to describe a tf.sparse.SparseTensor) A (possibly nested) tuple, list, or dict containing the above types. RaggedTensors map_fn supports tf.RaggedTensor inputs and outputs. In particular:
If elems is a RaggedTensor, then fn will be called with each row of that ragged tensor. If elems has only one ragged dimension, then the values passed to fn will be tf.Tensors. If elems has multiple ragged dimensions, then the values passed to fn will be tf.RaggedTensors with one fewer ragged dimension.
If the result of map_fn should be a RaggedTensor, then use a tf.RaggedTensorSpec to specify fn_output_signature. If fn returns tf.Tensors with varying sizes, then use a tf.RaggedTensorSpec with ragged_rank=0 to combine them into a single ragged tensor (which will have ragged_rank=1). If fn returns tf.RaggedTensors, then use a tf.RaggedTensorSpec with the same ragged_rank.
# Example: RaggedTensor input
rt = tf.ragged.constant([[1, 2, 3], [], [4, 5], [6]])
tf.map_fn(tf.reduce_sum, rt, fn_output_signature=tf.int32)
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([6, 0, 9, 6], dtype=int32)>
# Example: RaggedTensor output
elems = tf.constant([3, 5, 0, 2])
tf.map_fn(tf.range, elems,
fn_output_signature=tf.RaggedTensorSpec(shape=[None],
dtype=tf.int32))
<tf.RaggedTensor [[0, 1, 2], [0, 1, 2, 3, 4], [], [0, 1]]>
Note: map_fn should only be used if you need to map a function over the rows of a RaggedTensor. If you wish to map a function over the individual values, then you should use:
tf.ragged.map_flat_values(fn, rt) (if fn is expressible as TensorFlow ops)
rt.with_flat_values(map_fn(fn, rt.flat_values)) (otherwise) E.g.:
rt = tf.ragged.constant([[1, 2, 3], [], [4, 5], [6]])
tf.ragged.map_flat_values(lambda x: x + 2, rt)
<tf.RaggedTensor [[3, 4, 5], [], [6, 7], [8]]>
SparseTensors map_fn supports tf.sparse.SparseTensor inputs and outputs. In particular: If elems is a SparseTensor, then fn will be called with each row of that sparse tensor. In particular, the value passed to fn will be a tf.sparse.SparseTensor with one fewer dimension than elems. If the result of map_fn should be a SparseTensor, then use a tf.SparseTensorSpec to specify fn_output_signature. The individual SparseTensors returned by fn will be stacked into a single SparseTensor with one more dimension.
# Example: SparseTensor input
st = tf.sparse.SparseTensor([[0, 0], [2, 0], [2, 1]], [2, 3, 4], [4, 4])
tf.map_fn(tf.sparse.reduce_sum, st, fn_output_signature=tf.int32)
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([2, 0, 7, 0], dtype=int32)>
# Example: SparseTensor output
tf.sparse.to_dense(
tf.map_fn(tf.sparse.eye, tf.constant([2, 3]),
fn_output_signature=tf.SparseTensorSpec(None, tf.float32)))
<tf.Tensor: shape=(2, 3, 3), dtype=float32, numpy=
array([[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]],
[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]], dtype=float32)>
Note: map_fn should only be used if you need to map a function over the rows of a SparseTensor. If you wish to map a function over the nonzero values, then you should use:
If the function is expressible as TensorFlow ops, use: tf.sparse.SparseTensor(st.indices, fn(st.values), st.dense_shape)
Otherwise, use: tf.sparse.SparseTensor(st.indices, tf.map_fn(fn, st.values),
st.dense_shape)
map_fn vs. vectorized operations map_fn will apply the operations used by fn to each element of elems, resulting in O(elems.shape[0]) total operations. This is somewhat mitigated by the fact that map_fn can process elements in parallel. However, a transform expressed using map_fn is still typically less efficient than an equivalent transform expressed using vectorized operations. map_fn should typically only be used if one of the following is true: It is difficult or expensive to express the desired transform with vectorized operations.
fn creates large intermediate values, so an equivalent vectorized transform would take too much memory. Processing elements in parallel is more efficient than an equivalent vectorized transform. Efficiency of the transform is not critical, and using map_fn is more readable. E.g., the example given above that maps fn=lambda t: tf.range(t, t + 3) across elems could be rewritten more efficiently using vectorized ops:
elems = tf.constant([3, 5, 2])
tf.range(3) + tf.expand_dims(elems, 1)
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[3, 4, 5],
[5, 6, 7],
[2, 3, 4]], dtype=int32)>
In some cases, tf.vectorized_map can be used to automatically convert a function to a vectorized eqivalent. Eager execution When executing eagerly, map_fn does not execute in parallel even if parallel_iterations is set to a value > 1. You can still get the performance benefits of running a function in parallel by using the tf.function decorator:
fn=lambda t: tf.range(t, t + 3)
@tf.function
def func(elems):
return tf.map_fn(fn, elems, parallel_iterations=3)
func(tf.constant([3, 5, 2]))
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[3, 4, 5],
[5, 6, 7],
[2, 3, 4]], dtype=int32)>
Note: if you use the tf.function decorator, any non-TensorFlow Python code that you may have written in your function won't get executed. See tf.function for more details. The recommendation would be to debug without tf.function but switch to it to get performance benefits of running map_fn in parallel.
Args
fn The callable to be performed. It accepts one argument, which will have the same (possibly nested) structure as elems. Its output must have the same structure as fn_output_signature if one is provided; otherwise it must have the same structure as elems.
elems A tensor or (possibly nested) sequence of tensors, each of which will be unstacked along their first dimension. fn will be applied to the nested sequence of the resulting slices. elems may include ragged and sparse tensors. elems must consist of at least one tensor.
dtype Deprecated: Equivalent to fn_output_signature.
parallel_iterations (optional) The number of iterations allowed to run in parallel. When graph building, the default value is 10. While executing eagerly, the default value is set to 1.
back_prop (optional) Deprecated: prefer using tf.stop_gradient instead. False disables support for back propagation.
swap_memory (optional) True enables GPU-CPU memory swapping.
infer_shape (optional) False disables tests for consistent output shapes.
name (optional) Name prefix for the returned tensors.
fn_output_signature The output signature of fn. Must be specified if fn's input and output signatures are different (i.e., if their structures, dtypes, or tensor types do not match). fn_output_signature can be specified using any of the following: A tf.DType or tf.TensorSpec (to describe a tf.Tensor) A tf.RaggedTensorSpec (to describe a tf.RaggedTensor) A tf.SparseTensorSpec (to describe a tf.sparse.SparseTensor) A (possibly nested) tuple, list, or dict containing the above types.
Returns A tensor or (possibly nested) sequence of tensors. Each tensor stacks the results of applying fn to tensors unstacked from elems along the first dimension, from first to last. The result may include ragged and sparse tensors.
Raises
TypeError if fn is not callable or the structure of the output of fn and fn_output_signature do not match.
ValueError if the lengths of the output of fn and fn_output_signature do not match, or if the elems does not contain any tensor. Examples:
elems = np.array([1, 2, 3, 4, 5, 6])
tf.map_fn(lambda x: x * x, elems)
<tf.Tensor: shape=(6,), dtype=int64, numpy=array([ 1, 4, 9, 16, 25, 36])>
elems = (np.array([1, 2, 3]), np.array([-1, 1, -1]))
tf.map_fn(lambda x: x[0] * x[1], elems, fn_output_signature=tf.int64)
<tf.Tensor: shape=(3,), dtype=int64, numpy=array([-1, 2, -3])>
elems = np.array([1, 2, 3])
tf.map_fn(lambda x: (x, -x), elems,
fn_output_signature=(tf.int64, tf.int64))
(<tf.Tensor: shape=(3,), dtype=int64, numpy=array([1, 2, 3])>,
<tf.Tensor: shape=(3,), dtype=int64, numpy=array([-1, -2, -3])>) | tensorflow.map_fn |
Module: tf.math Math Operations.
Note: Functions taking Tensor arguments can also take anything accepted by tf.convert_to_tensor.
Note: Elementwise binary operations in TensorFlow follow numpy-style broadcasting.
TensorFlow provides a variety of math functions including: Basic arithmetic operators and trigonometric functions. Special math functions (like: tf.math.igamma and tf.math.zeta) Complex number functions (like: tf.math.imag and tf.math.angle) Reductions and scans (like: tf.math.reduce_mean and tf.math.cumsum) Segment functions (like: tf.math.segment_sum) See: tf.linalg for matrix and tensor functions. About Segmentation TensorFlow provides several operations that you can use to perform common math computations on tensor segments. Here a segmentation is a partitioning of a tensor along the first dimension, i.e. it defines a mapping from the first dimension onto segment_ids. The segment_ids tensor should be the size of the first dimension, d0, with consecutive IDs in the range 0 to k, where k<d0. In particular, a segmentation of a matrix tensor is a mapping of rows to segments. For example: c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
tf.math.segment_sum(c, tf.constant([0, 0, 1]))
# ==> [[0 0 0 0]
# [5 6 7 8]]
The standard segment_* functions assert that the segment indices are sorted. If you have unsorted indices use the equivalent unsorted_segment_ function. These functions take an additional argument num_segments so that the output tensor can be efficiently allocated. c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
tf.math.unsorted_segment_sum(c, tf.constant([0, 1, 0]), num_segments=2)
# ==> [[ 6, 8, 10, 12],
# [-1, -2, -3, -4]]
Modules special module: Public API for tf.math.special namespace. Functions abs(...): Computes the absolute value of a tensor. accumulate_n(...): Returns the element-wise sum of a list of tensors. acos(...): Computes acos of x element-wise. acosh(...): Computes inverse hyperbolic cosine of x element-wise. add(...): Returns x + y element-wise. add_n(...): Adds all input tensors element-wise. angle(...): Returns the element-wise argument of a complex (or real) tensor. argmax(...): Returns the index with the largest value across axes of a tensor. argmin(...): Returns the index with the smallest value across axes of a tensor. asin(...): Computes the trignometric inverse sine of x element-wise. asinh(...): Computes inverse hyperbolic sine of x element-wise. atan(...): Computes the trignometric inverse tangent of x element-wise. atan2(...): Computes arctangent of y/x element-wise, respecting signs of the arguments. atanh(...): Computes inverse hyperbolic tangent of x element-wise. bessel_i0(...): Computes the Bessel i0 function of x element-wise. bessel_i0e(...): Computes the Bessel i0e function of x element-wise. bessel_i1(...): Computes the Bessel i1 function of x element-wise. bessel_i1e(...): Computes the Bessel i1e function of x element-wise. betainc(...): Compute the regularized incomplete beta integral \(I_x(a, b)\). bincount(...): Counts the number of occurrences of each value in an integer array. ceil(...): Return the ceiling of the input, element-wise. confusion_matrix(...): Computes the confusion matrix from predictions and labels. conj(...): Returns the complex conjugate of a complex number. cos(...): Computes cos of x element-wise. cosh(...): Computes hyperbolic cosine of x element-wise. count_nonzero(...): Computes number of nonzero elements across dimensions of a tensor. cumprod(...): Compute the cumulative product of the tensor x along axis. cumsum(...): Compute the cumulative sum of the tensor x along axis. cumulative_logsumexp(...): Compute the cumulative log-sum-exp of the tensor x along axis. digamma(...): Computes Psi, the derivative of Lgamma (the log of the absolute value of divide(...): Computes Python style division of x by y. divide_no_nan(...): Computes a safe divide which returns 0 if the y is zero. equal(...): Returns the truth value of (x == y) element-wise. erf(...): Computes the Gauss error function of x element-wise. erfc(...): Computes the complementary error function of x element-wise. erfcinv(...): Computes the inverse of complementary error function. erfinv(...): Compute inverse error function. exp(...): Computes exponential of x element-wise. \(y = e^x\). expm1(...): Computes exp(x) - 1 element-wise. floor(...): Returns element-wise largest integer not greater than x. floordiv(...): Divides x / y elementwise, rounding toward the most negative integer. floormod(...): Returns element-wise remainder of division. When x < 0 xor y < 0 is greater(...): Returns the truth value of (x > y) element-wise. greater_equal(...): Returns the truth value of (x >= y) element-wise. igamma(...): Compute the lower regularized incomplete Gamma function P(a, x). igammac(...): Compute the upper regularized incomplete Gamma function Q(a, x). imag(...): Returns the imaginary part of a complex (or real) tensor. in_top_k(...): Says whether the targets are in the top K predictions. invert_permutation(...): Computes the inverse permutation of a tensor. is_finite(...): Returns which elements of x are finite. is_inf(...): Returns which elements of x are Inf. is_nan(...): Returns which elements of x are NaN. is_non_decreasing(...): Returns True if x is non-decreasing. is_strictly_increasing(...): Returns True if x is strictly increasing. l2_normalize(...): Normalizes along dimension axis using an L2 norm. lbeta(...): Computes \(ln(|Beta(x)|)\), reducing along the last dimension. less(...): Returns the truth value of (x < y) element-wise. less_equal(...): Returns the truth value of (x <= y) element-wise. lgamma(...): Computes the log of the absolute value of Gamma(x) element-wise. log(...): Computes natural logarithm of x element-wise. log1p(...): Computes natural logarithm of (1 + x) element-wise. log_sigmoid(...): Computes log sigmoid of x element-wise. log_softmax(...): Computes log softmax activations. logical_and(...): Logical AND function. logical_not(...): Returns the truth value of NOT x element-wise. logical_or(...): Returns the truth value of x OR y element-wise. logical_xor(...): Logical XOR function. maximum(...): Returns the max of x and y (i.e. x > y ? x : y) element-wise. minimum(...): Returns the min of x and y (i.e. x < y ? x : y) element-wise. mod(...): Returns element-wise remainder of division. When x < 0 xor y < 0 is multiply(...): Returns an element-wise x * y. multiply_no_nan(...): Computes the product of x and y and returns 0 if the y is zero, even if x is NaN or infinite. ndtri(...): Compute quantile of Standard Normal. negative(...): Computes numerical negative value element-wise. nextafter(...): Returns the next representable value of x1 in the direction of x2, element-wise. not_equal(...): Returns the truth value of (x != y) element-wise. polygamma(...): Compute the polygamma function \(\psi^{(n)}(x)\). polyval(...): Computes the elementwise value of a polynomial. pow(...): Computes the power of one value to another. real(...): Returns the real part of a complex (or real) tensor. reciprocal(...): Computes the reciprocal of x element-wise. reciprocal_no_nan(...): Performs a safe reciprocal operation, element wise. reduce_all(...): Computes the "logical and" of elements across dimensions of a tensor. reduce_any(...): Computes the "logical or" of elements across dimensions of a tensor. reduce_euclidean_norm(...): Computes the Euclidean norm of elements across dimensions of a tensor. reduce_logsumexp(...): Computes log(sum(exp(elements across dimensions of a tensor))). reduce_max(...): Computes the maximum of elements across dimensions of a tensor. reduce_mean(...): Computes the mean of elements across dimensions of a tensor. reduce_min(...): Computes the minimum of elements across dimensions of a tensor. reduce_prod(...): Computes the product of elements across dimensions of a tensor. reduce_std(...): Computes the standard deviation of elements across dimensions of a tensor. reduce_sum(...): Computes the sum of elements across dimensions of a tensor. reduce_variance(...): Computes the variance of elements across dimensions of a tensor. rint(...): Returns element-wise integer closest to x. round(...): Rounds the values of a tensor to the nearest integer, element-wise. rsqrt(...): Computes reciprocal of square root of x element-wise. scalar_mul(...): Multiplies a scalar times a Tensor or IndexedSlices object. segment_max(...): Computes the maximum along segments of a tensor. segment_mean(...): Computes the mean along segments of a tensor. segment_min(...): Computes the minimum along segments of a tensor. segment_prod(...): Computes the product along segments of a tensor. segment_sum(...): Computes the sum along segments of a tensor. sigmoid(...): Computes sigmoid of x element-wise. sign(...): Returns an element-wise indication of the sign of a number. sin(...): Computes sine of x element-wise. sinh(...): Computes hyperbolic sine of x element-wise. sobol_sample(...): Generates points from the Sobol sequence. softmax(...): Computes softmax activations. softplus(...): Computes softplus: log(exp(features) + 1). softsign(...): Computes softsign: features / (abs(features) + 1). sqrt(...): Computes element-wise square root of the input tensor. square(...): Computes square of x element-wise. squared_difference(...): Returns conj(x - y)(x - y) element-wise. subtract(...): Returns x - y element-wise. tan(...): Computes tan of x element-wise. tanh(...): Computes hyperbolic tangent of x element-wise. top_k(...): Finds values and indices of the k largest entries for the last dimension. truediv(...): Divides x / y elementwise (using Python 3 division operator semantics). unsorted_segment_max(...): Computes the maximum along segments of a tensor. unsorted_segment_mean(...): Computes the mean along segments of a tensor. unsorted_segment_min(...): Computes the minimum along segments of a tensor. unsorted_segment_prod(...): Computes the product along segments of a tensor. unsorted_segment_sqrt_n(...): Computes the sum along segments of a tensor divided by the sqrt(N). unsorted_segment_sum(...): Computes the sum along segments of a tensor. xdivy(...): Returns 0 if x == 0, and x / y otherwise, elementwise. xlog1py(...): Compute x * log1p(y). xlogy(...): Returns 0 if x == 0, and x * log(y) otherwise, elementwise. zero_fraction(...): Returns the fraction of zeros in value. zeta(...): Compute the Hurwitz zeta function \(\zeta(x, q)\). | tensorflow.math |
tf.math.abs View source on GitHub Computes the absolute value of a tensor. View aliases Main aliases
tf.abs Compat aliases for migration See Migration guide for more details. tf.compat.v1.abs, tf.compat.v1.math.abs
tf.math.abs(
x, name=None
)
Given a tensor of integer or floating-point values, this operation returns a tensor of the same type, where each element contains the absolute value of the corresponding element in the input. Given a tensor x of complex numbers, this operation returns a tensor of type float32 or float64 that is the absolute value of each element in x. For a complex number \(a + bj\), its absolute value is computed as \(\sqrt{a^2 + b^2}\). For example:
# real number
x = tf.constant([-2.25, 3.25])
tf.abs(x)
<tf.Tensor: shape=(2,), dtype=float32,
numpy=array([2.25, 3.25], dtype=float32)>
# complex number
x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]])
tf.abs(x)
<tf.Tensor: shape=(2, 1), dtype=float64, numpy=
array([[5.25594901],
[6.60492241]])>
Args
x A Tensor or SparseTensor of type float16, float32, float64, int32, int64, complex64 or complex128.
name A name for the operation (optional).
Returns A Tensor or SparseTensor of the same size, type and sparsity as x, with absolute values. Note, for complex64 or complex128 input, the returned Tensor will be of type float32 or float64, respectively. If x is a SparseTensor, returns SparseTensor(x.indices, tf.math.abs(x.values, ...), x.dense_shape) | tensorflow.math.abs |
tf.math.accumulate_n View source on GitHub Returns the element-wise sum of a list of tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.accumulate_n, tf.compat.v1.math.accumulate_n
tf.math.accumulate_n(
inputs, shape=None, tensor_dtype=None, name=None
)
Optionally, pass shape and tensor_dtype for shape and type checking, otherwise, these are inferred. accumulate_n performs the same operation as tf.math.add_n. For example: a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[5, 0], [0, 6]])
tf.math.accumulate_n([a, b, a]) # [[7, 4], [6, 14]]
# Explicitly pass shape and type
tf.math.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=tf.int32)
# [[7, 4],
# [6, 14]]
Args
inputs A list of Tensor objects, each with same shape and type.
shape Expected shape of elements of inputs (optional). Also controls the output shape of this op, which may affect type inference in other ops. A value of None means "infer the input shape from the shapes in inputs".
tensor_dtype Expected data type of inputs (optional). A value of None means "infer the input dtype from inputs[0]".
name A name for the operation (optional).
Returns A Tensor of same shape and type as the elements of inputs.
Raises
ValueError If inputs don't all have same shape and dtype or the shape cannot be inferred. | tensorflow.math.accumulate_n |
tf.math.acos View source on GitHub Computes acos of x element-wise. View aliases Main aliases
tf.acos Compat aliases for migration See Migration guide for more details. tf.compat.v1.acos, tf.compat.v1.math.acos
tf.math.acos(
x, name=None
)
Provided an input tensor, the tf.math.acos operation returns the inverse cosine of each element of the tensor. If y = tf.math.cos(x) then, x = tf.math.acos(y). Input range is [-1, 1] and the output has a range of [0, pi]. For example:
x = tf.constant([1.0, -0.5, 3.4, 0.2, 0.0, -2], dtype = tf.float32)
tf.math.acos(x)
<tf.Tensor: shape=(6,), dtype=float32,
numpy= array([0. , 2.0943952, nan, 1.3694383, 1.5707964, nan],
dtype=float32)>
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128, string.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x. | tensorflow.math.acos |
tf.math.acosh Computes inverse hyperbolic cosine of x element-wise. View aliases Main aliases
tf.acosh Compat aliases for migration See Migration guide for more details. tf.compat.v1.acosh, tf.compat.v1.math.acosh
tf.math.acosh(
x, name=None
)
Given an input tensor, the function computes inverse hyperbolic cosine of every element. Input range is [1, inf]. It returns nan if the input lies outside the range. x = tf.constant([-2, -0.5, 1, 1.2, 200, 10000, float("inf")])
tf.math.acosh(x) ==> [nan nan 0. 0.62236255 5.9914584 9.903487 inf]
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, complex64, complex128.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x. | tensorflow.math.acosh |
tf.math.add Returns x + y element-wise. View aliases Main aliases
tf.add Compat aliases for migration See Migration guide for more details. tf.compat.v1.add, tf.compat.v1.math.add
tf.math.add(
x, y, name=None
)
Note: math.add supports broadcasting. AddN does not. More about broadcasting here
Given two input tensors, the tf.add operation computes the sum for every element in the tensor. Both input and output have a range (-inf, inf).
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128, string.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x. | tensorflow.math.add |
tf.math.add_n View source on GitHub Adds all input tensors element-wise. View aliases Main aliases
tf.add_n Compat aliases for migration See Migration guide for more details. tf.compat.v1.add_n, tf.compat.v1.math.add_n
tf.math.add_n(
inputs, name=None
)
tf.math.add_n performs the same operation as tf.math.accumulate_n, but it waits for all of its inputs to be ready before beginning to sum. This buffering can result in higher memory consumption when inputs are ready at different times, since the minimum temporary storage required is proportional to the input size rather than the output size. This op does not broadcast its inputs. If you need broadcasting, use tf.math.add (or the + operator) instead. For example:
a = tf.constant([[3, 5], [4, 8]])
b = tf.constant([[1, 6], [2, 9]])
tf.math.add_n([a, b, a])
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 7, 16],
[10, 25]], dtype=int32)>
Args
inputs A list of tf.Tensor or tf.IndexedSlices objects, each with the same shape and type. tf.IndexedSlices objects will be converted into dense tensors prior to adding.
name A name for the operation (optional).
Returns A tf.Tensor of the same shape and type as the elements of inputs.
Raises
ValueError If inputs don't all have same shape and dtype or the shape cannot be inferred. | tensorflow.math.add_n |
tf.math.angle View source on GitHub Returns the element-wise argument of a complex (or real) tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.angle, tf.compat.v1.math.angle
tf.math.angle(
input, name=None
)
Given a tensor input, this operation returns a tensor of type float that is the argument of each element in input considered as a complex number. The elements in input are considered to be complex numbers of the form \(a + bj\), where a is the real part and b is the imaginary part. If input is real then b is zero by definition. The argument returned by this function is of the form \(atan2(b, a)\). If input is real, a tensor of all zeros is returned. For example: input = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j], dtype=tf.complex64)
tf.math.angle(input).numpy()
# ==> array([2.0131705, 1.056345 ], dtype=float32)
Args
input A Tensor. Must be one of the following types: float, double, complex64, complex128.
name A name for the operation (optional).
Returns A Tensor of type float32 or float64. | tensorflow.math.angle |
tf.math.argmax View source on GitHub Returns the index with the largest value across axes of a tensor. View aliases Main aliases
tf.argmax
tf.math.argmax(
input, axis=None, output_type=tf.dtypes.int64, name=None
)
In case of identity returns the smallest index. For example:
A = tf.constant([2, 20, 30, 3, 6])
tf.math.argmax(A) # A[2] is maximum in tensor A
<tf.Tensor: shape=(), dtype=int64, numpy=2>
B = tf.constant([[2, 20, 30, 3, 6], [3, 11, 16, 1, 8],
[14, 45, 23, 5, 27]])
tf.math.argmax(B, 0)
<tf.Tensor: shape=(5,), dtype=int64, numpy=array([2, 2, 0, 2, 2])>
tf.math.argmax(B, 1)
<tf.Tensor: shape=(3,), dtype=int64, numpy=array([2, 2, 1])>
C = tf.constant([0, 0, 0, 0])
tf.math.argmax(C) # Returns smallest index in case of ties
<tf.Tensor: shape=(), dtype=int64, numpy=0>
Args
input A Tensor.
axis An integer, the axis to reduce across. Default to 0.
output_type An optional output dtype (tf.int32 or tf.int64). Defaults to tf.int64.
name An optional name for the operation.
Returns A Tensor of type output_type. | tensorflow.math.argmax |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.