_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_27500 |
Return whether the artist is pickable. See also
set_picker, get_picker, pick | |
doc_27501 | A subclass of HTTPException. | |
doc_27502 |
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor). | |
doc_27503 | Returns a request with the data. If the request class is not specified request_class is used. Parameters
cls (Optional[Type[werkzeug.wrappers.request.Request]]) – The request wrapper to use. Return type
werkzeug.wrappers.request.Request | |
doc_27504 | Force as many objects as possible to be collected. This is needed because timely deallocation is not guaranteed by the garbage collector. This means that __del__ methods may be called later than expected and weakrefs may remain alive for longer than expected. | |
doc_27505 | This signal is sent when an application context is pushed. The sender is the application. This is usually useful for unittests in order to temporarily hook in information. For instance it can be used to set a resource early onto the g object. Example usage: from contextlib import contextmanager
from flask import appcontext_pushed
@contextmanager
def user_set(app, user):
def handler(sender, **kwargs):
g.user = user
with appcontext_pushed.connected_to(handler, app):
yield
And in the testcode: def test_user_me(self):
with user_set(app, 'john'):
c = app.test_client()
resp = c.get('/users/me')
assert resp.data == 'username=john'
Changelog New in version 0.10. | |
doc_27506 | stat.IO_REPARSE_TAG_MOUNT_POINT
stat.IO_REPARSE_TAG_APPEXECLINK
New in version 3.8. | |
doc_27507 | Retrieves the target object and calls its delete() method, then redirects to the success URL. | |
doc_27508 | class sklearn.linear_model.LinearRegression(*, fit_intercept=True, normalize=False, copy_X=True, n_jobs=None, positive=False) [source]
Ordinary least squares Linear Regression. LinearRegression fits a linear model with coefficients w = (w1, …, wp) to minimize the residual sum of squares between the observed targets in the dataset, and the targets predicted by the linear approximation. Parameters
fit_interceptbool, default=True
Whether to calculate the intercept for this model. If set to False, no intercept will be used in calculations (i.e. data is expected to be centered).
normalizebool, default=False
This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
copy_Xbool, default=True
If True, X will be copied; else, it may be overwritten.
n_jobsint, default=None
The number of jobs to use for the computation. This will only provide speedup for n_targets > 1 and sufficient large problems. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
positivebool, default=False
When set to True, forces the coefficients to be positive. This option is only supported for dense arrays. New in version 0.24. Attributes
coef_array of shape (n_features, ) or (n_targets, n_features)
Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features.
rank_int
Rank of matrix X. Only available when X is dense.
singular_array of shape (min(X, y),)
Singular values of X. Only available when X is dense.
intercept_float or array of shape (n_targets,)
Independent term in the linear model. Set to 0.0 if fit_intercept = False. See also
Ridge
Ridge regression addresses some of the problems of Ordinary Least Squares by imposing a penalty on the size of the coefficients with l2 regularization.
Lasso
The Lasso is a linear model that estimates sparse coefficients with l1 regularization.
ElasticNet
Elastic-Net is a linear regression model trained with both l1 and l2 -norm regularization of the coefficients. Notes From the implementation point of view, this is just plain Ordinary Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares (scipy.optimize.nnls) wrapped as a predictor object. Examples >>> import numpy as np
>>> from sklearn.linear_model import LinearRegression
>>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
>>> # y = 1 * x_0 + 2 * x_1 + 3
>>> y = np.dot(X, np.array([1, 2])) + 3
>>> reg = LinearRegression().fit(X, y)
>>> reg.score(X, y)
1.0
>>> reg.coef_
array([1., 2.])
>>> reg.intercept_
3.0000...
>>> reg.predict(np.array([[3, 5]]))
array([16.])
Methods
fit(X, y[, sample_weight]) Fit linear model.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit linear model. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data
yarray-like of shape (n_samples,) or (n_samples, n_targets)
Target values. Will be cast to X’s dtype if necessary
sample_weightarray-like of shape (n_samples,), default=None
Individual weights for each sample New in version 0.17: parameter sample_weight support to LinearRegression. Returns
selfreturns an instance of self.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X) [source]
Predict using the linear model. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape (n_samples,)
Returns predicted values.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
Examples using sklearn.linear_model.LinearRegression
Principal Component Regression vs Partial Least Squares Regression
Plot individual and voting regression predictions
Ordinary Least Squares and Ridge Regression Variance
Logistic function
Non-negative least squares
Linear Regression Example
Robust linear model estimation using RANSAC
Sparsity Example: Fitting only features 1 and 2
Theil-Sen Regression
Robust linear estimator fitting
Automatic Relevance Determination Regression (ARD)
Bayesian Ridge Regression
Isotonic Regression
Face completion with a multi-output estimators
Plotting Cross-Validated Predictions
Underfitting vs. Overfitting
Using KBinsDiscretizer to discretize continuous features | |
doc_27509 |
Select and call the function that accepts *args, **kwargs. funcs is a list of functions which should not raise any exception (other than TypeError if the arguments passed do not match their signature). select_matching_signature tries to call each of the functions in funcs with *args, **kwargs (in the order in which they are given). Calls that fail with a TypeError are silently skipped. As soon as a call succeeds, select_matching_signature returns its return value. If no function accepts *args, **kwargs, then the TypeError raised by the last failing call is re-raised. Callers should normally make sure that any *args, **kwargs can only bind a single func (to avoid any ambiguity), although this is not checked by select_matching_signature. Notes select_matching_signature is intended to help implementing signature-overloaded functions. In general, such functions should be avoided, except for back-compatibility concerns. A typical use pattern is def my_func(*args, **kwargs):
params = select_matching_signature(
[lambda old1, old2: locals(), lambda new: locals()],
*args, **kwargs)
if "old1" in params:
warn_deprecated(...)
old1, old2 = params.values() # note that locals() is ordered.
else:
new, = params.values()
# do things with params
which allows my_func to be called either with two parameters (old1 and old2) or a single one (new). Note that the new signature is given last, so that callers get a TypeError corresponding to the new signature if the arguments they passed in do not match any signature. | |
doc_27510 | See torch.cholesky_inverse() | |
doc_27511 |
Computes the (weighted) graph of k-Neighbors for points in X Parameters
Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None
The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features).
n_neighborsint, default=None
Number of neighbors for each sample. The default is the value passed to the constructor.
mode{‘connectivity’, ‘distance’}, default=’connectivity’
Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns
Asparse-matrix of shape (n_queries, n_samples_fit)
n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also
NearestNeighbors.radius_neighbors_graph
Examples >>> X = [[0], [3], [1]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(n_neighbors=2)
>>> neigh.fit(X)
NearestNeighbors(n_neighbors=2)
>>> A = neigh.kneighbors_graph(X)
>>> A.toarray()
array([[1., 0., 1.],
[0., 1., 1.],
[1., 0., 1.]]) | |
doc_27512 | Wide char variant of ungetch(), accepting a Unicode value. | |
doc_27513 | See Migration guide for more details. tf.compat.v1.keras.backend.set_image_data_format
tf.keras.backend.set_image_data_format(
data_format
)
Arguments
data_format string. 'channels_first' or 'channels_last'. Example:
tf.keras.backend.image_data_format()
'channels_last'
tf.keras.backend.set_image_data_format('channels_first')
tf.keras.backend.image_data_format()
'channels_first'
tf.keras.backend.set_image_data_format('channels_last')
Raises
ValueError In case of invalid data_format value. | |
doc_27514 | tf.compat.v1.keras.layers.experimental.preprocessing.StringLookup(
max_tokens=None, num_oov_indices=1, mask_token='',
oov_token='[UNK]', vocabulary=None, encoding=None, invert=False,
**kwargs
)
Methods adapt View source
adapt(
data, reset_state=True
)
Fits the state of the preprocessing layer to the dataset. Overrides the default adapt method to apply relevant preprocessing to the inputs before passing to the combiner.
Arguments
data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array.
reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt. This must be True for this layer, which does not support repeated calls to adapt. get_vocabulary View source
get_vocabulary()
set_vocabulary View source
set_vocabulary(
vocab
)
Sets vocabulary data for this layer with inverse=False. This method sets the vocabulary for this layer directly, instead of analyzing a dataset through 'adapt'. It should be used whenever the vocab information is already known. If vocabulary data is already present in the layer, this method will either replace it
Arguments
vocab An array of string tokens.
Raises
ValueError If there are too many inputs, the inputs do not match, or input data is missing. vocab_size View source
vocab_size() | |
doc_27515 |
Bases: skimage.viewer.canvastools.base.CanvasToolBase Widget for line selection in a plot. Parameters
managerViewer or PlotPlugin.
Skimage viewer or plot plugin object.
on_movefunction
Function called whenever a control handle is moved. This function must accept the end points of line as the only argument.
on_releasefunction
Function called whenever the control handle is released.
on_enterfunction
Function called whenever the “enter” key is pressed.
maxdistfloat
Maximum pixel distance allowed when selecting control handle.
line_propsdict
Properties for matplotlib.lines.Line2D.
handle_propsdict
Marker properties for the handles (also see matplotlib.lines.Line2D). Attributes
end_points2D array
End points of line ((x1, y1), (x2, y2)).
__init__(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, line_props=None, handle_props=None, **kwargs) [source]
Initialize self. See help(type(self)) for accurate signature.
property end_points
property geometry
Geometry information that gets passed to callback functions.
hit_test(event) [source]
on_mouse_press(event) [source]
on_mouse_release(event) [source]
on_move(event) [source]
update(x=None, y=None) [source] | |
doc_27516 | Used by session backends to determine if a Set-Cookie header should be set for this session cookie for this response. If the session has been modified, the cookie is set. If the session is permanent and the SESSION_REFRESH_EACH_REQUEST config is true, the cookie is always set. This check is usually skipped if the session was deleted. Changelog New in version 0.11. Parameters
app (Flask) –
session (flask.sessions.SessionMixin) – Return type
bool | |
doc_27517 |
Handler for Patch instances. Parameters
patch_funccallable, optional
The function that creates the legend key artist. patch_func should have the signature: def patch_func(legend=legend, orig_handle=orig_handle,
xdescent=xdescent, ydescent=ydescent,
width=width, height=height, fontsize=fontsize)
Subsequently the created artist will have its update_prop method called and the appropriate transform will be applied. **kwargs
Keyword arguments forwarded to HandlerBase. create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)[source] | |
doc_27518 | Sparse representation of the fitted coef_. | |
doc_27519 | 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
) | |
doc_27520 | This function resizes the internal memory buffer of obj, which must be an instance of a ctypes type. It is not possible to make the buffer smaller than the native size of the objects type, as given by sizeof(type(obj)), but it is possible to enlarge the buffer. | |
doc_27521 | Return the members as a list of their names. It has the same order as the list returned by getmembers(). | |
doc_27522 | For syntax errors - the compiler error message. | |
doc_27523 |
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'} | |
doc_27524 | tf.image.stateless_random_flip_up_down(
image, seed
)
Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). Example usage:
image = np.array([[[1], [2]], [[3], [4]]])
seed = (2, 3)
tf.image.stateless_random_flip_up_down(image, seed).numpy().tolist()
[[[3], [4]], [[1], [2]]]
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
Returns A tensor of the same type and shape as image. | |
doc_27525 | Alias for PROTOCOL_TLS. Deprecated since version 3.6: Use PROTOCOL_TLS instead. | |
doc_27526 |
Close open elements, up to (and including) the element identified by the given identifier. Parameters
id
Element identifier, as returned by the start() method. | |
doc_27527 |
Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels. Parameters
bottomfloat, default: 0.2
The bottom of the subplots for subplots_adjust.
rotationfloat, default: 30 degrees
The rotation angle of the xtick labels in degrees.
ha{'left', 'center', 'right'}, default: 'right'
The horizontal alignment of the xticklabels.
which{'major', 'minor', 'both'}, default: 'major'
Selects which ticklabels to rotate. | |
doc_27528 | def make_variables(k, initializer):
return (tf.Variable(initializer(shape=[k], dtype=tf.float32)),
tf.Variable(initializer(shape=[k, k], dtype=tf.float32)))
v1, v2 = make_variables(3, tf.ones_initializer())
v1
<tf.Variable ... shape=(3,) ... numpy=array([1., 1., 1.], dtype=float32)>
v2
<tf.Variable ... shape=(3, 3) ... numpy=
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=float32)>
make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.))
(<tf.Variable...shape=(4,) dtype=float32...>, <tf.Variable...shape=(4, 4) ...
Methods from_config View source
@classmethod
from_config(
config
)
Instantiates an initializer from a configuration dictionary. Example: initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
Args
config A Python dictionary. It will typically be the output of get_config.
Returns An Initializer instance.
get_config View source
get_config()
Returns the configuration of the initializer as a JSON-serializable dict.
Returns A JSON-serializable Python dict.
__call__ View source
__call__(
shape, dtype=tf.dtypes.float32, **kwargs
)
Returns a tensor object initialized as specified by the initializer.
Args
shape Shape of the tensor.
dtype Optional dtype of the tensor. Only numeric or boolean dtypes are supported.
**kwargs Additional keyword arguments.
Raises
ValuesError If the dtype is not numeric or boolean. | |
doc_27529 |
Partial Dependence Plot (PDP). This can also display individual partial dependencies which are often referred to as: Individual Condition Expectation (ICE). It is recommended to use plot_partial_dependence to create a PartialDependenceDisplay. All parameters are stored as attributes. Read more in Advanced Plotting With Partial Dependence and the User Guide. New in version 0.22. Parameters
pd_resultslist of Bunch
Results of partial_dependence for features.
featureslist of (int,) or list of (int, int)
Indices of features for a given plot. A tuple of one integer will plot a partial dependence curve of one feature. A tuple of two integers will plot a two-way partial dependence curve as a contour plot.
feature_nameslist of str
Feature names corresponding to the indices in features.
target_idxint
In a multiclass setting, specifies the class for which the PDPs should be computed. Note that for binary classification, the positive class (index 1) is always used. In a multioutput setting, specifies the task for which the PDPs should be computed. Ignored in binary classification or classical regression settings.
pdp_limdict
Global min and max average predictions, such that all plots will have the same scale and y limits. pdp_lim[1] is the global min and max for single partial dependence curves. pdp_lim[2] is the global min and max for two-way partial dependence curves.
decilesdict
Deciles for feature indices in features.
kind{‘average’, ‘individual’, ‘both’}, default=’average’
Whether to plot the partial dependence averaged across all the samples in the dataset or one line per sample or both.
kind='average' results in the traditional PD plot;
kind='individual' results in the ICE plot. Note that the fast method='recursion' option is only available for kind='average'. Plotting individual dependencies requires using the slower method='brute' option. New in version 0.24.
subsamplefloat, int or None, default=1000
Sampling for ICE curves when kind is ‘individual’ or ‘both’. If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to be used to plot ICE curves. If int, represents the maximum absolute number of samples to use. Note that the full dataset is still used to calculate partial dependence when kind='both'. New in version 0.24.
random_stateint, RandomState instance or None, default=None
Controls the randomness of the selected samples when subsamples is not None. See Glossary for details. New in version 0.24. Attributes
bounding_ax_matplotlib Axes or None
If ax is an axes or None, the bounding_ax_ is the axes where the grid of partial dependence plots are drawn. If ax is a list of axes or a numpy array of axes, bounding_ax_ is None.
axes_ndarray of matplotlib Axes
If ax is an axes or None, axes_[i, j] is the axes on the i-th row and j-th column. If ax is a list of axes, axes_[i] is the i-th item in ax. Elements that are None correspond to a nonexisting axes in that position.
lines_ndarray of matplotlib Artists
If ax is an axes or None, lines_[i, j] is the partial dependence curve on the i-th row and j-th column. If ax is a list of axes, lines_[i] is the partial dependence curve corresponding to the i-th item in ax. Elements that are None correspond to a nonexisting axes or an axes that does not include a line plot.
deciles_vlines_ndarray of matplotlib LineCollection
If ax is an axes or None, vlines_[i, j] is the line collection representing the x axis deciles of the i-th row and j-th column. If ax is a list of axes, vlines_[i] corresponds to the i-th item in ax. Elements that are None correspond to a nonexisting axes or an axes that does not include a PDP plot. New in version 0.23.
deciles_hlines_ndarray of matplotlib LineCollection
If ax is an axes or None, vlines_[i, j] is the line collection representing the y axis deciles of the i-th row and j-th column. If ax is a list of axes, vlines_[i] corresponds to the i-th item in ax. Elements that are None correspond to a nonexisting axes or an axes that does not include a 2-way plot. New in version 0.23.
contours_ndarray of matplotlib Artists
If ax is an axes or None, contours_[i, j] is the partial dependence plot on the i-th row and j-th column. If ax is a list of axes, contours_[i] is the partial dependence plot corresponding to the i-th item in ax. Elements that are None correspond to a nonexisting axes or an axes that does not include a contour plot.
figure_matplotlib Figure
Figure containing partial dependence plots. See also
partial_dependence
Compute Partial Dependence values.
plot_partial_dependence
Plot Partial Dependence. Methods
plot(*[, ax, n_cols, line_kw, contour_kw]) Plot partial dependence plots.
plot(*, ax=None, n_cols=3, line_kw=None, contour_kw=None) [source]
Plot partial dependence plots. Parameters
axMatplotlib axes or array-like of Matplotlib axes, default=None
If a single axis is passed in, it is treated as a bounding axes
and a grid of partial dependence plots will be drawn within these bounds. The n_cols parameter controls the number of columns in the grid.
If an array-like of axes are passed in, the partial dependence
plots will be drawn directly into these axes.
If None, a figure and a bounding axes is created and treated
as the single axes case.
n_colsint, default=3
The maximum number of columns in the grid plot. Only active when ax is a single axes or None.
line_kwdict, default=None
Dict with keywords passed to the matplotlib.pyplot.plot call. For one-way partial dependence plots.
contour_kwdict, default=None
Dict with keywords passed to the matplotlib.pyplot.contourf call for two-way partial dependence plots. Returns
displayPartialDependenceDisplay | |
doc_27530 | tf.metrics.SensitivityAtSpecificity Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.SensitivityAtSpecificity
tf.keras.metrics.SensitivityAtSpecificity(
specificity, num_thresholds=200, name=None, dtype=None
)
the sensitivity at a given specificity. Sensitivity measures the proportion of actual positives that are correctly identified as such (tp / (tp + fn)). Specificity measures the proportion of actual negatives that are correctly identified as such (tn / (tn + fp)). This metric creates four local variables, true_positives, true_negatives, false_positives and false_negatives that are used to compute the sensitivity at the given specificity. The threshold for the given specificity value is computed and used to evaluate the corresponding sensitivity. If sample_weight is None, weights default to 1. Use sample_weight of 0 to mask values. For additional information about specificity and sensitivity, see the following.
Args
specificity A scalar value in range [0, 1].
num_thresholds (Optional) Defaults to 200. The number of thresholds to use for matching the given specificity.
name (Optional) string name of the metric instance.
dtype (Optional) data type of the metric result. Standalone usage:
m = tf.keras.metrics.SensitivityAtSpecificity(0.5)
m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8])
m.result().numpy()
0.5
m.reset_states()
m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8],
sample_weight=[1, 1, 2, 2, 1])
m.result().numpy()
0.333333
Usage with compile() API: model.compile(
optimizer='sgd',
loss='mse',
metrics=[tf.keras.metrics.SensitivityAtSpecificity()])
Methods reset_states View source
reset_states()
Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
y_true, y_pred, sample_weight=None
)
Accumulates confusion matrix statistics.
Args
y_true The ground truth values.
y_pred The predicted values.
sample_weight Optional weighting of each example. Defaults to 1. Can be a Tensor whose rank is either 0, or the same rank as y_true, and must be broadcastable to y_true.
Returns Update op. | |
doc_27531 | Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to str, for example, would make option names case sensitive: cfgparser = ConfigParser()
cfgparser.optionxform = str
Note that when reading configuration files, whitespace around the option names is stripped before optionxform() is called. | |
doc_27532 | draw an antialiased polygon aapolygon(surface, points, color) -> None Draws an unfilled antialiased polygon on the given surface. The adjacent coordinates in the points argument, as well as the first and last points, will be connected by line segments. e.g. For the points [(x1, y1), (x2, y2), (x3, y3)] a line segment will be drawn from (x1, y1) to (x2, y2), from (x2, y2) to (x3, y3), and from (x3, y3) to (x1, y1).
Parameters:
surface (Surface) -- surface to draw on
points (tuple(coordinate) or list(coordinate)) -- a sequence of 3 or more (x, y) coordinates, where each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats (float values will be truncated)
color (Color or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
Returns:
None
Return type:
NoneType
Raises:
ValueError -- if len(points) < 3 (must have at least 3 points)
IndexError -- if len(coordinate) < 2 (each coordinate must have at least 2 items) | |
doc_27533 | operator.__sub__(a, b)
Return a - b. | |
doc_27534 | tf.compat.v1.distribute.get_loss_reduction()
This is used to decide whether loss should be scaled in optimizer (used only for estimator + v1 optimizer use case).
Returns tf.distribute.ReduceOp corresponding to the last loss reduction for estimator and v1 optimizer use case. tf.distribute.ReduceOp.SUM otherwise. | |
doc_27535 | Return the maximum allowed number of headers named name. Called when a header is added to an EmailMessage or Message object. If the returned value is not 0 or None, and there are already a number of headers with the name name greater than or equal to the value returned, a ValueError is raised. Because the default behavior of Message.__setitem__ is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a Message programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.) The default implementation returns None for all header names. | |
doc_27536 | class sklearn.cluster.SpectralClustering(n_clusters=8, *, eigen_solver=None, n_components=None, random_state=None, n_init=10, gamma=1.0, affinity='rbf', n_neighbors=10, eigen_tol=0.0, assign_labels='kmeans', degree=3, coef0=1, kernel_params=None, n_jobs=None, verbose=False) [source]
Apply clustering to a projection of the normalized Laplacian. In practice Spectral Clustering is very useful when the structure of the individual clusters is highly non-convex or more generally when a measure of the center and spread of the cluster is not a suitable description of the complete cluster. For instance when clusters are nested circles on the 2D plane. If affinity is the adjacency matrix of a graph, this method can be used to find normalized graph cuts. When calling fit, an affinity matrix is constructed using either kernel function such the Gaussian (aka RBF) kernel of the euclidean distanced d(X, X): np.exp(-gamma * d(X,X) ** 2)
or a k-nearest neighbors connectivity matrix. Alternatively, using precomputed, a user-provided affinity matrix can be used. Read more in the User Guide. Parameters
n_clustersint, default=8
The dimension of the projection subspace.
eigen_solver{‘arpack’, ‘lobpcg’, ‘amg’}, default=None
The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities. If None, then 'arpack' is used.
n_componentsint, default=n_clusters
Number of eigen vectors to use for the spectral embedding
random_stateint, RandomState instance, default=None
A pseudo random number generator used for the initialization of the lobpcg eigen vectors decomposition when eigen_solver='amg' and by the K-Means initialization. Use an int to make the randomness deterministic. See Glossary.
n_initint, default=10
Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia.
gammafloat, default=1.0
Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels. Ignored for affinity='nearest_neighbors'.
affinitystr or callable, default=’rbf’
How to construct the affinity matrix.
‘nearest_neighbors’ : construct the affinity matrix by computing a graph of nearest neighbors. ‘rbf’ : construct the affinity matrix using a radial basis function (RBF) kernel. ‘precomputed’ : interpret X as a precomputed affinity matrix. ‘precomputed_nearest_neighbors’ : interpret X as a sparse graph of precomputed nearest neighbors, and constructs the affinity matrix by selecting the n_neighbors nearest neighbors. one of the kernels supported by pairwise_kernels. Only kernels that produce similarity scores (non-negative values that increase with similarity) should be used. This property is not checked by the clustering algorithm.
n_neighborsint, default=10
Number of neighbors to use when constructing the affinity matrix using the nearest neighbors method. Ignored for affinity='rbf'.
eigen_tolfloat, default=0.0
Stopping criterion for eigendecomposition of the Laplacian matrix when eigen_solver='arpack'.
assign_labels{‘kmeans’, ‘discretize’}, default=’kmeans’
The strategy to use to assign labels in the embedding space. There are two ways to assign labels after the laplacian embedding. k-means can be applied and is a popular choice. But it can also be sensitive to initialization. Discretization is another approach which is less sensitive to random initialization.
degreefloat, default=3
Degree of the polynomial kernel. Ignored by other kernels.
coef0float, default=1
Zero coefficient for polynomial and sigmoid kernels. Ignored by other kernels.
kernel_paramsdict of str to any, default=None
Parameters (keyword arguments) and values for kernel passed as callable object. Ignored by other kernels.
n_jobsint, default=None
The number of parallel jobs to run when affinity='nearest_neighbors' or affinity='precomputed_nearest_neighbors'. The neighbors search will be done in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
verbosebool, default=False
Verbosity mode. New in version 0.24. Attributes
affinity_matrix_array-like of shape (n_samples, n_samples)
Affinity matrix used for clustering. Available only if after calling fit.
labels_ndarray of shape (n_samples,)
Labels of each point Notes If you have an affinity matrix, such as a distance matrix, for which 0 means identical elements, and high values means very dissimilar elements, it can be transformed in a similarity matrix that is well suited for the algorithm by applying the Gaussian (RBF, heat) kernel: np.exp(- dist_matrix ** 2 / (2. * delta ** 2))
Where delta is a free parameter representing the width of the Gaussian kernel. Another alternative is to take a symmetric version of the k nearest neighbors connectivity matrix of the points. If the pyamg package is installed, it is used: this greatly speeds up computation. References Normalized cuts and image segmentation, 2000 Jianbo Shi, Jitendra Malik http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324
A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323
Multiclass spectral clustering, 2003 Stella X. Yu, Jianbo Shi https://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf
Examples >>> from sklearn.cluster import SpectralClustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralClustering(n_clusters=2,
... assign_labels="discretize",
... random_state=0).fit(X)
>>> clustering.labels_
array([1, 1, 1, 0, 0, 0])
>>> clustering
SpectralClustering(assign_labels='discretize', n_clusters=2,
random_state=0)
Methods
fit(X[, y]) Perform spectral clustering from features, or affinity matrix.
fit_predict(X[, y]) Perform spectral clustering from features, or affinity matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Perform spectral clustering from features, or affinity matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None) [source]
Perform spectral clustering from features, or affinity matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
Examples using sklearn.cluster.SpectralClustering
Comparing different clustering algorithms on toy datasets | |
doc_27537 | Add the given payload to the current payload, which must be None or a list of Message objects before the call. After the call, the payload will always be a list of Message objects. If you want to set the payload to a scalar object (e.g. a string), use set_payload() instead. This is a legacy method. On the EmailMessage class its functionality is replaced by set_content() and the related make and add methods. | |
doc_27538 |
Return an iterable of the ModuleDict values. | |
doc_27539 | Returns a panel object, associating it with the given window win. Be aware that you need to keep the returned panel object referenced explicitly. If you don’t, the panel object is garbage collected and removed from the panel stack. | |
doc_27540 | Use this method to render the raw value of this field as it would be rendered by a Widget: >>> initial = {'subject': 'welcome'}
>>> unbound_form = ContactForm(initial=initial)
>>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial)
>>> print(unbound_form['subject'].value())
welcome
>>> print(bound_form['subject'].value())
hi | |
doc_27541 |
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values. | |
doc_27542 | Creates an SSL key for development. This should be used instead of the 'adhoc' key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN *.host/CN=host. For more information see run_simple(). Changelog New in version 0.9. Parameters
base_path (str) – the path to the certificate and key. The extension .crt is added for the certificate, .key is added for the key.
host (Optional[str]) – the name of the host. This can be used as an alternative for the cn.
cn (Optional[str]) – the CN to use. Return type
Tuple[str, str] | |
doc_27543 | Declares that function should be used as a “reduction” function for objects of type type. function should return either a string or a tuple containing two or three elements. The optional constructor parameter, if provided, is a callable object which can be used to reconstruct the object when called with the tuple of arguments returned by function at pickling time. TypeError will be raised if object is a class or constructor is not callable. See the pickle module for more details on the interface expected of function and constructor. Note that the dispatch_table attribute of a pickler object or subclass of pickle.Pickler can also be used for declaring reduction functions. | |
doc_27544 | An array that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_name[0] is the empty string. | |
doc_27545 |
Vandermonde matrix of given degree. Returns the Vandermonde matrix of degree deg and sample points x. The Vandermonde matrix is defined by \[V[..., i] = x^i,\] where 0 <= i <= deg. The leading indices of V index the elements of x and the last index is the power of x. If c is a 1-D array of coefficients of length n + 1 and V is the matrix V = polyvander(x, n), then np.dot(V, c) and polyval(x, c) are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of polynomials of the same degree and sample points. Parameters
xarray_like
Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If x is scalar it is converted to a 1-D array.
degint
Degree of the resulting matrix. Returns
vanderndarray.
The Vandermonde matrix. The shape of the returned matrix is x.shape + (deg + 1,), where the last index is the power of x. The dtype will be the same as the converted x. See also
polyvander2d, polyvander3d | |
doc_27546 | Return the index of the header in the set or raise an IndexError. Parameters
header – the header to be looked up. | |
doc_27547 |
Context-manager that disabled gradient calculation. Disabling gradient calculation is useful for inference, when you are sure that you will not call Tensor.backward(). It will reduce memory consumption for computations that would otherwise have requires_grad=True. In this mode, the result of every computation will have requires_grad=False, even when the inputs have requires_grad=True. This context manager is thread local; it will not affect computation in other threads. Also functions as a decorator. (Make sure to instantiate with parenthesis.) Example: >>> x = torch.tensor([1], requires_grad=True)
>>> with torch.no_grad():
... y = x * 2
>>> y.requires_grad
False
>>> @torch.no_grad()
... def doubler(x):
... return x * 2
>>> z = doubler(x)
>>> z.requires_grad
False | |
doc_27548 | The child return code, set by poll() and wait() (and indirectly by communicate()). A None value indicates that the process hasn’t terminated yet. A negative value -N indicates that the child was terminated by signal N (POSIX only). | |
doc_27549 |
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor). | |
doc_27550 |
Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. See also char.isdigit | |
doc_27551 |
Return a reference to the shared axes Grouper object for y axes. | |
doc_27552 |
Attributes
partition_graphs repeated GraphDef partition_graphs
post_optimization_graph GraphDef post_optimization_graph
pre_optimization_graph GraphDef pre_optimization_graph | |
doc_27553 |
Set the antialiasing state for rendering. Parameters
aabool or list of bools | |
doc_27554 | Casts this storage to bool type | |
doc_27555 | Django view for the model instance(s) deletion confirmation page. See note below. | |
doc_27556 | User identifier of the file owner. | |
doc_27557 | set - other - ...
Return a new set with elements in the set that are not in the others. | |
doc_27558 | Set the propertyname to value. If the property is not recognized, SAXNotRecognizedException is raised. If the property or its setting is not supported by the parser, SAXNotSupportedException is raised. | |
doc_27559 | See Migration guide for more details. tf.compat.v1.raw_ops.RGBToHSV
tf.raw_ops.RGBToHSV(
images, name=None
)
Outputs a tensor of the same shape as the images tensor, containing the HSV value of the pixels. The output is only well defined if the value in images are in [0,1]. output[..., 0] contains hue, output[..., 1] contains saturation, and output[..., 2] contains value. All HSV values are in [0,1]. A hue of 0 corresponds to pure red, hue 1/3 is pure green, and 2/3 is pure blue. Usage Example:
blue_image = tf.stack([
tf.zeros([5,5]),
tf.zeros([5,5]),
tf.ones([5,5])],
axis=-1)
blue_hsv_image = tf.image.rgb_to_hsv(blue_image)
blue_hsv_image[0,0].numpy()
array([0.6666667, 1. , 1. ], dtype=float32)
Args
images A Tensor. Must be one of the following types: half, bfloat16, float32, float64. 1-D or higher rank. RGB data to convert. Last dimension must be size 3.
name A name for the operation (optional).
Returns A Tensor. Has the same type as images. | |
doc_27560 | Check whether we should break here, depending on the way the breakpoint b was set. If it was set via line number, it checks if b.line is the same as the one in the frame also passed as argument. If the breakpoint was set via function name, we have to check we are in the right frame (the right function) and if we are in its first executable line. | |
doc_27561 |
Set whether the widget is active. | |
doc_27562 |
Bases: matplotlib.transforms.Affine2DBase BboxTransform linearly transforms points from one Bbox to another. Create a new BboxTransform that linearly transforms points from boxin to boxout. __init__(boxin, boxout, **kwargs)[source]
Create a new BboxTransform that linearly transforms points from boxin to boxout.
__module__='matplotlib.transforms'
__str__()[source]
Return str(self).
get_matrix()[source]
Get the matrix for the affine part of this transform.
is_separable=True
True if this transform is separable in the x- and y- dimensions. | |
doc_27563 |
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned. | |
doc_27564 | Rename this file or directory to the given target, and return a new Path instance pointing to target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object: >>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
PosixPath('bar')
>>> target.open().read()
'some text'
The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object. Changed in version 3.8: Added return value, return the new Path instance. | |
doc_27565 |
Return a Dataframe of the components of the Timedeltas. Returns
DataFrame
Examples
>>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='s'))
>>> s
0 0 days 00:00:00
1 0 days 00:00:01
2 0 days 00:00:02
3 0 days 00:00:03
4 0 days 00:00:04
dtype: timedelta64[ns]
>>> s.dt.components
days hours minutes seconds milliseconds microseconds nanoseconds
0 0 0 0 0 0 0 0
1 0 0 0 1 0 0 0
2 0 0 0 2 0 0 0
3 0 0 0 3 0 0 0
4 0 0 0 4 0 0 0 | |
doc_27566 | See Migration guide for more details. tf.compat.v1.raw_ops.RandomCrop
tf.raw_ops.RandomCrop(
image, size, seed=0, seed2=0, name=None
)
size is a 1-D int64 tensor with 2 elements representing the crop height and width. The values must be non negative. This Op picks a random location in image and crops a height by width rectangle from that location. The random location is picked so the cropped area will fit inside the original image.
Args
image A Tensor. Must be one of the following types: uint8, int8, int16, int32, int64, float32, float64. 3-D of shape [height, width, channels].
size A Tensor of type int64. 1-D of length 2 containing: crop_height, crop_width..
seed An optional int. Defaults to 0. If either seed or seed2 are set to be non-zero, the random number generator is seeded by the given seed. Otherwise, it is seeded by a random seed.
seed2 An optional int. Defaults to 0. An second seed to avoid seed collision.
name A name for the operation (optional).
Returns A Tensor. Has the same type as image. | |
doc_27567 | An abstract base class for objects representing a file system path, e.g. pathlib.PurePath. New in version 3.6.
abstractmethod __fspath__()
Return the file system path representation of the object. The method should only return a str or bytes object, with the preference being for str. | |
doc_27568 |
Update the pixel positions of the annotation text and the arrow patch. | |
doc_27569 | Start a Unix socket server. Similar to start_server() but works with Unix sockets. See also the documentation of loop.create_unix_server(). Availability: Unix. New in version 3.7: The ssl_handshake_timeout and start_serving parameters. Changed in version 3.7: The path parameter can now be a path-like object. | |
doc_27570 |
Test element-wise for positive or negative infinity. Returns a boolean array of the same shape as x, True where x ==
+/-inf, otherwise False. Parameters
xarray_like
Input values
outndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs
For other keyword-only arguments, see the ufunc docs. Returns
ybool (scalar) or boolean ndarray
True where x is positive or negative infinity, false otherwise. This is a scalar if x is a scalar. See also
isneginf, isposinf, isnan, isfinite
Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Errors result if the second argument is supplied when the first argument is a scalar, or if the first and second arguments have different shapes. Examples >>> np.isinf(np.inf)
True
>>> np.isinf(np.nan)
False
>>> np.isinf(np.NINF)
True
>>> np.isinf([np.inf, -np.inf, 1.0, np.nan])
array([ True, True, False, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([2, 2, 2])
>>> np.isinf(x, y)
array([1, 0, 1])
>>> y
array([1, 0, 1]) | |
doc_27571 | Called after the request is dispatched and the response is returned, right before the request context is popped. This calls all functions decorated with teardown_request(), and Blueprint.teardown_request() if a blueprint handled the request. Finally, the request_tearing_down signal is sent. This is called by RequestContext.pop(), which may be delayed during testing to maintain access to resources. Parameters
exc (Optional[BaseException]) – An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function. Return type
None Changelog Changed in version 0.9: Added the exc argument. | |
doc_27572 | Create and return a comment node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree. | |
doc_27573 |
Return the artist's zorder. | |
doc_27574 |
Sets the random number generator state of all devices. Parameters
new_states (Iterable of torch.ByteTensor) – The desired state for each device | |
doc_27575 | In-memory text streams are also available as StringIO objects: f = io.StringIO("some initial text data")
The text stream API is described in detail in the documentation of TextIOBase. Binary I/O Binary I/O (also called buffered I/O) expects bytes-like objects and produces bytes objects. No encoding, decoding, or newline translation is performed. This category of streams can be used for all kinds of non-text data, and also when manual control over the handling of text data is desired. The easiest way to create a binary stream is with open() with 'b' in the mode string: f = open("myfile.jpg", "rb")
In-memory binary streams are also available as BytesIO objects: f = io.BytesIO(b"some initial binary data: \x00\x01")
The binary stream API is described in detail in the docs of BufferedIOBase. Other library modules may provide additional ways to create text or binary streams. See socket.socket.makefile() for example. Raw I/O Raw I/O (also called unbuffered I/O) is generally used as a low-level building-block for binary and text streams; it is rarely useful to directly manipulate a raw stream from user code. Nevertheless, you can create a raw stream by opening a file in binary mode with buffering disabled: f = open("myfile.jpg", "rb", buffering=0)
The raw stream API is described in detail in the docs of RawIOBase. High-level Module Interface
io.DEFAULT_BUFFER_SIZE
An int containing the default buffer size used by the module’s buffered I/O classes. open() uses the file’s blksize (as obtained by os.stat()) if possible.
io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
This is an alias for the builtin open() function.
This function raises an auditing event open with arguments path, mode and flags. The mode and flags arguments may have been modified or inferred from the original call.
io.open_code(path)
Opens the provided file with mode 'rb'. This function should be used when the intent is to treat the contents as executable code. path should be a str and an absolute path. The behavior of this function may be overridden by an earlier call to the PyFile_SetOpenCodeHook(). However, assuming that path is a str and an absolute path, open_code(path) should always behave the same as open(path, 'rb'). Overriding the behavior is intended for additional validation or preprocessing of the file. New in version 3.8.
exception io.BlockingIOError
This is a compatibility alias for the builtin BlockingIOError exception.
exception io.UnsupportedOperation
An exception inheriting OSError and ValueError that is raised when an unsupported operation is called on a stream.
See also
sys
contains the standard IO streams: sys.stdin, sys.stdout, and sys.stderr. Class hierarchy The implementation of I/O streams is organized as a hierarchy of classes. First abstract base classes (ABCs), which are used to specify the various categories of streams, then concrete classes providing the standard stream implementations. Note The abstract base classes also provide default implementations of some methods in order to help implementation of concrete stream classes. For example, BufferedIOBase provides unoptimized implementations of readinto() and readline(). At the top of the I/O hierarchy is the abstract base class IOBase. It defines the basic interface to a stream. Note, however, that there is no separation between reading and writing to streams; implementations are allowed to raise UnsupportedOperation if they do not support a given operation. The RawIOBase ABC extends IOBase. It deals with the reading and writing of bytes to a stream. FileIO subclasses RawIOBase to provide an interface to files in the machine’s file system. The BufferedIOBase ABC extends IOBase. It deals with buffering on a raw binary stream (RawIOBase). Its subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer raw binary streams that are readable, writable, and both readable and writable, respectively. BufferedRandom provides a buffered interface to seekable streams. Another BufferedIOBase subclass, BytesIO, is a stream of in-memory bytes. The TextIOBase ABC extends IOBase. It deals with streams whose bytes represent text, and handles encoding and decoding to and from strings. TextIOWrapper, which extends TextIOBase, is a buffered text interface to a buffered raw stream (BufferedIOBase). Finally, StringIO is an in-memory stream for text. Argument names are not part of the specification, and only the arguments of open() are intended to be used as keyword arguments. The following table summarizes the ABCs provided by the io module:
ABC Inherits Stub Methods Mixin Methods and Properties
IOBase fileno, seek, and truncate close, closed, __enter__, __exit__, flush, isatty, __iter__, __next__, readable, readline, readlines, seekable, tell, writable, and writelines
RawIOBase IOBase readinto and write Inherited IOBase methods, read, and readall
BufferedIOBase IOBase detach, read, read1, and write Inherited IOBase methods, readinto, and readinto1
TextIOBase IOBase detach, read, readline, and write Inherited IOBase methods, encoding, errors, and newlines I/O Base Classes
class io.IOBase
The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor. This class provides empty abstract implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked. Even though IOBase does not declare read() or write() because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise a ValueError (or UnsupportedOperation) when operations they do not support are called. The basic type used for binary data read from or written to a file is bytes. Other bytes-like objects are accepted as method arguments too. Text I/O classes work with str data. Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise ValueError in this case. IOBase (and its subclasses) supports the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream. Lines are defined slightly differently depending on whether the stream is a binary stream (yielding bytes), or a text stream (yielding character strings). See readline() below. IOBase is also a context manager and therefore supports the with statement. In this example, file is closed after the with statement’s suite is finished—even if an exception occurs: with open('spam.txt', 'w') as file:
file.write('Spam and eggs!')
IOBase provides these data attributes and methods:
close()
Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file (e.g. reading or writing) will raise a ValueError. As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect.
closed
True if the stream is closed.
fileno()
Return the underlying file descriptor (an integer) of the stream if it exists. An OSError is raised if the IO object does not use a file descriptor.
flush()
Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams.
isatty()
Return True if the stream is interactive (i.e., connected to a terminal/tty device).
readable()
Return True if the stream can be read from. If False, read() will raise OSError.
readline(size=-1)
Read and return one line from the stream. If size is specified, at most size bytes will be read. The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.
readlines(hint=-1)
Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint. Note that it’s already possible to iterate on file objects using for
line in file: ... without calling file.readlines().
seek(offset, whence=SEEK_SET)
Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:
SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
SEEK_CUR or 1 – current stream position; offset may be negative
SEEK_END or 2 – end of the stream; offset is usually negative Return the new absolute position. New in version 3.1: The SEEK_* constants. New in version 3.3: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA. The valid values for a file could depend on it being open in text or binary mode.
seekable()
Return True if the stream supports random access. If False, seek(), tell() and truncate() will raise OSError.
tell()
Return the current stream position.
truncate(size=None)
Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned. Changed in version 3.5: Windows will now zero-fill files when extending.
writable()
Return True if the stream supports writing. If False, write() and truncate() will raise OSError.
writelines(lines)
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
__del__()
Prepare for object destruction. IOBase provides a default implementation of this method that calls the instance’s close() method.
class io.RawIOBase
Base class for raw binary streams. It inherits IOBase. There is no public constructor. Raw binary streams typically provide low-level access to an underlying OS device or API, and do not try to encapsulate it in high-level primitives (this functionality is done at a higher-level in buffered binary streams and text streams, described later in this page). RawIOBase provides these methods in addition to those from IOBase:
read(size=-1)
Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Otherwise, only one system call is ever made. Fewer than size bytes may be returned if the operating system call returns fewer than size bytes. If 0 bytes are returned, and size was not 0, this indicates end of file. If the object is in non-blocking mode and no bytes are available, None is returned. The default implementation defers to readall() and readinto().
readall()
Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary.
readinto(b)
Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. For example, b might be a bytearray. If the object is in non-blocking mode and no bytes are available, None is returned.
write(b)
Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. This can be less than the length of b in bytes, depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode. None is returned if the raw stream is set not to block and no single byte could be readily written to it. The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.
class io.BufferedIOBase
Base class for binary streams that support some kind of buffering. It inherits IOBase. There is no public constructor. The main difference with RawIOBase is that methods read(), readinto() and write() will try (respectively) to read as much input as requested or to consume all given output, at the expense of making perhaps more than one system call. In addition, those methods can raise BlockingIOError if the underlying raw stream is in non-blocking mode and cannot take or give enough data; unlike their RawIOBase counterparts, they will never return None. Besides, the read() method does not have a default implementation that defers to readinto(). A typical BufferedIOBase implementation should not inherit from a RawIOBase implementation, but wrap one, like BufferedWriter and BufferedReader do. BufferedIOBase provides or overrides these data attributes and methods in addition to those from IOBase:
raw
The underlying raw stream (a RawIOBase instance) that BufferedIOBase deals with. This is not part of the BufferedIOBase API and may not exist on some implementations.
detach()
Separate the underlying raw stream from the buffer and return it. After the raw stream has been detached, the buffer is in an unusable state. Some buffers, like BytesIO, do not have the concept of a single raw stream to return from this method. They raise UnsupportedOperation. New in version 3.1.
read(size=-1)
Read and return up to size bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. An empty bytes object is returned if the stream is already at EOF. If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent. A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
read1([size])
Read and return up to size bytes, with at most one call to the underlying raw stream’s read() (or readinto()) method. This can be useful if you are implementing your own buffering on top of a BufferedIOBase object. If size is -1 (the default), an arbitrary number of bytes are returned (more than zero unless EOF is reached).
readinto(b)
Read bytes into a pre-allocated, writable bytes-like object b and return the number of bytes read. For example, b might be a bytearray. Like read(), multiple reads may be issued to the underlying raw stream, unless the latter is interactive. A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
readinto1(b)
Read bytes into a pre-allocated, writable bytes-like object b, using at most one call to the underlying raw stream’s read() (or readinto()) method. Return the number of bytes read. A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment. New in version 3.5.
write(b)
Write the given bytes-like object, b, and return the number of bytes written (always equal to the length of b in bytes, since if the write fails an OSError will be raised). Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons. When in non-blocking mode, a BlockingIOError is raised if the data needed to be written to the raw stream but it couldn’t accept all the data without blocking. The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.
Raw File I/O
class io.FileIO(name, mode='r', closefd=True, opener=None)
A raw binary stream representing an OS-level file containing bytes data. It inherits RawIOBase. The name can be one of two things: a character string or bytes object representing the path to the file which will be opened. In this case closefd must be True (the default) otherwise an error will be raised. an integer representing the number of an existing OS-level file descriptor to which the resulting FileIO object will give access. When the FileIO object is closed this fd will be closed as well, unless closefd is set to False. The mode can be 'r', 'w', 'x' or 'a' for reading (default), writing, exclusive creation or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. FileExistsError will be raised if it already exists when opened for creating. Opening a file for creating implies writing, so this mode behaves in a similar way to 'w'. Add a '+' to the mode to allow simultaneous reading and writing. The read() (when called with a positive argument), readinto() and write() methods on this class will only make one system call. A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (name, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None). The newly created file is non-inheritable. See the open() built-in function for examples on using the opener parameter. Changed in version 3.3: The opener parameter was added. The 'x' mode was added. Changed in version 3.4: The file is now non-inheritable. FileIO provides these data attributes in addition to those from RawIOBase and IOBase:
mode
The mode as given in the constructor.
name
The file name. This is the file descriptor of the file when no name is given in the constructor.
Buffered Streams Buffered I/O streams provide a higher-level interface to an I/O device than raw I/O does.
class io.BytesIO([initial_bytes])
A binary stream using an in-memory bytes buffer. It inherits BufferedIOBase. The buffer is discarded when the close() method is called. The optional argument initial_bytes is a bytes-like object that contains initial data. BytesIO provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
getbuffer()
Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer: >>> b = io.BytesIO(b"abcdef")
>>> view = b.getbuffer()
>>> view[2:4] = b"56"
>>> b.getvalue()
b'ab56ef'
Note As long as the view exists, the BytesIO object cannot be resized or closed. New in version 3.2.
getvalue()
Return bytes containing the entire contents of the buffer.
read1([size])
In BytesIO, this is the same as read(). Changed in version 3.7: The size argument is now optional.
readinto1(b)
In BytesIO, this is the same as readinto(). New in version 3.5.
class io.BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
A buffered binary stream providing higher-level access to a readable, non seekable RawIOBase raw binary stream. It inherits BufferedIOBase. When reading data from this object, a larger amount of data may be requested from the underlying raw stream, and kept in an internal buffer. The buffered data can then be returned directly on subsequent reads. The constructor creates a BufferedReader for the given readable raw stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE is used. BufferedReader provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
peek([size])
Return bytes from the stream without advancing the position. At most one single read on the raw stream is done to satisfy the call. The number of bytes returned may be less or more than requested.
read([size])
Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.
read1([size])
Read and return up to size bytes with only one call on the raw stream. If at least one byte is buffered, only buffered bytes are returned. Otherwise, one raw stream read call is made. Changed in version 3.7: The size argument is now optional.
class io.BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
A buffered binary stream providing higher-level access to a writeable, non seekable RawIOBase raw binary stream. It inherits BufferedIOBase. When writing to this object, data is normally placed into an internal buffer. The buffer will be written out to the underlying RawIOBase object under various conditions, including: when the buffer gets too small for all pending data; when flush() is called; when a seek() is requested (for BufferedRandom objects); when the BufferedWriter object is closed or destroyed. The constructor creates a BufferedWriter for the given writeable raw stream. If the buffer_size is not given, it defaults to DEFAULT_BUFFER_SIZE. BufferedWriter provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
flush()
Force bytes held in the buffer into the raw stream. A BlockingIOError should be raised if the raw stream blocks.
write(b)
Write the bytes-like object, b, and return the number of bytes written. When in non-blocking mode, a BlockingIOError is raised if the buffer needs to be written out but the raw stream blocks.
class io.BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
A buffered binary stream providing higher-level access to a seekable RawIOBase raw binary stream. It inherits BufferedReader and BufferedWriter. The constructor creates a reader and writer for a seekable raw stream, given in the first argument. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE. BufferedRandom is capable of anything BufferedReader or BufferedWriter can do. In addition, seek() and tell() are guaranteed to be implemented.
class io.BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
A buffered binary stream providing higher-level access to two non seekable RawIOBase raw binary streams—one readable, the other writeable. It inherits BufferedIOBase. reader and writer are RawIOBase objects that are readable and writeable respectively. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE. BufferedRWPair implements all of BufferedIOBase’s methods except for detach(), which raises UnsupportedOperation. Warning BufferedRWPair does not attempt to synchronize accesses to its underlying raw streams. You should not pass it the same object as reader and writer; use BufferedRandom instead.
Text I/O
class io.TextIOBase
Base class for text streams. This class provides a character and line based interface to stream I/O. It inherits IOBase. There is no public constructor. TextIOBase provides or overrides these data attributes and methods in addition to those from IOBase:
encoding
The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.
errors
The error setting of the decoder or encoder.
newlines
A string, a tuple of strings, or None, indicating the newlines translated so far. Depending on the implementation and the initial constructor flags, this may not be available.
buffer
The underlying binary buffer (a BufferedIOBase instance) that TextIOBase deals with. This is not part of the TextIOBase API and may not exist in some implementations.
detach()
Separate the underlying binary buffer from the TextIOBase and return it. After the underlying buffer has been detached, the TextIOBase is in an unusable state. Some TextIOBase implementations, like StringIO, may not have the concept of an underlying buffer and calling this method will raise UnsupportedOperation. New in version 3.1.
read(size=-1)
Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.
readline(size=-1)
Read until newline or EOF and return a single str. If the stream is already at EOF, an empty string is returned. If size is specified, at most size characters will be read.
seek(offset, whence=SEEK_SET)
Change the stream position to the given offset. Behaviour depends on the whence parameter. The default value for whence is SEEK_SET.
SEEK_SET or 0: seek from the start of the stream (the default); offset must either be a number returned by TextIOBase.tell(), or zero. Any other offset value produces undefined behaviour.
SEEK_CUR or 1: “seek” to the current position; offset must be zero, which is a no-operation (all other values are unsupported).
SEEK_END or 2: seek to the end of the stream; offset must be zero (all other values are unsupported). Return the new absolute position as an opaque number. New in version 3.1: The SEEK_* constants.
tell()
Return the current stream position as an opaque number. The number does not usually represent a number of bytes in the underlying binary storage.
write(s)
Write the string s to the stream and return the number of characters written.
class io.TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False)
A buffered text stream providing higher-level access to a BufferedIOBase buffered binary stream. It inherits TextIOBase. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors is an optional string that specifies how encoding and decoding errors are to be handled. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data. 'backslashreplace' causes malformed data to be replaced by a backslashed escape sequence. When writing, 'xmlcharrefreplace' (replace with the appropriate XML character reference) or 'namereplace' (replace with \N{...} escape sequences) can be used. Any other error handling name that has been registered with codecs.register_error() is also valid. newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows: When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If newline is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If newline has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If line_buffering is True, flush() is implied when a call to write contains a newline character or a carriage return. If write_through is True, calls to write() are guaranteed not to be buffered: any data written on the TextIOWrapper object is immediately handled to its underlying binary buffer. Changed in version 3.3: The write_through argument has been added. Changed in version 3.3: The default encoding is now locale.getpreferredencoding(False) instead of locale.getpreferredencoding(). Don’t change temporary the locale encoding using locale.setlocale(), use the current locale encoding instead of the user preferred encoding. TextIOWrapper provides these data attributes and methods in addition to those from TextIOBase and IOBase:
line_buffering
Whether line buffering is enabled.
write_through
Whether writes are passed immediately to the underlying binary buffer. New in version 3.7.
reconfigure(*[, encoding][, errors][, newline][, line_buffering][, write_through])
Reconfigure this text stream using new settings for encoding, errors, newline, line_buffering and write_through. Parameters not specified keep current settings, except errors='strict' is used when encoding is specified but errors is not specified. It is not possible to change the encoding or newline if some data has already been read from the stream. On the other hand, changing encoding after write is possible. This method does an implicit stream flush before setting the new parameters. New in version 3.7.
class io.StringIO(initial_value='', newline='\n')
A text stream using an in-memory text buffer. It inherits TextIOBase. The text buffer is discarded when the close() method is called. The initial value of the buffer can be set by providing initial_value. If newline translation is enabled, newlines will be encoded as if by write(). The stream is positioned at the start of the buffer. The newline argument works like that of TextIOWrapper, except that when writing output to the stream, if newline is None, newlines are written as \n on all platforms. StringIO provides this method in addition to those from TextIOBase and IOBase:
getvalue()
Return a str containing the entire contents of the buffer. Newlines are decoded as if by read(), although the stream position is not changed.
Example usage: import io
output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)
# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()
# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()
class io.IncrementalNewlineDecoder
A helper codec that decodes newlines for universal newlines mode. It inherits codecs.IncrementalDecoder.
Performance This section discusses the performance of the provided concrete I/O implementations. Binary I/O By reading and writing only large chunks of data even when the user asks for a single byte, buffered I/O hides any inefficiency in calling and executing the operating system’s unbuffered I/O routines. The gain depends on the OS and the kind of I/O which is performed. For example, on some modern OSes such as Linux, unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however, is that buffered I/O offers predictable performance regardless of the platform and the backing device. Therefore, it is almost always preferable to use buffered I/O rather than unbuffered I/O for binary data. Text I/O Text I/O over a binary storage (such as a file) is significantly slower than binary I/O over the same storage, because it requires conversions between unicode and binary data using a character codec. This can become noticeable handling huge amounts of text data like large log files. Also, TextIOWrapper.tell() and TextIOWrapper.seek() are both quite slow due to the reconstruction algorithm used. StringIO, however, is a native in-memory unicode container and will exhibit similar speed to BytesIO. Multi-threading FileIO objects are thread-safe to the extent that the operating system calls (such as read(2) under Unix) they wrap are thread-safe too. Binary buffered objects (instances of BufferedReader, BufferedWriter, BufferedRandom and BufferedRWPair) protect their internal structures using a lock; it is therefore safe to call them from multiple threads at once. TextIOWrapper objects are not thread-safe. Reentrancy Binary buffered objects (instances of BufferedReader, BufferedWriter, BufferedRandom and BufferedRWPair) are not reentrant. While reentrant calls will not happen in normal situations, they can arise from doing I/O in a signal handler. If a thread tries to re-enter a buffered object which it is already accessing, a RuntimeError is raised. Note this doesn’t prohibit a different thread from entering the buffered object. The above implicitly extends to text files, since the open() function will wrap a buffered object inside a TextIOWrapper. This includes standard streams and therefore affects the built-in print() function as well. | |
doc_27576 | >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Compact encoding: >>> import json
>>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
'[1,2,3,{"4":5,"6":7}]'
Pretty printing: >>> import json
>>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
{
"4": 5,
"6": 7
}
Decoding JSON: >>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
>>> json.loads('"\\"foo\\bar"')
'"foo\x08ar'
>>> from io import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)
['streaming API']
Specializing JSON object decoding: >>> import json
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')
Extending JSONEncoder: >>> import json
>>> class ComplexEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... # Let the base class default method raise the TypeError
... return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[2.0', ', 1.0', ']']
Using json.tool from the shell to validate and pretty-print: $ echo '{"json":"obj"}' | python -m json.tool
{
"json": "obj"
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
See Command Line Interface for detailed documentation. Note JSON is a subset of YAML 1.2. The JSON produced by this module’s default settings (in particular, the default separators value) is also a subset of YAML 1.0 and 1.1. This module can thus also be used as a YAML serializer. Note This module’s encoders and decoders preserve input and output order by default. Order is only lost if the underlying containers are unordered. Prior to Python 3.7, dict was not guaranteed to be ordered, so inputs and outputs were typically scrambled unless collections.OrderedDict was specifically requested. Starting with Python 3.7, the regular dict became order preserving, so it is no longer necessary to specify collections.OrderedDict for JSON generation and parsing. Basic Usage
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table. If skipkeys is true (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError. The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input. If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is. If check_circular is false (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). If allow_nan is false (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification. If allow_nan is true, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used. If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level. Changed in version 3.2: Allow strings for indent in addition to integers. If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace. Changed in version 3.4: Use (',', ': ') as default if indent is not None. If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised. If sort_keys is true (default: False), then the output of dictionaries will be sorted by key. To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used. Changed in version 3.6: All optional parameters are now keyword-only. Note Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file.
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump(). Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table. object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority. Changed in version 3.1: Added support for object_pairs_hook. parse_float, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). parse_int, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). parse_constant, if specified, will be called with one of the following strings: '-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered. Changed in version 3.1: parse_constant doesn’t get called on ‘null’, ‘true’, ‘false’ anymore. To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used. Additional keyword arguments will be passed to the constructor of the class. If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: All optional parameters are now keyword-only. Changed in version 3.6: fp can now be a binary file. The input encoding should be UTF-8, UTF-16 or UTF-32.
json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table. The other arguments have the same meaning as in load(). If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32. Changed in version 3.9: The keyword argument encoding has been removed.
Encoders and Decoders
class json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
Simple JSON decoder. Performs the following translations in decoding by default:
JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None It also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec. object_hook, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). object_pairs_hook, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority. Changed in version 3.1: Added support for object_pairs_hook. parse_float, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). parse_int, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). parse_constant, if specified, will be called with one of the following strings: '-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered. If strict is false (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'. If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: All parameters are now keyword-only.
decode(s)
Return the Python representation of s (a str instance containing a JSON document). JSONDecodeError will be raised if the given JSON document is not valid.
raw_decode(s)
Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end.
class json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
Extensible JSON encoder for Python data structures. Supports the following objects and types by default:
Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null Changed in version 3.4: Added support for int- and float-derived Enum classes. To extend this to recognize other objects, subclass and implement a default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError). If skipkeys is false (the default), a TypeError will be raised when trying to encode keys that are not str, int, float or None. If skipkeys is true, such items are simply skipped. If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is. If check_circular is true (the default), then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is true (the default), then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true (default: False), then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level. Changed in version 3.2: Allow strings for indent in addition to integers. If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace. Changed in version 3.4: Use (',', ': ') as default if indent is not None. If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised. Changed in version 3.6: All parameters are now keyword-only.
default(o)
Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError). For example, to support arbitrary iterators, you could implement default() like this: def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, o)
encode(o)
Return a JSON string representation of a Python data structure, o. For example: >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
iterencode(o)
Encode the given object, o, and yield each string representation as available. For example: for chunk in json.JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
Exceptions
exception json.JSONDecodeError(msg, doc, pos)
Subclass of ValueError with the following additional attributes:
msg
The unformatted error message.
doc
The JSON document being parsed.
pos
The start index of doc where parsing failed.
lineno
The line corresponding to pos.
colno
The column corresponding to pos.
New in version 3.5.
Standard Compliance and Interoperability The JSON format is specified by RFC 7159 and by ECMA-404. This section details this module’s level of compliance with the RFC. For simplicity, JSONEncoder and JSONDecoder subclasses, and parameters other than those explicitly mentioned, are not considered. This module does not comply with the RFC in a strict fashion, implementing some extensions that are valid JavaScript but not valid JSON. In particular: Infinite and NaN number values are accepted and output; Repeated names within an object are accepted, and only the value of the last name-value pair is used. Since the RFC permits RFC-compliant parsers to accept input texts that are not RFC-compliant, this module’s deserializer is technically RFC-compliant under default settings. Character Encodings The RFC requires that JSON be represented using either UTF-8, UTF-16, or UTF-32, with UTF-8 being the recommended default for maximum interoperability. As permitted, though not required, by the RFC, this module’s serializer sets ensure_ascii=True by default, thus escaping the output so that the resulting strings only contain ASCII characters. Other than the ensure_ascii parameter, this module is defined strictly in terms of conversion between Python objects and Unicode strings, and thus does not otherwise directly address the issue of character encodings. The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text, and this module’s serializer does not add a BOM to its output. The RFC permits, but does not require, JSON deserializers to ignore an initial BOM in their input. This module’s deserializer raises a ValueError when an initial BOM is present. The RFC does not explicitly forbid JSON strings which contain byte sequences that don’t correspond to valid Unicode characters (e.g. unpaired UTF-16 surrogates), but it does note that they may cause interoperability problems. By default, this module accepts and outputs (when present in the original str) code points for such sequences. Infinite and NaN Number Values The RFC does not permit the representation of infinite or NaN number values. Despite that, by default, this module accepts and outputs Infinity, -Infinity, and NaN as if they were valid JSON number literal values: >>> # Neither of these calls raises an exception, but the results are not valid JSON
>>> json.dumps(float('-inf'))
'-Infinity'
>>> json.dumps(float('nan'))
'NaN'
>>> # Same when deserializing
>>> json.loads('-Infinity')
-inf
>>> json.loads('NaN')
nan
In the serializer, the allow_nan parameter can be used to alter this behavior. In the deserializer, the parse_constant parameter can be used to alter this behavior. Repeated Names Within an Object The RFC specifies that the names within a JSON object should be unique, but does not mandate how repeated names in JSON objects should be handled. By default, this module does not raise an exception; instead, it ignores all but the last name-value pair for a given name: >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> json.loads(weird_json)
{'x': 3}
The object_pairs_hook parameter can be used to alter this behavior. Top-level Non-Object, Non-Array Values The old version of JSON specified by the obsolete RFC 4627 required that the top-level value of a JSON text must be either a JSON object or array (Python dict or list), and could not be a JSON null, boolean, number, or string value. RFC 7159 removed that restriction, and this module does not and has never implemented that restriction in either its serializer or its deserializer. Regardless, for maximum interoperability, you may wish to voluntarily adhere to the restriction yourself. Implementation Limitations Some JSON deserializer implementations may set limits on: the size of accepted JSON texts the maximum level of nesting of JSON objects and arrays the range and precision of JSON numbers the content and maximum length of JSON strings This module does not impose any such limits beyond those of the relevant Python datatypes themselves or the Python interpreter itself. When serializing to JSON, beware any such limitations in applications that may consume your JSON. In particular, it is common for JSON numbers to be deserialized into IEEE 754 double precision numbers and thus subject to that representation’s range and precision limitations. This is especially relevant when serializing Python int values of extremely large magnitude, or when serializing instances of “exotic” numerical types such as decimal.Decimal. Command Line Interface Source code: Lib/json/tool.py The json.tool module provides a simple command line interface to validate and pretty-print JSON objects. If the optional infile and outfile arguments are not specified, sys.stdin and sys.stdout will be used respectively: $ echo '{"json": "obj"}' | python -m json.tool
{
"json": "obj"
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Changed in version 3.5: The output is now in the same order as the input. Use the --sort-keys option to sort the output of dictionaries alphabetically by key. Command line options
infile
The JSON file to be validated or pretty-printed: $ python -m json.tool mp_films.json
[
{
"title": "And Now for Something Completely Different",
"year": 1971
},
{
"title": "Monty Python and the Holy Grail",
"year": 1975
}
]
If infile is not specified, read from sys.stdin.
outfile
Write the output of the infile to the given outfile. Otherwise, write it to sys.stdout.
--sort-keys
Sort the output of dictionaries alphabetically by key. New in version 3.5.
--no-ensure-ascii
Disable escaping of non-ascii characters, see json.dumps() for more information. New in version 3.9.
--json-lines
Parse every input line as separate JSON object. New in version 3.8.
--indent, --tab, --no-indent, --compact
Mutually exclusive options for whitespace control. New in version 3.9.
-h, --help
Show the help message.
Footnotes
1
As noted in the errata for RFC 7159, JSON permits literal U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript (as of ECMAScript Edition 5.1) does not. | |
doc_27577 |
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array. | |
doc_27578 |
For each element in a, return a copy with the leading and trailing characters removed. Calls str.strip element-wise. Parameters
aarray-like of str or unicode
charsstr or unicode, optional
The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped. Returns
outndarray
Output array of str or unicode, depending on input type See also str.strip
Examples >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.char.strip(c)
array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7')
>>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads
array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7')
>>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails
array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7') | |
doc_27579 | tf.experimental.dlpack.to_dlpack(
tf_tensor
)
This operation ensures the underlying data memory is ready when returns. a = tf.tensor([1, 10])
dlcapsule = tf.experimental.dlpack.to_dlpack(a)
# dlcapsule represents the dlpack data structure
Args
tf_tensor Tensorflow eager tensor, to be converted to dlpack capsule.
Returns A PyCapsule named as dltensor, which shares the underlying memory to other framework. This PyCapsule can be consumed only once. | |
doc_27580 | See Migration guide for more details. tf.compat.v1.raw_ops.RaggedRange
tf.raw_ops.RaggedRange(
starts, limits, deltas, Tsplits=tf.dtypes.int64, name=None
)
Returns a RaggedTensor result composed from rt_dense_values and rt_nested_splits, such that result[i] = range(starts[i], limits[i], deltas[i]). (rt_nested_splits, rt_dense_values) = ragged_range(
starts=[2, 5, 8], limits=[3, 5, 12], deltas=1)
result = tf.ragged.from_row_splits(rt_dense_values, rt_nested_splits)
print(result)
<tf.RaggedTensor [[2], [], [8, 9, 10, 11]] >
The input tensors starts, limits, and deltas may be scalars or vectors. The vector inputs must all have the same size. Scalar inputs are broadcast to match the size of the vector inputs.
Args
starts A Tensor. Must be one of the following types: bfloat16, float32, float64, int32, int64. The starts of each range.
limits A Tensor. Must have the same type as starts. The limits of each range.
deltas A Tensor. Must have the same type as starts. The deltas of each range.
Tsplits An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int64.
name A name for the operation (optional).
Returns A tuple of Tensor objects (rt_nested_splits, rt_dense_values). rt_nested_splits A Tensor of type Tsplits.
rt_dense_values A Tensor. Has the same type as starts. | |
doc_27581 |
Fills fields from output with fields from input, with support for nested structures. Parameters
inputndarray
Input array.
outputndarray
Output array. Notes
output should be at least the same size as input
Examples >>> from numpy.lib import recfunctions as rfn
>>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', np.int64), ('B', np.float64)])
>>> b = np.zeros((3,), dtype=a.dtype)
>>> rfn.recursive_fill_fields(a, b)
array([(1, 10.), (2, 20.), (0, 0.)], dtype=[('A', '<i8'), ('B', '<f8')]) | |
doc_27582 |
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
figure Figure
gid str
in_layout bool
label str
label1 str
label2 str
pad float
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float | |
doc_27583 |
Sort an array in-place. Refer to numpy.sort for full documentation. Parameters
axisint, optional
Axis along which to sort. Default is -1, which means sort along the last axis.
kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. The ‘mergesort’ option is retained for backwards compatibility. Changed in version 1.15.0: The ‘stable’ option was added.
orderstr or list of str, optional
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. See also numpy.sort
Return a sorted copy of an array. numpy.argsort
Indirect sort. numpy.lexsort
Indirect stable sort on multiple keys. numpy.searchsorted
Find elements in sorted array. numpy.partition
Partial sort. Notes See numpy.sort for notes on the different sorting algorithms. Examples >>> a = np.array([[1,4], [3,1]])
>>> a.sort(axis=1)
>>> a
array([[1, 4],
[1, 3]])
>>> a.sort(axis=0)
>>> a
array([[1, 3],
[1, 4]])
Use the order keyword to specify a field to use when sorting a structured array: >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
>>> a.sort(order='y')
>>> a
array([(b'c', 1), (b'a', 2)],
dtype=[('x', 'S1'), ('y', '<i8')]) | |
doc_27584 |
Removes the spectral normalization reparameterization from a module. Parameters
module (Module) – containing module
name (str, optional) – name of weight parameter Example >>> m = spectral_norm(nn.Linear(40, 10))
>>> remove_spectral_norm(m) | |
doc_27585 | See Migration guide for more details. tf.compat.v1.keras.layers.LocallyConnected2D
tf.keras.layers.LocallyConnected2D(
filters, kernel_size, strides=(1, 1), padding='valid',
data_format=None, activation=None, use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros', kernel_regularizer=None,
bias_regularizer=None, activity_regularizer=None, kernel_constraint=None,
bias_constraint=None, implementation=1, **kwargs
)
The LocallyConnected2D layer works similarly to the Conv2D layer, except that weights are unshared, that is, a different set of filters is applied at each different patch of the input.
Note: layer attributes cannot be modified after the layer has been called once (except the trainable attribute).
Examples: # apply a 3x3 unshared weights convolution with 64 output filters on a
32x32 image
# with `data_format="channels_last"`:
model = Sequential()
model.add(LocallyConnected2D(64, (3, 3), input_shape=(32, 32, 3)))
# now model.output_shape == (None, 30, 30, 64)
# notice that this layer will consume (30*30)*(3*3*3*64) + (30*30)*64
parameters
# add a 3x3 unshared weights convolution on top, with 32 output filters:
model.add(LocallyConnected2D(32, (3, 3)))
# now model.output_shape == (None, 28, 28, 32)
Arguments
filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution).
kernel_size An integer or tuple/list of 2 integers, specifying the width and height of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions.
strides An integer or tuple/list of 2 integers, specifying the strides of the convolution along the width and height. Can be a single integer to specify the same value for all spatial dimensions.
padding Currently only support "valid" (case-insensitive). "same" will be supported in future. "valid" means no padding.
data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "channels_last".
activation Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x).
use_bias Boolean, whether the layer uses a bias vector.
kernel_initializer Initializer for the kernel weights matrix.
bias_initializer Initializer for the bias vector.
kernel_regularizer Regularizer function applied to the kernel weights matrix.
bias_regularizer Regularizer function applied to the bias vector.
activity_regularizer Regularizer function applied to the output of the layer (its "activation").
kernel_constraint Constraint function applied to the kernel matrix.
bias_constraint Constraint function applied to the bias vector.
implementation implementation mode, either 1, 2, or 3. 1 loops over input spatial locations to perform the forward pass. It is memory-efficient but performs a lot of (small) ops. 2 stores layer weights in a dense but sparsely-populated 2D matrix and implements the forward pass as a single matrix-multiply. It uses a lot of RAM but performs few (large) ops. 3 stores layer weights in a sparse tensor and implements the forward pass as a single sparse matrix-multiply. How to choose: 1: large, dense models, 2: small models, 3: large, sparse models, where "large" stands for large input/output activations (i.e. many filters, input_filters, large np.prod(input_size), np.prod(output_size)), and "sparse" stands for few connections between inputs and outputs, i.e. small ratio `filters * input_filters * np.prod(kernel_size) / (np.prod(input_size) np.prod(strides)), where inputs to and outputs of the layer are assumed to have shapesinput_size + (input_filters,),output_size + (filters,)` respectively. It is recommended to benchmark each in the setting of interest to pick the most efficient one (in terms of speed and memory usage). Correct choice of implementation can lead to dramatic speed improvements (e.g. 50X), potentially at the expense of RAM. Also, only padding="valid" is supported by implementation=1.
Input shape: 4D tensor with shape: (samples, channels, rows, cols) if data_format='channels_first' or 4D tensor with shape: (samples, rows, cols, channels) if data_format='channels_last'. Output shape: 4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding. | |
doc_27586 | See Migration guide for more details. tf.compat.v1.raw_ops.SparseMatrixMatMul
tf.raw_ops.SparseMatrixMatMul(
a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False,
transpose_output=False, conjugate_output=False, name=None
)
Returns a dense matrix. For inputs A and B, where A is CSR and B is dense; this op returns a dense C; If transpose_output is false, returns: C = A . B
If transpose_output is true, returns: C = transpose(A . B) = transpose(B) . transpose(A)
where the transposition is performed along the two innermost (matrix) dimensions. If conjugate_output is true, returns: C = conjugate(A . B) = conjugate(A) . conjugate(B)
If both conjugate_output and transpose_output are true, returns: C = conjugate(transpose(A . B)) = conjugate(transpose(B)) .
conjugate(transpose(A))
Args
a A Tensor of type variant. A CSRSparseMatrix.
b A Tensor. A dense tensor.
transpose_a An optional bool. Defaults to False. Indicates whether a should be transposed.
transpose_b An optional bool. Defaults to False. Indicates whether b should be transposed.
adjoint_a An optional bool. Defaults to False. Indicates whether a should be conjugate-transposed.
adjoint_b An optional bool. Defaults to False. Indicates whether b should be conjugate-transposed.
transpose_output An optional bool. Defaults to False. Transposes the product of a and b.
conjugate_output An optional bool. Defaults to False. Conjugates the product of a and b.
name A name for the operation (optional).
Returns A Tensor. Has the same type as b. | |
doc_27587 |
Compute the cross-spectral density. The cross spectral density \(P_{xy}\) by Welch's average periodogram method. The vectors x and y are divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The product of the direct FFTs of x and y are averaged over each segment to compute \(P_{xy}\), with a scaling to correct for power loss due to windowing. If len(x) < NFFT or len(y) < NFFT, they will be zero padded to NFFT. Parameters
x, y1-D arrays or sequences
Arrays or sequences containing the data
Fsfloat, default: 2
The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
windowcallable or ndarray, default: window_hanning
A function or a vector of length NFFT. To create window vectors see window_hanning, window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides{'default', 'onesided', 'twosided'}, optional
Which sides of the spectrum to return. 'default' is one-sided for real data and two-sided for complex data. 'onesided' forces the return of a one-sided spectrum, while 'twosided' forces two-sided.
pad_toint, optional
The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to NFFT
NFFTint, default: 256
The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.
detrend{'none', 'mean', 'linear'} or callable, default: 'none'
The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The mlab module defines detrend_none, detrend_mean, and detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: 'none' calls detrend_none. 'mean' calls detrend_mean. 'linear' calls detrend_linear.
scale_by_freqbool, default: True
Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of Hz^-1. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.
noverlapint, default: 0 (no overlap)
The number of points of overlap between segments. Returns
Pxy1-D array
The values for the cross spectrum \(P_{xy}\) before scaling (real valued)
freqs1-D array
The frequencies corresponding to the elements in Pxy See also psd
equivalent to setting y = x. References Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986) | |
doc_27588 |
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
figure Figure
gid str
height float
in_layout bool
label object
offset (float, float) or callable
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
width float
zorder float | |
doc_27589 | See Migration guide for more details. tf.compat.v1.Tensor
tf.Tensor(
op, value_index, dtype
)
tf.Tensor object. All elements are of a single known data type. When writing a TensorFlow program, the main object that is manipulated and passed around is the tf.Tensor. A tf.Tensor has the following properties: a single data type (float32, int32, or string, for example) a shape TensorFlow supports eager execution and graph execution. In eager execution, operations are evaluated immediately. In graph execution, a computational graph is constructed for later evaluation. TensorFlow defaults to eager execution. In the example below, the matrix multiplication results are calculated immediately.
# Compute some values using a Tensor
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)
print(e)
tf.Tensor(
[[1. 3.]
[3. 7.]], shape=(2, 2), dtype=float32)
Note that during eager execution, you may discover your Tensors are actually of type EagerTensor. This is an internal detail, but it does give you access to a useful function, numpy:
type(e)
<class '...ops.EagerTensor'>
print(e.numpy())
[[1. 3.]
[3. 7.]]
In TensorFlow, tf.functions are a common way to define graph execution. A Tensor's shape (that is, the rank of the Tensor and the size of each dimension) may not always be fully known. In tf.function definitions, the shape may only be partially known. Most operations produce tensors of fully-known shapes if the shapes of their inputs are also fully known, but in some cases it's only possible to find the shape of a tensor at execution time. A number of specialized tensors are available: see tf.Variable, tf.constant, tf.placeholder, tf.sparse.SparseTensor, and tf.RaggedTensor. For more on Tensors, see the guide.
Args
op An Operation. Operation that computes this tensor.
value_index An int. Index of the operation's endpoint that produces this tensor.
dtype A DType. Type of elements stored in this tensor.
Raises
TypeError If the op is not an Operation.
Attributes
device The name of the device on which this tensor will be produced, or None.
dtype The DType of elements in this tensor.
graph The Graph that contains this tensor.
name The string name of this tensor.
op The Operation that produces this tensor as an output.
shape Returns a tf.TensorShape that represents the shape of this tensor.
t = tf.constant([1,2,3,4,5])
t.shape
TensorShape([5])
tf.Tensor.shape is equivalent to tf.Tensor.get_shape(). In a tf.function or when building a model using tf.keras.Input, they return the build-time shape of the tensor, which may be partially unknown. A tf.TensorShape is not a tensor. Use tf.shape(t) to get a tensor containing the shape, calculated at runtime. See tf.Tensor.get_shape(), and tf.TensorShape for details and examples.
value_index The index of this tensor in the outputs of its Operation. Methods consumers View source
consumers()
Returns a list of Operations that consume this tensor.
Returns A list of Operations.
eval View source
eval(
feed_dict=None, session=None
)
Evaluates this tensor in a Session.
Note: If you are not using compat.v1 libraries, you should not need this, (or feed_dict or Session). In eager execution (or within tf.function) you do not need to call eval.
Calling this method will execute all preceding operations that produce the inputs needed for the operation that produces this tensor.
Note: Before invoking Tensor.eval(), its graph must have been launched in a session, and either a default session must be available, or session must be specified explicitly.
Args
feed_dict A dictionary that maps Tensor objects to feed values. See tf.Session.run for a description of the valid feed values.
session (Optional.) The Session to be used to evaluate this tensor. If none, the default session will be used.
Returns A numpy array corresponding to the value of this tensor.
experimental_ref View source
experimental_ref()
DEPRECATED FUNCTION Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use ref() instead. get_shape View source
get_shape()
Returns a tf.TensorShape that represents the shape of this tensor. In eager execution the shape is always fully-known.
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(a.shape)
(2, 3)
tf.Tensor.get_shape() is equivalent to tf.Tensor.shape. When executing in a tf.function or building a model using tf.keras.Input, Tensor.shape may return a partial shape (including None for unknown dimensions). See tf.TensorShape for more details.
inputs = tf.keras.Input(shape = [10])
# Unknown batch size
print(inputs.shape)
(None, 10)
The shape is computed using shape inference functions that are registered for each tf.Operation. The returned tf.TensorShape is determined at build time, without executing the underlying kernel. It is not a tf.Tensor. If you need a shape tensor, either convert the tf.TensorShape to a tf.constant, or use the tf.shape(tensor) function, which returns the tensor's shape at execution time. This is useful for debugging and providing early errors. For example, when tracing a tf.function, no ops are being executed, shapes may be unknown (See the Concrete Functions Guide for details).
@tf.function
def my_matmul(a, b):
result = a@b
# the `print` executes during tracing.
print("Result shape: ", result.shape)
return result
The shape inference functions propagate shapes to the extent possible:
f = my_matmul.get_concrete_function(
tf.TensorSpec([None,3]),
tf.TensorSpec([3,5]))
Result shape: (None, 5)
Tracing may fail if a shape missmatch can be detected:
cf = my_matmul.get_concrete_function(
tf.TensorSpec([None,3]),
tf.TensorSpec([4,5]))
Traceback (most recent call last):
ValueError: Dimensions must be equal, but are 3 and 4 for 'matmul' (op:
'MatMul') with input shapes: [?,3], [4,5].
In some cases, the inferred shape may have unknown dimensions. If the caller has additional information about the values of these dimensions, tf.ensure_shape or Tensor.set_shape() can be used to augment the inferred shape.
@tf.function
def my_fun(a):
a = tf.ensure_shape(a, [5, 5])
# the `print` executes during tracing.
print("Result shape: ", a.shape)
return a
cf = my_fun.get_concrete_function(
tf.TensorSpec([None, None]))
Result shape: (5, 5)
Returns A tf.TensorShape representing the shape of this tensor.
ref View source
ref()
Returns a hashable reference object to this Tensor. The primary use case for this API is to put tensors in a set/dictionary. We can't put tensors in a set/dictionary as tensor.__hash__() is no longer available starting Tensorflow 2.0. The following will raise an exception starting 2.0
x = tf.constant(5)
y = tf.constant(10)
z = tf.constant(10)
tensor_set = {x, y, z}
Traceback (most recent call last):
TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key.
tensor_dict = {x: 'five', y: 'ten'}
Traceback (most recent call last):
TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key.
Instead, we can use tensor.ref().
tensor_set = {x.ref(), y.ref(), z.ref()}
x.ref() in tensor_set
True
tensor_dict = {x.ref(): 'five', y.ref(): 'ten', z.ref(): 'ten'}
tensor_dict[y.ref()]
'ten'
Also, the reference object provides .deref() function that returns the original Tensor.
x = tf.constant(5)
x.ref().deref()
<tf.Tensor: shape=(), dtype=int32, numpy=5>
set_shape View source
set_shape(
shape
)
Updates the shape of this tensor.
Note: It is recommended to use tf.ensure_shape instead of Tensor.set_shape, because tf.ensure_shape provides better checking for programming errors and can create guarantees for compiler optimization.
With eager execution this operates as a shape assertion. Here the shapes match:
t = tf.constant([[1,2,3]])
t.set_shape([1, 3])
Passing a None in the new shape allows any value for that axis:
t.set_shape([1,None])
An error is raised if an incompatible shape is passed.
t.set_shape([1,5])
Traceback (most recent call last):
ValueError: Tensor's shape (1, 3) is not compatible with supplied
shape [1, 5]
When executing in a tf.function, or building a model using tf.keras.Input, Tensor.set_shape will merge the given shape with the current shape of this tensor, and set the tensor's shape to the merged value (see tf.TensorShape.merge_with for details):
t = tf.keras.Input(shape=[None, None, 3])
print(t.shape)
(None, None, None, 3)
Dimensions set to None are not updated:
t.set_shape([None, 224, 224, None])
print(t.shape)
(None, 224, 224, 3)
The main use case for this is to provide additional shape information that cannot be inferred from the graph alone. For example if you know all the images in a dataset have shape [28,28,3] you can set it with tf.set_shape:
@tf.function
def load_image(filename):
raw = tf.io.read_file(filename)
image = tf.image.decode_png(raw, channels=3)
# the `print` executes during tracing.
print("Initial shape: ", image.shape)
image.set_shape([28, 28, 3])
print("Final shape: ", image.shape)
return image
Trace the function, see the Concrete Functions Guide for details.
cf = load_image.get_concrete_function(
tf.TensorSpec([], dtype=tf.string))
Initial shape: (None, None, 3)
Final shape: (28, 28, 3)
Similarly the tf.io.parse_tensor function could return a tensor with any shape, even the tf.rank is unknown. If you know that all your serialized tensors will be 2d, set it with set_shape:
@tf.function
def my_parse(string_tensor):
result = tf.io.parse_tensor(string_tensor, out_type=tf.float32)
# the `print` executes during tracing.
print("Initial shape: ", result.shape)
result.set_shape([None, None])
print("Final shape: ", result.shape)
return result
Trace the function
concrete_parse = my_parse.get_concrete_function(
tf.TensorSpec([], dtype=tf.string))
Initial shape: <unknown>
Final shape: (None, None)
Make sure it works:
t = tf.ones([5,3], dtype=tf.float32)
serialized = tf.io.serialize_tensor(t)
print(serialized.dtype)
<dtype: 'string'>
print(serialized.shape)
()
t2 = concrete_parse(serialized)
print(t2.shape)
(5, 3)
Caution: set_shape ensures that the applied shape is compatible with the existing shape, but it does not check at runtime. Setting incorrect shapes can result in inconsistencies between the statically-known graph and the runtime value of tensors. For runtime validation of the shape, use tf.ensure_shape instead. It also modifies the shape of the tensor.
# Serialize a rank-3 tensor
t = tf.ones([5,5,5], dtype=tf.float32)
serialized = tf.io.serialize_tensor(t)
# The function still runs, even though it `set_shape([None,None])`
t2 = concrete_parse(serialized)
print(t2.shape)
(5, 5, 5)
Args
shape A TensorShape representing the shape of this tensor, a TensorShapeProto, a list, a tuple, or None.
Raises
ValueError If shape is not compatible with the current shape of this tensor. __abs__ View source
__abs__(
x, name=None
)
Computes the absolute value of a tensor. 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)
__add__ View source
__add__(
x, y
)
The operation invoked by the Tensor.add operator. Purpose in the API: This method is exposed in TensorFlow's API so that library developers
can register dispatching for <a href="../tf/Tensor#__add__"><code>Tensor.__add__</code></a> to allow it to handle
custom composite tensors & other custom objects.
The API symbol is not intended to be called by users directly and does
appear in TensorFlow's generated documentation.
Args
x The left-hand side of the + operator.
y The right-hand side of the + operator.
name an optional name for the operation.
Returns The result of the elementwise + operation.
__and__ View source
__and__(
x, y
)
__bool__ View source
__bool__()
Dummy method to prevent a tensor from being used as a Python bool. This overload raises a TypeError when the user inadvertently treats a Tensor as a boolean (most commonly in an if or while statement), in code that was not converted by AutoGraph. For example: if tf.constant(True): # Will raise.
# ...
if tf.constant(5) < tf.constant(7): # Will raise.
# ...
Raises TypeError.
__div__ View source
__div__(
x, y
)
Divides x / y elementwise (using Python 2 division operator semantics). (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Deprecated in favor of operator or tf.math.divide.
Note: Prefer using the Tensor division operator or tf.divide which obey Python 3 division operator semantics.
This function divides x and y, forcing Python 2 semantics. That is, if x and y are both integers then the result will be an integer. This is in contrast to Python 3, where division with / is always a float while division with // is always an integer.
Args
x Tensor numerator of real numeric type.
y Tensor denominator of real numeric type.
name A name for the operation (optional).
Returns x / y returns the quotient of x and y.
__eq__ View source
__eq__(
other
)
The operation invoked by the Tensor.eq operator. Compares two tensors element-wise for equality if they are broadcast-compatible; or returns False if they are not broadcast-compatible. (Note that this behavior differs from tf.math.equal, which raises an exception if the two tensors are not broadcast-compatible.) Purpose in the API: This method is exposed in TensorFlow's API so that library developers can register dispatching for Tensor.eq to allow it to handle custom composite tensors & other custom objects. The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation.
Args
self The left-hand side of the == operator.
other The right-hand side of the == operator.
Returns The result of the elementwise == operation, or False if the arguments are not broadcast-compatible.
__floordiv__ View source
__floordiv__(
x, y
)
Divides x / y elementwise, rounding toward the most negative integer. The same as tf.compat.v1.div(x,y) for integers, but uses tf.floor(tf.compat.v1.div(x,y)) for floating point arguments so that the result is always an integer (though possibly an integer represented as floating point). This op is generated by x // y floor division in Python 3 and in Python 2.7 with from __future__ import division. x and y must have the same type, and the result will have the same type as well.
Args
x Tensor numerator of real numeric type.
y Tensor denominator of real numeric type.
name A name for the operation (optional).
Returns x / y rounded down.
Raises
TypeError If the inputs are complex. __ge__
__ge__(
x, y, name=None
)
Returns the truth value of (x >= y) element-wise.
Note: math.greater_equal supports broadcasting. More about broadcasting here
Example: x = tf.constant([5, 4, 6, 7])
y = tf.constant([5, 2, 5, 10])
tf.math.greater_equal(x, y) ==> [True, True, True, False]
x = tf.constant([5, 4, 6, 7])
y = tf.constant([5])
tf.math.greater_equal(x, y) ==> [True, False, True, True]
Args
x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor of type bool.
__getitem__ View source
__getitem__(
tensor, slice_spec, var=None
)
Overload for Tensor.getitem. This operation extracts the specified region from the tensor. The notation is similar to NumPy with the restriction that currently only support basic indexing. That means that using a non-scalar tensor as input is not currently allowed. Some useful examples: # Strip leading and trailing 2 elements
foo = tf.constant([1,2,3,4,5,6])
print(foo[2:-2].eval()) # => [3,4]
# Skip every other row and reverse the order of the columns
foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])
print(foo[::2,::-1].eval()) # => [[3,2,1], [9,8,7]]
# Use scalar tensors as indices on both dimensions
print(foo[tf.constant(0), tf.constant(2)].eval()) # => 3
# Insert another dimension
foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])
print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]
print(foo[:, tf.newaxis, :].eval()) # => [[[1,2,3]], [[4,5,6]], [[7,8,9]]]
print(foo[:, :, tf.newaxis].eval()) # => [[[1],[2],[3]], [[4],[5],[6]],
[[7],[8],[9]]]
# Ellipses (3 equivalent operations)
foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])
print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]
print(foo[tf.newaxis, ...].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]
print(foo[tf.newaxis].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]
# Masks
foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])
print(foo[foo > 2].eval()) # => [3, 4, 5, 6, 7, 8, 9]
Notes:
tf.newaxis is None as in NumPy. An implicit ellipsis is placed at the end of the slice_spec
NumPy advanced indexing is currently not supported. Purpose in the API: This method is exposed in TensorFlow's API so that library developers can register dispatching for Tensor.getitem to allow it to handle custom composite tensors & other custom objects. The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation.
Args
tensor An ops.Tensor object.
slice_spec The arguments to Tensor.getitem.
var In the case of variable slice assignment, the Variable object to slice (i.e. tensor is the read-only view of this variable).
Returns The appropriate slice of "tensor", based on "slice_spec".
Raises
ValueError If a slice range is negative size.
TypeError If the slice indices aren't int, slice, ellipsis, tf.newaxis or scalar int32/int64 tensors. __gt__
__gt__(
x, y, name=None
)
Returns the truth value of (x > y) element-wise.
Note: math.greater supports broadcasting. More about broadcasting here
Example: x = tf.constant([5, 4, 6])
y = tf.constant([5, 2, 5])
tf.math.greater(x, y) ==> [False, True, True]
x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.greater(x, y) ==> [False, False, True]
Args
x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor of type bool.
__invert__ View source
__invert__(
x, name=None
)
__iter__ View source
__iter__()
__le__
__le__(
x, y, name=None
)
Returns the truth value of (x <= y) element-wise.
Note: math.less_equal supports broadcasting. More about broadcasting here
Example: x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.less_equal(x, y) ==> [True, True, False]
x = tf.constant([5, 4, 6])
y = tf.constant([5, 6, 6])
tf.math.less_equal(x, y) ==> [True, True, True]
Args
x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor of type bool.
__len__ View source
__len__()
__lt__
__lt__(
x, y, name=None
)
Returns the truth value of (x < y) element-wise.
Note: math.less supports broadcasting. More about broadcasting here
Example: x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.less(x, y) ==> [False, True, False]
x = tf.constant([5, 4, 6])
y = tf.constant([5, 6, 7])
tf.math.less(x, y) ==> [False, True, True]
Args
x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor of type bool.
__matmul__ View source
__matmul__(
x, y
)
Multiplies matrix a by matrix b, producing a * b. 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. __mod__ View source
__mod__(
x, y
)
Returns element-wise remainder of division. When x < 0 xor y < 0 is true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x.
Note: math.floormod supports broadcasting. More about broadcasting here
Args
x A Tensor. Must be one of the following types: int32, int64, uint64, bfloat16, half, float32, float64.
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.
__mul__ View source
__mul__(
x, y
)
Dispatches cwise mul for "DenseDense" and "DenseSparse". __ne__ View source
__ne__(
other
)
The operation invoked by the Tensor.ne operator. Compares two tensors element-wise for inequality if they are broadcast-compatible; or returns True if they are not broadcast-compatible. (Note that this behavior differs from tf.math.not_equal, which raises an exception if the two tensors are not broadcast-compatible.) Purpose in the API: This method is exposed in TensorFlow's API so that library developers can register dispatching for Tensor.ne to allow it to handle custom composite tensors & other custom objects. The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation.
Args
self The left-hand side of the != operator.
other The right-hand side of the != operator.
Returns The result of the elementwise != operation, or True if the arguments are not broadcast-compatible.
__neg__
__neg__(
x, name=None
)
Computes numerical negative value element-wise. I.e., \(y = -x\).
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, int8, int16, int32, int64, complex64, complex128.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x. If x is a SparseTensor, returns SparseTensor(x.indices, tf.math.negative(x.values, ...), x.dense_shape)
__nonzero__ View source
__nonzero__()
Dummy method to prevent a tensor from being used as a Python bool. This is the Python 2.x counterpart to __bool__() above.
Raises TypeError.
__or__ View source
__or__(
x, y
)
__pow__ View source
__pow__(
x, y
)
Computes the power of one value to another. Given a tensor x and a tensor y, this operation computes \(x^y\) for corresponding elements in x and y. For example: x = tf.constant([[2, 2], [3, 3]])
y = tf.constant([[8, 16], [2, 3]])
tf.pow(x, y) # [[256, 65536], [9, 27]]
Args
x A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128.
y A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128.
name A name for the operation (optional).
Returns A Tensor.
__radd__ View source
__radd__(
y, x
)
The operation invoked by the Tensor.add operator. Purpose in the API: This method is exposed in TensorFlow's API so that library developers
can register dispatching for <a href="../tf/Tensor#__add__"><code>Tensor.__add__</code></a> to allow it to handle
custom composite tensors & other custom objects.
The API symbol is not intended to be called by users directly and does
appear in TensorFlow's generated documentation.
Args
x The left-hand side of the + operator.
y The right-hand side of the + operator.
name an optional name for the operation.
Returns The result of the elementwise + operation.
__rand__ View source
__rand__(
y, x
)
__rdiv__ View source
__rdiv__(
y, x
)
Divides x / y elementwise (using Python 2 division operator semantics). (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Deprecated in favor of operator or tf.math.divide.
Note: Prefer using the Tensor division operator or tf.divide which obey Python 3 division operator semantics.
This function divides x and y, forcing Python 2 semantics. That is, if x and y are both integers then the result will be an integer. This is in contrast to Python 3, where division with / is always a float while division with // is always an integer.
Args
x Tensor numerator of real numeric type.
y Tensor denominator of real numeric type.
name A name for the operation (optional).
Returns x / y returns the quotient of x and y.
__rfloordiv__ View source
__rfloordiv__(
y, x
)
Divides x / y elementwise, rounding toward the most negative integer. The same as tf.compat.v1.div(x,y) for integers, but uses tf.floor(tf.compat.v1.div(x,y)) for floating point arguments so that the result is always an integer (though possibly an integer represented as floating point). This op is generated by x // y floor division in Python 3 and in Python 2.7 with from __future__ import division. x and y must have the same type, and the result will have the same type as well.
Args
x Tensor numerator of real numeric type.
y Tensor denominator of real numeric type.
name A name for the operation (optional).
Returns x / y rounded down.
Raises
TypeError If the inputs are complex. __rmatmul__ View source
__rmatmul__(
y, x
)
Multiplies matrix a by matrix b, producing a * b. 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. __rmod__ View source
__rmod__(
y, x
)
Returns element-wise remainder of division. When x < 0 xor y < 0 is true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x.
Note: math.floormod supports broadcasting. More about broadcasting here
Args
x A Tensor. Must be one of the following types: int32, int64, uint64, bfloat16, half, float32, float64.
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.
__rmul__ View source
__rmul__(
y, x
)
Dispatches cwise mul for "DenseDense" and "DenseSparse". __ror__ View source
__ror__(
y, x
)
__rpow__ View source
__rpow__(
y, x
)
Computes the power of one value to another. Given a tensor x and a tensor y, this operation computes \(x^y\) for corresponding elements in x and y. For example: x = tf.constant([[2, 2], [3, 3]])
y = tf.constant([[8, 16], [2, 3]])
tf.pow(x, y) # [[256, 65536], [9, 27]]
Args
x A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128.
y A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128.
name A name for the operation (optional).
Returns A Tensor.
__rsub__ View source
__rsub__(
y, x
)
Returns x - y element-wise.
Note: Subtract supports broadcasting. More about broadcasting here
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128, uint32.
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.
__rtruediv__ View source
__rtruediv__(
y, x
)
Divides x / y elementwise (using Python 3 division operator semantics).
Note: Prefer using the Tensor operator or tf.divide which obey Python division operator semantics.
This function forces Python 3 division operator semantics where all integer arguments are cast to floating types first. This op is generated by normal x / y division in Python 3 and in Python 2.7 with from __future__ import division. If you want integer division that rounds down, use x // y or tf.math.floordiv. x and y must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to float32 for int8 and int16 and float64 for int32 and int64 (matching the behavior of Numpy).
Args
x Tensor numerator of numeric type.
y Tensor denominator of numeric type.
name A name for the operation (optional).
Returns x / y evaluated in floating point.
Raises
TypeError If x and y have different dtypes. __rxor__ View source
__rxor__(
y, x
)
__sub__ View source
__sub__(
x, y
)
Returns x - y element-wise.
Note: Subtract supports broadcasting. More about broadcasting here
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128, uint32.
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.
__truediv__ View source
__truediv__(
x, y
)
Divides x / y elementwise (using Python 3 division operator semantics).
Note: Prefer using the Tensor operator or tf.divide which obey Python division operator semantics.
This function forces Python 3 division operator semantics where all integer arguments are cast to floating types first. This op is generated by normal x / y division in Python 3 and in Python 2.7 with from __future__ import division. If you want integer division that rounds down, use x // y or tf.math.floordiv. x and y must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to float32 for int8 and int16 and float64 for int32 and int64 (matching the behavior of Numpy).
Args
x Tensor numerator of numeric type.
y Tensor denominator of numeric type.
name A name for the operation (optional).
Returns x / y evaluated in floating point.
Raises
TypeError If x and y have different dtypes. __xor__ View source
__xor__(
x, y
)
Class Variables
OVERLOADABLE_OPERATORS | |
doc_27590 |
Check gradients of gradients computed via small finite differences against analytical gradients w.r.t. tensors in inputs and grad_outputs that are of floating point or complex type and with requires_grad=True. This function checks that backpropagating through the gradients computed to the given grad_outputs are correct. The check between numerical and analytical gradients uses allclose(). Note The default values are designed for input and grad_outputs of double precision. This check will likely fail if they are of less precision, e.g., FloatTensor. Warning If any checked tensor in input and grad_outputs has overlapping memory, i.e., different indices pointing to the same memory address (e.g., from torch.expand()), this check will likely fail because the numerical gradients computed by point perturbation at such indices will change values at all other indices that share the same memory address. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor or a tuple of Tensors
inputs (tuple of Tensor or Tensor) – inputs to the function
grad_outputs (tuple of Tensor or Tensor, optional) – The gradients with respect to the function’s outputs.
eps (float, optional) – perturbation for finite differences
atol (float, optional) – absolute tolerance
rtol (float, optional) – relative tolerance
gen_non_contig_grad_outputs (bool, optional) – if grad_outputs is None and gen_non_contig_grad_outputs is True, the randomly generated gradient outputs are made to be noncontiguous
raise_exception (bool, optional) – indicating whether to raise an exception if the check fails. The exception gives more information about the exact nature of the failure. This is helpful when debugging gradchecks.
nondet_tol (float, optional) – tolerance for non-determinism. When running identical inputs through the differentiation, the results must either match exactly (default, 0.0) or be within this tolerance. Note that a small amount of nondeterminism in the gradient will lead to larger inaccuracies in the second derivative.
check_undefined_grad (bool, optional) – if True, check if undefined output grads are supported and treated as zeros
check_batched_grad (bool, optional) – if True, check if we can compute batched gradients using prototype vmap support. Defaults to False. Returns
True if all differences satisfy allclose condition | |
doc_27591 |
Parameters
vlist of axes_size
sizes for vertical division | |
doc_27592 |
Fit linear model with Passive Aggressive algorithm. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Subset of the training data
ynumpy array of shape [n_samples]
Subset of the target values
classesarray, shape = [n_classes]
Classes across all calls to partial_fit. Can be obtained by via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is required for the first call to partial_fit and can be omitted in the subsequent calls. Note that y doesn’t need to contain all labels in classes. Returns
selfreturns an instance of self. | |
doc_27593 |
Learning curve. Determines cross-validated training and test scores for different training set sizes. A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterwards, the scores will be averaged over all k runs for each training subset size. Read more in the User Guide. Parameters
estimatorobject type that implements the “fit” and “predict” methods
An object of that type which is cloned for each validation.
Xarray-like of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Target relative to X for classification or regression; None for unsupervised learning.
groupsarray-like of shape (n_samples,), default=None
Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold).
train_sizesarray-like of shape (n_ticks,), default=np.linspace(0.1, 1.0, 5)
Relative or absolute numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of the maximum size of the training set (that is determined by the selected validation method), i.e. it has to be within (0, 1]. Otherwise it is interpreted as absolute sizes of the training sets. Note that for classification the number of samples usually have to be big enough to contain at least one sample from each class.
cvint, cross-validation generator or an iterable, default=None
Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross validation, int, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices. For int/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here. Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
scoringstr or callable, default=None
A str (see model evaluation documentation) or a scorer callable object / function with signature scorer(estimator, X, y).
exploit_incremental_learningbool, default=False
If the estimator supports incremental learning, this will be used to speed up fitting for different training set sizes.
n_jobsint, default=None
Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the different training and test sets. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
pre_dispatchint or str, default=’all’
Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The str can be an expression like ‘2*n_jobs’.
verboseint, default=0
Controls the verbosity: the higher, the more messages.
shufflebool, default=False
Whether to shuffle training data before taking prefixes of it based on``train_sizes``.
random_stateint, RandomState instance or None, default=None
Used when shuffle is True. Pass an int for reproducible output across multiple function calls. See Glossary.
error_score‘raise’ or numeric, default=np.nan
Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. New in version 0.20.
return_timesbool, default=False
Whether to return the fit and score times.
fit_paramsdict, default=None
Parameters to pass to the fit method of the estimator. New in version 0.24. Returns
train_sizes_absarray of shape (n_unique_ticks,)
Numbers of training examples that has been used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed.
train_scoresarray of shape (n_ticks, n_cv_folds)
Scores on training sets.
test_scoresarray of shape (n_ticks, n_cv_folds)
Scores on test set.
fit_timesarray of shape (n_ticks, n_cv_folds)
Times spent for fitting in seconds. Only present if return_times is True.
score_timesarray of shape (n_ticks, n_cv_folds)
Times spent for scoring in seconds. Only present if return_times is True. Notes See examples/model_selection/plot_learning_curve.py | |
doc_27594 | Return True if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised. | |
doc_27595 | The list of fields that should be used to validate the field’s value (in the order in which they are provided). >>> from django.forms import ComboField
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
>>> f.clean('test@example.com')
'test@example.com'
>>> f.clean('longemailaddress@example.com')
Traceback (most recent call last):
...
ValidationError: ['Ensure this value has at most 20 characters (it has 28).'] | |
doc_27596 | class collections.abc.MutableSet
ABCs for read-only and mutable sets. | |
doc_27597 |
Turn the x- and y-axis off. This affects the axis lines, ticks, ticklabels, grid and axis labels. | |
doc_27598 |
[Deprecated] Notes Deprecated since version 3.4: | |
doc_27599 |
Return a new Timestamp floored to this resolution. Parameters
freq:str
Frequency string indicating the flooring resolution.
ambiguous:bool or {‘raise’, ‘NaT’}, default ‘raise’
The behavior is as follows: bool contains flags to determine if time is dst or not (note that this flag is only applicable for ambiguous fall dst dates). ‘NaT’ will return NaT for an ambiguous time. ‘raise’ will raise an AmbiguousTimeError for an ambiguous time.
nonexistent:{‘raise’, ‘shift_forward’, ‘shift_backward, ‘NaT’, timedelta}, default ‘raise’
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST. ‘shift_forward’ will shift the nonexistent time forward to the closest existing time. ‘shift_backward’ will shift the nonexistent time backward to the closest existing time. ‘NaT’ will return NaT where there are nonexistent times. timedelta objects will shift nonexistent times by the timedelta. ‘raise’ will raise an NonExistentTimeError if there are nonexistent times. Raises
ValueError if the freq cannot be converted.
Notes If the Timestamp has a timezone, flooring will take place relative to the local (“wall”) time and re-localized to the same timezone. When flooring near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior. Examples Create a timestamp object:
>>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651')
A timestamp can be floored using multiple frequency units:
>>> ts.floor(freq='H') # hour
Timestamp('2020-03-14 15:00:00')
>>> ts.floor(freq='T') # minute
Timestamp('2020-03-14 15:32:00')
>>> ts.floor(freq='S') # seconds
Timestamp('2020-03-14 15:32:52')
>>> ts.floor(freq='N') # nanoseconds
Timestamp('2020-03-14 15:32:52.192548651')
freq can also be a multiple of a single unit, like ‘5T’ (i.e. 5 minutes):
>>> ts.floor(freq='5T')
Timestamp('2020-03-14 15:30:00')
or a combination of multiple units, like ‘1H30T’ (i.e. 1 hour and 30 minutes):
>>> ts.floor(freq='1H30T')
Timestamp('2020-03-14 15:00:00')
Analogous for pd.NaT:
>>> pd.NaT.floor()
NaT
When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized.
>>> ts_tz = pd.Timestamp("2021-10-31 03:30:00").tz_localize("Europe/Amsterdam")
>>> ts_tz.floor("2H", ambiguous=False)
Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam')
>>> ts_tz.floor("2H", ambiguous=True)
Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.