_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_29800
Set the (group) id for the artist. Parameters gidstr
doc_29801
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError.
doc_29802
Convert datetime objects to Matplotlib dates. Parameters ddatetime.datetime or numpy.datetime64 or sequences of these Returns float or sequence of floats Number of days since the epoch. See get_epoch for the epoch, which can be changed by rcParams["date.epoch"] (default: '1970-01-01T00:00:00') or set_epoch. If the epoch is "1970-01-01T00:00:00" (default) then noon Jan 1 1970 ("1970-01-01T12:00:00") returns 0.5. Notes The Gregorian calendar is assumed; this is not universal practice. For details see the module docstring.
doc_29803
Accept a connection. The socket must be bound to an address and listening for connections. The return value can be either None or a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection. When None is returned it means the connection didn’t take place, in which case the server should just ignore this event and keep listening for further incoming connections.
doc_29804
Abort signal from abort(3).
doc_29805
This class is the low-level building block of the module. It uses xml.parsers.expat for efficient, event-based parsing of XML. It can be fed XML data incrementally with the feed() method, and parsing events are translated to a push API - by invoking callbacks on the target object. If target is omitted, the standard TreeBuilder is used. If encoding 1 is given, the value overrides the encoding specified in the XML file. Changed in version 3.8: Parameters are now keyword-only. The html argument no longer supported. close() Finishes feeding data to the parser. Returns the result of calling the close() method of the target passed during construction; by default, this is the toplevel document element. feed(data) Feeds data to the parser. data is encoded data. XMLParser.feed() calls target’s start(tag, attrs_dict) method for each opening tag, its end(tag) method for each closing tag, and data is processed by method data(data). For further supported callback methods, see the TreeBuilder class. XMLParser.close() calls target’s method close(). XMLParser can be used not only for building a tree structure. This is an example of counting the maximum depth of an XML file: >>> from xml.etree.ElementTree import XMLParser >>> class MaxDepth: # The target object of the parser ... maxDepth = 0 ... depth = 0 ... def start(self, tag, attrib): # Called for each opening tag. ... self.depth += 1 ... if self.depth > self.maxDepth: ... self.maxDepth = self.depth ... def end(self, tag): # Called for each closing tag. ... self.depth -= 1 ... def data(self, data): ... pass # We do not need to do anything with data. ... def close(self): # Called when all data has been parsed. ... return self.maxDepth ... >>> target = MaxDepth() >>> parser = XMLParser(target=target) >>> exampleXml = """ ... <a> ... <b> ... </b> ... <b> ... <c> ... <d> ... </d> ... </c> ... </b> ... </a>""" >>> parser.feed(exampleXml) >>> parser.close() 4
doc_29806
tf.experimental.numpy.positive( x ) Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.positive.
doc_29807
Others have write permission.
doc_29808
determine which modifier keys are being held get_mods() -> int Returns a single integer representing a bitmask of all the modifier keys being held. Using bitwise operators you can test if specific modifier keys are pressed.
doc_29809
Decorator for skipping tests if resource is not available.
doc_29810
Fit the model from data in X. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. Returns selfobject Returns the instance itself.
doc_29811
See Migration guide for more details. tf.compat.v1.raw_ops.Erfinv tf.raw_ops.Erfinv( x, name=None ) Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64. name A name for the operation (optional). Returns A Tensor. Has the same type as x.
doc_29812
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback remove_callback
doc_29813
max_error metric calculates the maximum residual error. Read more in the User Guide. Parameters y_truearray-like of shape (n_samples,) Ground truth (correct) target values. y_predarray-like of shape (n_samples,) Estimated target values. Returns max_errorfloat A positive floating point value (the best value is 0.0). Examples >>> from sklearn.metrics import max_error >>> y_true = [3, 2, 7, 1] >>> y_pred = [4, 2, 7, 1] >>> max_error(y_true, y_pred) 1
doc_29814
DateOffset of one month end. Attributes base Returns a copy of the calling offset object with n=1 and all other attributes equal. freqstr kwds n name nanos normalize rule_code Methods __call__(*args, **kwargs) Call self as a function. rollback Roll provided date backward to next offset only if not on offset. rollforward Roll provided date forward to next offset only if not on offset. apply apply_index copy isAnchored is_anchored is_month_end is_month_start is_on_offset is_quarter_end is_quarter_start is_year_end is_year_start onOffset
doc_29815
Shifted opposite of the Local Outlier Factor of X. Bigger is better, i.e. large values correspond to inliers. Only available for novelty detection (when novelty is set to True). The shift offset allows a zero threshold for being an outlier. The argument X is supposed to contain new data: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns shifted_opposite_lof_scoresndarray of shape (n_samples,) The shifted opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal. Negative scores represent outliers, positive scores represent inliers.
doc_29816
See Migration guide for more details. tf.compat.v1.math.reduce_min tf.compat.v1.reduce_min( input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (keep_dims). They will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims instead Reduces input_tensor along the dimensions given in axis. Unless keepdims is true, the rank of the tensor is reduced by 1 for each of the entries in axis, which must be unique. If keepdims is true, the reduced dimensions are retained with length 1. If axis is None, all dimensions are reduced, and a tensor with a single element is returned. Args input_tensor The tensor to reduce. Should have real numeric type. axis The dimensions to reduce. If None (the default), reduces all dimensions. Must be in the range [-rank(input_tensor), rank(input_tensor)). keepdims If true, retains reduced dimensions with length 1. name A name for the operation (optional). reduction_indices The old (deprecated) name for axis. keep_dims Deprecated alias for keepdims. Returns The reduced tensor. Numpy Compatibility Equivalent to np.min
doc_29817
See torch.tril()
doc_29818
Alias for set_linestyle.
doc_29819
copy Sound samples into an array array(Sound) -> array Creates a new array for the sound data and copies the samples. The array will always be in the format returned from pygame.mixer.get_init().
doc_29820
See Migration guide for more details. tf.compat.v1.keras.layers.InputLayer tf.keras.layers.InputLayer( input_shape=None, batch_size=None, dtype=None, input_tensor=None, sparse=False, name=None, ragged=False, **kwargs ) It can either wrap an existing tensor (pass an input_tensor argument) or create a placeholder tensor (pass arguments input_shape, and optionally, dtype). It is generally recommend to use the functional layer API via Input, (which creates an InputLayer) without directly using InputLayer. When using InputLayer with Keras Sequential model, it can be skipped by moving the input_shape parameter to the first layer after the InputLayer. This class can create placeholders for tf.Tensors, tf.SparseTensors, and tf.RaggedTensors by choosing 'sparse=True' or 'ragged=True'. Note that 'sparse' and 'ragged' can't be configured to True at same time. Usage: # With explicit InputLayer. model = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(4,)), tf.keras.layers.Dense(8)]) model.compile(tf.optimizers.RMSprop(0.001), loss='mse') model.fit(np.zeros((10, 4)), np.ones((10, 8))) # Without InputLayer and let the first layer to have the input_shape. # Keras will add a input for the model behind the scene. model = tf.keras.Sequential([ tf.keras.layers.Dense(8, input_shape=(4,))]) model.compile(tf.optimizers.RMSprop(0.001), loss='mse') model.fit(np.zeros((10, 4)), np.ones((10, 8))) Arguments input_shape Shape tuple (not including the batch axis), or TensorShape instance (not including the batch axis). batch_size Optional input batch size (integer or None). dtype Optional datatype of the input. When not provided, the Keras default float type will be used. input_tensor Optional tensor to use as layer input. If set, the layer will use the tf.TypeSpec of this tensor rather than creating a new placeholder tensor. sparse Boolean, whether the placeholder created is meant to be sparse. Default to False. ragged Boolean, whether the placeholder created is meant to be ragged. In this case, values of 'None' in the 'shape' argument represent ragged dimensions. For more information about RaggedTensors, see this guide. Default to False. name Optional name of the layer (string).
doc_29821
Fit label encoder and return encoded labels. Parameters yarray-like of shape (n_samples,) Target values. Returns yarray-like of shape (n_samples,)
doc_29822
Instances of this class have __call__() methods identical in signature to the built-in function compile(), but with the difference that if the instance compiles program text containing a __future__ statement, the instance ‘remembers’ and compiles all subsequent program texts with the statement in force.
doc_29823
class sklearn.ensemble.HistGradientBoostingRegressor(loss='least_squares', *, learning_rate=0.1, max_iter=100, max_leaf_nodes=31, max_depth=None, min_samples_leaf=20, l2_regularization=0.0, max_bins=255, categorical_features=None, monotonic_cst=None, warm_start=False, early_stopping='auto', scoring='loss', validation_fraction=0.1, n_iter_no_change=10, tol=1e-07, verbose=0, random_state=None) [source] Histogram-based Gradient Boosting Regression Tree. This estimator is much faster than GradientBoostingRegressor for big datasets (n_samples >= 10 000). This estimator has native support for missing values (NaNs). During training, the tree grower learns at each split point whether samples with missing values should go to the left or right child, based on the potential gain. When predicting, samples with missing values are assigned to the left or right child consequently. If no missing values were encountered for a given feature during training, then samples with missing values are mapped to whichever child has the most samples. This implementation is inspired by LightGBM. Note This estimator is still experimental for now: the predictions and the API might change without any deprecation cycle. To use it, you need to explicitly import enable_hist_gradient_boosting: >>> # explicitly require this experimental feature >>> from sklearn.experimental import enable_hist_gradient_boosting # noqa >>> # now you can import normally from ensemble >>> from sklearn.ensemble import HistGradientBoostingRegressor Read more in the User Guide. New in version 0.21. Parameters loss{‘least_squares’, ‘least_absolute_deviation’, ‘poisson’}, default=’least_squares’ The loss function to use in the boosting process. Note that the “least squares” and “poisson” losses actually implement “half least squares loss” and “half poisson deviance” to simplify the computation of the gradient. Furthermore, “poisson” loss internally uses a log-link and requires y >= 0 Changed in version 0.23: Added option ‘poisson’. learning_ratefloat, default=0.1 The learning rate, also known as shrinkage. This is used as a multiplicative factor for the leaves values. Use 1 for no shrinkage. max_iterint, default=100 The maximum number of iterations of the boosting process, i.e. the maximum number of trees. max_leaf_nodesint or None, default=31 The maximum number of leaves for each tree. Must be strictly greater than 1. If None, there is no maximum limit. max_depthint or None, default=None The maximum depth of each tree. The depth of a tree is the number of edges to go from the root to the deepest leaf. Depth isn’t constrained by default. min_samples_leafint, default=20 The minimum number of samples per leaf. For small datasets with less than a few hundred samples, it is recommended to lower this value since only very shallow trees would be built. l2_regularizationfloat, default=0 The L2 regularization parameter. Use 0 for no regularization (default). max_binsint, default=255 The maximum number of bins to use for non-missing values. Before training, each feature of the input array X is binned into integer-valued bins, which allows for a much faster training stage. Features with a small number of unique values may use less than max_bins bins. In addition to the max_bins bins, one more bin is always reserved for missing values. Must be no larger than 255. monotonic_cstarray-like of int of shape (n_features), default=None Indicates the monotonic constraint to enforce on each feature. -1, 1 and 0 respectively correspond to a negative constraint, positive constraint and no constraint. Read more in the User Guide. New in version 0.23. categorical_featuresarray-like of {bool, int} of shape (n_features) or shape (n_categorical_features,), default=None. Indicates the categorical features. None : no feature will be considered categorical. boolean array-like : boolean mask indicating categorical features. integer array-like : integer indices indicating categorical features. For each categorical feature, there must be at most max_bins unique categories, and each categorical value must be in [0, max_bins -1]. Read more in the User Guide. New in version 0.24. warm_startbool, default=False When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble. For results to be valid, the estimator should be re-trained on the same data only. See the Glossary. early_stopping‘auto’ or bool, default=’auto’ If ‘auto’, early stopping is enabled if the sample size is larger than 10000. If True, early stopping is enabled, otherwise early stopping is disabled. New in version 0.23. scoringstr or callable or None, default=’loss’ Scoring parameter to use for early stopping. It can be a single string (see The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions). If None, the estimator’s default scorer is used. If scoring='loss', early stopping is checked w.r.t the loss value. Only used if early stopping is performed. validation_fractionint or float or None, default=0.1 Proportion (or absolute size) of training data to set aside as validation data for early stopping. If None, early stopping is done on the training data. Only used if early stopping is performed. n_iter_no_changeint, default=10 Used to determine when to “early stop”. The fitting process is stopped when none of the last n_iter_no_change scores are better than the n_iter_no_change - 1 -th-to-last one, up to some tolerance. Only used if early stopping is performed. tolfloat or None, default=1e-7 The absolute tolerance to use when comparing scores during early stopping. The higher the tolerance, the more likely we are to early stop: higher tolerance means that it will be harder for subsequent iterations to be considered an improvement upon the reference score. verboseint, default=0 The verbosity level. If not zero, print some information about the fitting process. random_stateint, RandomState instance or None, default=None Pseudo-random number generator to control the subsampling in the binning process, and the train/validation data split if early stopping is enabled. Pass an int for reproducible output across multiple function calls. See Glossary. Attributes do_early_stopping_bool Indicates whether early stopping is used during training. n_iter_int The number of iterations as selected by early stopping, depending on the early_stopping parameter. Otherwise it corresponds to max_iter. n_trees_per_iteration_int The number of tree that are built at each iteration. For regressors, this is always 1. train_score_ndarray, shape (n_iter_+1,) The scores at each iteration on the training data. The first entry is the score of the ensemble before the first iteration. Scores are computed according to the scoring parameter. If scoring is not ‘loss’, scores are computed on a subset of at most 10 000 samples. Empty if no early stopping. validation_score_ndarray, shape (n_iter_+1,) The scores at each iteration on the held-out validation data. The first entry is the score of the ensemble before the first iteration. Scores are computed according to the scoring parameter. Empty if no early stopping or if validation_fraction is None. is_categorical_ndarray, shape (n_features, ) or None Boolean mask for the categorical features. None if there are no categorical features. Examples >>> # To use this experimental feature, we need to explicitly ask for it: >>> from sklearn.experimental import enable_hist_gradient_boosting # noqa >>> from sklearn.ensemble import HistGradientBoostingRegressor >>> from sklearn.datasets import load_diabetes >>> X, y = load_diabetes(return_X_y=True) >>> est = HistGradientBoostingRegressor().fit(X, y) >>> est.score(X, y) 0.92... Methods fit(X, y[, sample_weight]) Fit the gradient boosting model. get_params([deep]) Get parameters for this estimator. predict(X) Predict values for X. score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction. set_params(**params) Set the parameters of this estimator. staged_predict(X) Predict regression target for each iteration fit(X, y, sample_weight=None) [source] Fit the gradient boosting model. Parameters Xarray-like of shape (n_samples, n_features) The input samples. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,) default=None Weights of training data. New in version 0.23. Returns selfobject 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 values for X. Parameters Xarray-like, shape (n_samples, n_features) The input samples. Returns yndarray, shape (n_samples,) The 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. staged_predict(X) [source] Predict regression target for each iteration This method allows monitoring (i.e. determine error on testing set) after each stage. New in version 0.24. Parameters Xarray-like of shape (n_samples, n_features) The input samples. Yields ygenerator of ndarray of shape (n_samples,) The predicted values of the input samples, for each iteration. Examples using sklearn.ensemble.HistGradientBoostingRegressor Release Highlights for scikit-learn 0.23 Release Highlights for scikit-learn 0.24 Monotonic Constraints Gradient Boosting regression Categorical Feature Support in Gradient Boosting Combine predictors using stacking Poisson regression and non-normal loss Partial Dependence and Individual Conditional Expectation Plots
doc_29824
Create a directory named path with numeric mode mode. If the directory already exists, FileExistsError is raised. On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If bits other than the last 9 (i.e. the last 3 digits of the octal representation of the mode) are set, their meaning is platform-dependent. On some platforms, they are ignored and you should call chmod() explicitly to set them. This function can also support paths relative to directory descriptors. It is also possible to create temporary directories; see the tempfile module’s tempfile.mkdtemp() function. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.3: The dir_fd argument. Changed in version 3.6: Accepts a path-like object.
doc_29825
bytearray.replace(old, new[, count]) Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. The subsequence to search for and its replacement may be any bytes-like object. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
doc_29826
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX.
doc_29827
Computes the LU factorization of a matrix or batches of matrices A. Returns a tuple containing the LU factorization and pivots of A. Pivoting is done if pivot is set to True. Note The pivots returned by the function are 1-indexed. If pivot is False, then the returned pivots is a tensor filled with zeros of the appropriate size. Note LU factorization with pivot = False is not available for CPU, and attempting to do so will throw an error. However, LU factorization with pivot = False is available for CUDA. Note This function does not check if the factorization was successful or not if get_infos is True since the status of the factorization is present in the third element of the return tuple. Note In the case of batches of square matrices with size less or equal to 32 on a CUDA device, the LU factorization is repeated for singular matrices due to the bug in the MAGMA library (see magma issue 13). Note L, U, and P can be derived using torch.lu_unpack(). Warning The LU factorization does have backward support, but only for square inputs of full rank. Parameters A (Tensor) – the tensor to factor of size (∗,m,n)(*, m, n) pivot (bool, optional) – controls whether pivoting is done. Default: True get_infos (bool, optional) – if set to True, returns an info IntTensor. Default: False out (tuple, optional) – optional output tuple. If get_infos is True, then the elements in the tuple are Tensor, IntTensor, and IntTensor. If get_infos is False, then the elements in the tuple are Tensor, IntTensor. Default: None Returns A tuple of tensors containing factorization (Tensor): the factorization of size (∗,m,n)(*, m, n) pivots (IntTensor): the pivots of size (∗,min(m,n))(*, \text{min}(m, n)) . pivots stores all the intermediate transpositions of rows. The final permutation perm could be reconstructed by applying swap(perm[i], perm[pivots[i] - 1]) for i = 0, ..., pivots.size(-1) - 1, where perm is initially the identity permutation of mm elements (essentially this is what torch.lu_unpack() is doing). infos (IntTensor, optional): if get_infos is True, this is a tensor of size (∗)(*) where non-zero values indicate whether factorization for the matrix or each minibatch has succeeded or failed Return type (Tensor, IntTensor, IntTensor (optional)) Example: >>> A = torch.randn(2, 3, 3) >>> A_LU, pivots = torch.lu(A) >>> A_LU tensor([[[ 1.3506, 2.5558, -0.0816], [ 0.1684, 1.1551, 0.1940], [ 0.1193, 0.6189, -0.5497]], [[ 0.4526, 1.2526, -0.3285], [-0.7988, 0.7175, -0.9701], [ 0.2634, -0.9255, -0.3459]]]) >>> pivots tensor([[ 3, 3, 3], [ 3, 3, 3]], dtype=torch.int32) >>> A_LU, pivots, info = torch.lu(A, get_infos=True) >>> if info.nonzero().size(0) == 0: ... print('LU factorization succeeded for all samples!') LU factorization succeeded for all samples!
doc_29828
tf.profiler.experimental.client.monitor( service_addr, duration_ms, level=1 ) The monitoring result is a light weight performance summary of your model execution. This method will block the caller thread until it receives the monitoring result. This method currently supports Cloud TPU only. Args service_addr gRPC address of profiler service e.g. grpc://10.0.0.2:8466. duration_ms Duration of monitoring in ms. level Choose a monitoring level between 1 and 2 to monitor your job. Level 2 is more verbose than level 1 and shows more metrics. Returns A string of monitoring output. Example usage: # Continuously send gRPC requests to the Cloud TPU to monitor the model # execution. for query in range(0, 100): print( tf.profiler.experimental.client.monitor('grpc://10.0.0.2:8466', 1000))
doc_29829
Parameters input (Tensor) – the input tensor. Tests if any element in input evaluates to True. Note This function matches the behaviour of NumPy in returning output of dtype bool for all supported dtypes except uint8. For uint8 the dtype of output is uint8 itself. Example: >>> a = torch.rand(1, 2).bool() >>> a tensor([[False, True]], dtype=torch.bool) >>> torch.any(a) tensor(True, dtype=torch.bool) >>> a = torch.arange(0, 3) >>> a tensor([0, 1, 2]) >>> torch.any(a) tensor(True) torch.any(input, dim, keepdim=False, *, out=None) → Tensor For each row of input in the given dimension dim, returns True if any element in the row evaluate to True and False otherwise. If keepdim is True, the output tensor is of the same size as input except in the dimension dim where it is of size 1. Otherwise, dim is squeezed (see torch.squeeze()), resulting in the output tensor having 1 fewer dimension than input. Parameters input (Tensor) – the input tensor. dim (int) – the dimension to reduce. keepdim (bool) – whether the output tensor has dim retained or not. Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4, 2) < 0 >>> a tensor([[ True, True], [False, True], [ True, True], [False, False]]) >>> torch.any(a, 1) tensor([ True, True, True, False]) >>> torch.any(a, 0) tensor([True, True])
doc_29830
Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters **kwargs:dict of {str: callable or Series} The column names are keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas doesn’t check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned. Returns DataFrame A new DataFrame with the new columns in addition to all the existing columns. Notes Assigning multiple columns within the same assign is possible. Later items in ‘**kwargs’ may refer to newly created or modified columns in ‘df’; items are computed and assigned into ‘df’ in order. Examples >>> df = pd.DataFrame({'temp_c': [17.0, 25.0]}, ... index=['Portland', 'Berkeley']) >>> df temp_c Portland 17.0 Berkeley 25.0 Where the value is a callable, evaluated on df: >>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32) temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0 Alternatively, the same behavior can be achieved by directly referencing an existing Series or sequence: >>> df.assign(temp_f=df['temp_c'] * 9 / 5 + 32) temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0 You can create multiple columns within the same assign where one of the columns depends on another one defined within the same assign: >>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32, ... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9) temp_c temp_f temp_k Portland 17.0 62.6 290.15 Berkeley 25.0 77.0 298.15
doc_29831
class ast.Sub class ast.Mult class ast.Div class ast.FloorDiv class ast.Mod class ast.Pow class ast.LShift class ast.RShift class ast.BitOr class ast.BitXor class ast.BitAnd class ast.MatMult Binary operator tokens.
doc_29832
Return whether to use fancy math formatting. See also ScalarFormatter.set_useMathText
doc_29833
returns a linear interpolation to the given vector. lerp(Vector2, float) -> Vector2 Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self and other the result is going to be. It must be a value between 0 and 1 where 0 means self and 1 means other will be returned.
doc_29834
Returns the convolution of this mask with another mask convolve(othermask) -> Mask convolve(othermask, outputmask=None, offset=(0, 0)) -> Mask Convolve this mask with the given othermask. Parameters: othermask (Mask) -- mask to convolve this mask with outputmask (Mask or NoneType) -- (optional) mask for output (default is None) offset (tuple(int, int) or list[int, int]) -- the offset of othermask from this mask, (default is (0, 0)) Returns: a Mask with the (i - offset[0], j - offset[1]) bit set, if shifting othermask (such that its bottom right corner is at (i, j)) causes it to overlap with this mask If an outputmask is specified, the output is drawn onto it and it is returned. Otherwise a mask of size (MAX(0, width + othermask's width - 1), MAX(0, height + othermask's height - 1)) is created and returned. Return type: Mask
doc_29835
Compute Harris corner measure response image. This corner detector uses information from the auto-correlation matrix A: A = [(imx**2) (imx*imy)] = [Axx Axy] [(imx*imy) (imy**2)] [Axy Ayy] Where imx and imy are first derivatives, averaged with a gaussian filter. The corner measure is then defined as: det(A) - k * trace(A)**2 or: 2 * det(A) / (trace(A) + eps) Parameters imagendarray Input image. method{‘k’, ‘eps’}, optional Method to compute the response image from the auto-correlation matrix. kfloat, optional Sensitivity factor to separate corners from edges, typically in range [0, 0.2]. Small values of k result in detection of sharp corners. epsfloat, optional Normalisation factor (Noble’s corner measure). sigmafloat, optional Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix. Returns responsendarray Harris response image. References 1 https://en.wikipedia.org/wiki/Corner_detection Examples >>> from skimage.feature import corner_harris, corner_peaks >>> square = np.zeros([10, 10]) >>> square[2:8, 2:8] = 1 >>> square.astype(int) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> corner_peaks(corner_harris(square), min_distance=1) array([[2, 2], [2, 7], [7, 2], [7, 7]])
doc_29836
from django.shortcuts import get_object_or_404 from myapps.serializers import UserSerializer from rest_framework import viewsets from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving users. """ def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(serializer.data) If we need to, we can bind this viewset into two separate views, like so: user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'}) Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. from myapp.views import UserViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = router.urls Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: class UserViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing user instances. """ serializer_class = UserSerializer queryset = User.objects.all() There are two main advantages of using a ViewSet class over using a View class. Repeated logic can be combined into a single class. In the above example, we only need to specify the queryset once, and it'll be used across multiple views. By using routers, we no longer need to deal with wiring up the URL conf ourselves. Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. ViewSet actions The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below: class UserViewSet(viewsets.ViewSet): """ Example empty viewset demonstrating the standard actions that will be handled by a router class. If you're using format suffixes, make sure to also include the `format=None` keyword argument for each action. """ def list(self, request): pass def create(self, request): pass def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass Introspecting ViewSet actions During dispatch, the following attributes are available on the ViewSet. basename - the base to use for the URL names that are created. action - the name of the current action (e.g., list, create). detail - boolean indicating if the current action is configured for a list or detail view. suffix - the display suffix for the viewset type - mirrors the detail attribute. name - the display name for the viewset. This argument is mutually exclusive to suffix. description - the display description for the individual view of a viewset. You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list action similar to this: def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.action == 'list': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdmin] return [permission() for permission in permission_classes] Marking extra actions for routing If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the detail argument to True or False. The router will configure its URL patterns accordingly. e.g., the DefaultRouter will configure detail actions to contain pk in their URL patterns. A more complete example of extra actions: from django.contrib.auth.models import User from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.response import Response from myapp.serializers import UserSerializer, PasswordSerializer class UserViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer @action(detail=True, methods=['post']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.validated_data['password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action(detail=False) def recent_users(self, request): recent_users = User.objects.all().order_by('-last_login') page = self.paginate_queryset(recent_users) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(recent_users, many=True) return Response(serializer.data) The action decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example: @action(detail=True, methods=['post', 'delete']) def unset_password(self, request, pk=None): ... The decorator allows you to override any viewset-level configuration such as permission_classes, serializer_class, filter_backends...: @action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... The two new actions will then be available at the urls ^users/{pk}/set_password/$ and ^users/{pk}/unset_password/$. Use the url_path and url_name parameters to change the URL segment and the reverse URL name of the action. To view all extra actions, call the .get_extra_actions() method. Routing additional HTTP methods for extra actions Extra actions can map additional HTTP methods to separate ViewSet methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments. @action(detail=True, methods=['put'], name='Change Password') def password(self, request, pk=None): """Update the user's password.""" ... @password.mapping.delete def delete_password(self, request, pk=None): """Delete the user's password.""" ... Reversing action URLs If you need to get the URL of an action, use the .reverse_action() method. This is a convenience wrapper for reverse(), automatically passing the view's request object and prepending the url_name with the .basename attribute. Note that the basename is provided by the router during ViewSet registration. If you are not using a router, then you must provide the basename argument to the .as_view() method. Using the example from the previous section: >>> view.reverse_action('set-password', args=['1']) 'http://localhost:8000/api/users/1/set_password' Alternatively, you can use the url_name attribute set by the @action decorator. >>> view.reverse_action(view.set_password.url_name, args=['1']) 'http://localhost:8000/api/users/1/set_password' The url_name argument for .reverse_action() should match the same argument to the @action decorator. Additionally, this method can be used to reverse the default actions, such as list and create. API Reference ViewSet The ViewSet class inherits from APIView. You can use any of the standard attributes such as permission_classes, authentication_classes in order to control the API policy on the viewset. The ViewSet class does not provide any implementations of actions. In order to use a ViewSet class you'll override the class and define the action implementations explicitly. GenericViewSet The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default. In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly. ModelViewSet The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy(). Example Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing accounts. """ queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] Note that you can use any of the standard attributes or method overrides provided by GenericAPIView. For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this: class AccountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing the accounts associated with the user. """ serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] def get_queryset(self): return self.request.user.accounts.all() Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the basename of your Model automatically, and so you will have to specify the basename kwarg as part of your router registration. Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes. ReadOnlyModelViewSet The ReadOnlyModelViewSet class also inherits from GenericAPIView. As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve(). Example As with ModelViewSet, you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ReadOnlyModelViewSet): """ A simple ViewSet for viewing accounts. """ queryset = Account.objects.all() serializer_class = AccountSerializer Again, as with ModelViewSet, you can use any of the standard attributes and method overrides available to GenericAPIView. Custom ViewSet base classes You may need to provide custom ViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way. Example To create a base viewset class that provides create, list and retrieve operations, inherit from GenericViewSet, and mixin the required actions: from rest_framework import mixins class CreateListRetrieveViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ A viewset that provides `retrieve`, `create`, and `list` actions. To use it, override the class and set the `.queryset` and `.serializer_class` attributes. """ pass By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API. viewsets.py
doc_29837
Create a spreadsheet-style pivot table as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame. Parameters values:column to aggregate, optional index:column, Grouper, array, or list of the previous If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values. columns:column, Grouper, array, or list of the previous If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values. aggfunc:function, list of functions, dict, default numpy.mean If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) If dict is passed, the key is column to aggregate and value is function or list of functions. fill_value:scalar, default None Value to replace missing values with (in the resulting pivot table, after aggregation). margins:bool, default False Add all row / columns (e.g. for subtotal / grand totals). dropna:bool, default True Do not include columns whose entries are all NaN. margins_name:str, default ‘All’ Name of the row / column that will contain the totals when margins is True. observed:bool, default False This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. Changed in version 0.25.0. sort:bool, default True Specifies if the result should be sorted. New in version 1.3.0. Returns DataFrame An Excel style pivot table. See also DataFrame.pivot Pivot without aggregation that can handle non-numeric data. DataFrame.melt Unpivot a DataFrame from wide to long format, optionally leaving identifiers set. wide_to_long Wide panel to long format. Less flexible but more user-friendly than melt. Examples >>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", ... "bar", "bar", "bar", "bar"], ... "B": ["one", "one", "one", "two", "two", ... "one", "one", "two", "two"], ... "C": ["small", "large", "large", "small", ... "small", "large", "small", "small", ... "large"], ... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7], ... "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]}) >>> df A B C D E 0 foo one small 1 2 1 foo one large 2 4 2 foo one large 2 5 3 foo two small 3 5 4 foo two small 3 6 5 bar one large 4 6 6 bar one small 5 8 7 bar two small 6 9 8 bar two large 7 9 This first example aggregates values by taking the sum. >>> table = pd.pivot_table(df, values='D', index=['A', 'B'], ... columns=['C'], aggfunc=np.sum) >>> table C large small A B bar one 4.0 5.0 two 7.0 6.0 foo one 4.0 1.0 two NaN 6.0 We can also fill missing values using the fill_value parameter. >>> table = pd.pivot_table(df, values='D', index=['A', 'B'], ... columns=['C'], aggfunc=np.sum, fill_value=0) >>> table C large small A B bar one 4 5 two 7 6 foo one 4 1 two 0 6 The next example aggregates by taking the mean across multiple columns. >>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], ... aggfunc={'D': np.mean, ... 'E': np.mean}) >>> table D E A C bar large 5.500000 7.500000 small 5.500000 8.500000 foo large 2.000000 4.500000 small 2.333333 4.333333 We can also calculate multiple types of aggregations for any given value column. >>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], ... aggfunc={'D': np.mean, ... 'E': [min, max, np.mean]}) >>> table D E mean max mean min A C bar large 5.500000 9 7.500000 6 small 5.500000 9 8.500000 8 foo large 2.000000 5 4.500000 4 small 2.333333 6 4.333333 2
doc_29838
Compare two arrays relatively to their spacing. This is a relatively robust method to compare two arrays whose amplitude is variable. Parameters x, yarray_like Input arrays. nulpint, optional The maximum number of unit in the last place for tolerance (see Notes). Default is 1. Returns None Raises AssertionError If the spacing between x and y for one or more elements is larger than nulp. See also assert_array_max_ulp Check that all items of arrays differ in at most N Units in the Last Place. spacing Return the distance between x and the nearest adjacent number. Notes An assertion is raised if the following condition is not met: abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y))) Examples >>> x = np.array([1., 1e-10, 1e-20]) >>> eps = np.finfo(x.dtype).eps >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x) >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x) Traceback (most recent call last): ... AssertionError: X and Y are not equal to 1 ULP (max is 2)
doc_29839
Check whether an array-like or dtype is of the Interval dtype. Parameters arr_or_dtype:array-like or dtype The array-like or dtype to check. Returns boolean Whether or not the array-like or dtype is of the Interval dtype. Examples >>> is_interval_dtype(object) False >>> is_interval_dtype(IntervalDtype()) True >>> is_interval_dtype([1, 2, 3]) False >>> >>> interval = pd.Interval(1, 2, closed="right") >>> is_interval_dtype(interval) False >>> is_interval_dtype(pd.IntervalIndex([interval])) True
doc_29840
The device map locations.
doc_29841
Returns a tensor filled with uninitialized data. The shape and strides of the tensor is defined by the variable argument size and stride respectively. torch.empty_strided(size, stride) is equivalent to torch.empty(size).as_strided(size, stride). Warning More than one element of the created tensor may refer to a single memory location. As a result, in-place operations (especially ones that are vectorized) may result in incorrect behavior. If you need to write to the tensors, please clone them first. Parameters size (tuple of python:ints) – the shape of the output tensor stride (tuple of python:ints) – the strides of the output tensor Keyword Arguments dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, uses a global default (see torch.set_default_tensor_type()). layout (torch.layout, optional) – the desired layout of returned Tensor. Default: torch.strided. device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types. requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False. pin_memory (bool, optional) – If set, returned tensor would be allocated in the pinned memory. Works only for CPU tensors. Default: False. Example: >>> a = torch.empty_strided((2, 3), (1, 2)) >>> a tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], [0.0000e+00, 0.0000e+00, 3.0705e-41]]) >>> a.stride() (1, 2) >>> a.size() torch.Size([2, 3])
doc_29842
Ordered list of field names, or None if there are no fields. The names are ordered according to increasing byte offset. This can be used, for example, to walk through all of the named fields in offset order. Examples >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt.names ('name', 'grades')
doc_29843
For each element in self, return a copy of the string with all occurrences of substring old replaced by new. See also char.replace
doc_29844
Encode the object as an enumerated type or categorical variable. This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. factorize is available as both a top-level function pandas.factorize(), and as a method Series.factorize() and Index.factorize(). Parameters values:sequence A 1-D sequence. Sequences that aren’t pandas objects are coerced to ndarrays before factorization. sort:bool, default False Sort uniques and shuffle codes to maintain the relationship. na_sentinel:int or None, default -1 Value to mark “not found”. If None, will not drop the NaN from the uniques of the values. Changed in version 1.1.2. size_hint:int, optional Hint to the hashtable sizer. Returns codes:ndarray An integer ndarray that’s an indexer into uniques. uniques.take(codes) will have the same values as values. uniques:ndarray, Index, or Categorical The unique valid values. When values is Categorical, uniques is a Categorical. When values is some other pandas object, an Index is returned. Otherwise, a 1-D ndarray is returned. Note Even if there’s a missing value in values, uniques will not contain an entry for it. See also cut Discretize continuous-valued array. unique Find the unique value in an array. Examples These examples all show factorize as a top-level method like pd.factorize(values). The results are identical for methods like Series.factorize(). >>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b']) >>> codes array([0, 0, 1, 2, 0]...) >>> uniques array(['b', 'a', 'c'], dtype=object) With sort=True, the uniques will be sorted, and codes will be shuffled so that the relationship is the maintained. >>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'], sort=True) >>> codes array([1, 1, 0, 2, 1]...) >>> uniques array(['a', 'b', 'c'], dtype=object) Missing values are indicated in codes with na_sentinel (-1 by default). Note that missing values are never included in uniques. >>> codes, uniques = pd.factorize(['b', None, 'a', 'c', 'b']) >>> codes array([ 0, -1, 1, 2, 0]...) >>> uniques array(['b', 'a', 'c'], dtype=object) Thus far, we’ve only factorized lists (which are internally coerced to NumPy arrays). When factorizing pandas objects, the type of uniques will differ. For Categoricals, a Categorical is returned. >>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]...) >>> uniques ['a', 'c'] Categories (3, object): ['a', 'b', 'c'] Notice that 'b' is in uniques.categories, despite not being present in cat.values. For all other pandas objects, an Index of the appropriate type is returned. >>> cat = pd.Series(['a', 'a', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]...) >>> uniques Index(['a', 'c'], dtype='object') If NaN is in the values, and we want to include NaN in the uniques of the values, it can be achieved by setting na_sentinel=None. >>> values = np.array([1, 2, 1, np.nan]) >>> codes, uniques = pd.factorize(values) # default: na_sentinel=-1 >>> codes array([ 0, 1, 0, -1]) >>> uniques array([1., 2.]) >>> codes, uniques = pd.factorize(values, na_sentinel=None) >>> codes array([0, 1, 0, 2]) >>> uniques array([ 1., 2., nan])
doc_29845
AutoLocator MaxNLocator with simple defaults. This is the default tick locator for most plotting. MaxNLocator Finds up to a max number of intervals with ticks at nice locations. LinearLocator Space ticks evenly from min to max. LogLocator Space ticks logarithmically from min to max. MultipleLocator Ticks and range are a multiple of base; either integer or float. FixedLocator Tick locations are fixed. IndexLocator Locator for index plots (e.g., where x = range(len(y))). NullLocator No ticks. SymmetricalLogLocator Locator for use with with the symlog norm; works like LogLocator for the part outside of the threshold and adds 0 if inside the limits. LogitLocator Locator for logit scaling. AutoMinorLocator Locator for minor ticks when the axis is linear and the major ticks are uniformly spaced. Subdivides the major tick interval into a specified number of minor intervals, defaulting to 4 or 5 depending on the major interval. There are a number of locators specialized for date locations - see the dates module. You can define your own locator by deriving from Locator. You must override the __call__ method, which returns a sequence of locations, and you will probably want to override the autoscale method to set the view limits from the data limits. If you want to override the default locator, use one of the above or a custom locator and pass it to the x or y axis instance. The relevant methods are: ax.xaxis.set_major_locator(xmajor_locator) ax.xaxis.set_minor_locator(xminor_locator) ax.yaxis.set_major_locator(ymajor_locator) ax.yaxis.set_minor_locator(yminor_locator) The default minor locator is NullLocator, i.e., no minor ticks on by default. Note Locator instances should not be used with more than one Axis or Axes. So instead of: locator = MultipleLocator(5) ax.xaxis.set_major_locator(locator) ax2.xaxis.set_major_locator(locator) do the following instead: ax.xaxis.set_major_locator(MultipleLocator(5)) ax2.xaxis.set_major_locator(MultipleLocator(5)) Tick formatting Tick formatting is controlled by classes derived from Formatter. The formatter operates on a single tick value and returns a string to the axis. NullFormatter No labels on the ticks. FixedFormatter Set the strings manually for the labels. FuncFormatter User defined function sets the labels. StrMethodFormatter Use string format method. FormatStrFormatter Use an old-style sprintf format string. ScalarFormatter Default formatter for scalars: autopick the format string. LogFormatter Formatter for log axes. LogFormatterExponent Format values for log axis using exponent = log_base(value). LogFormatterMathtext Format values for log axis using exponent = log_base(value) using Math text. LogFormatterSciNotation Format values for log axis using scientific notation. LogitFormatter Probability formatter. EngFormatter Format labels in engineering notation. PercentFormatter Format labels as a percentage. You can derive your own formatter from the Formatter base class by simply overriding the __call__ method. The formatter class has access to the axis view and data limits. To control the major and minor tick label formats, use one of the following methods: ax.xaxis.set_major_formatter(xmajor_formatter) ax.xaxis.set_minor_formatter(xminor_formatter) ax.yaxis.set_major_formatter(ymajor_formatter) ax.yaxis.set_minor_formatter(yminor_formatter) In addition to a Formatter instance, set_major_formatter and set_minor_formatter also accept a str or function. str input will be internally replaced with an autogenerated StrMethodFormatter with the input str. For function input, a FuncFormatter with the input function will be generated and used. See Major and minor ticks for an example of setting major and minor ticks. See the matplotlib.dates module for more information and examples of using date locators and formatters. classmatplotlib.ticker.AutoLocator[source] Bases: matplotlib.ticker.MaxNLocator Dynamically find major tick positions. This is actually a subclass of MaxNLocator, with parameters nbins = 'auto' and steps = [1, 2, 2.5, 5, 10]. To know the values of the non-public parameters, please have a look to the defaults of MaxNLocator. classmatplotlib.ticker.AutoMinorLocator(n=None)[source] Bases: matplotlib.ticker.Locator Dynamically find minor tick positions based on the positions of major ticks. The scale must be linear with major ticks evenly spaced. n is the number of subdivisions of the interval between major ticks; e.g., n=2 will place a single minor tick midway between major ticks. If n is omitted or None, it will be set to 5 or 4. tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] classmatplotlib.ticker.EngFormatter(unit='', places=None, sep=' ', *, usetex=None, useMathText=None)[source] Bases: matplotlib.ticker.Formatter Format axis values using engineering prefixes to represent powers of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7. Parameters unitstr, default: "" Unit symbol to use, suitable for use with single-letter representations of powers of 1000. For example, 'Hz' or 'm'. placesint, default: None Precision with which to display the number, specified in digits after the decimal point (there will be between one and three digits before the decimal point). If it is None, the formatting falls back to the floating point format '%g', which displays up to 6 significant digits, i.e. the equivalent value for places varies between 0 and 5 (inclusive). sepstr, default: " " Separator used between the value and the prefix/unit. For example, one get '3.14 mV' if sep is " " (default) and '3.14mV' if sep is "". Besides the default behavior, some other useful options may be: sep="" to append directly the prefix/unit to the value; sep="\N{THIN SPACE}" (U+2009); sep="\N{NARROW NO-BREAK SPACE}" (U+202F); sep="\N{NO-BREAK SPACE}" (U+00A0). usetexbool, default: rcParams["text.usetex"] (default: False) To enable/disable the use of TeX's math mode for rendering the numbers in the formatter. useMathTextbool, default: rcParams["axes.formatter.use_mathtext"] (default: False) To enable/disable the use mathtext for rendering the numbers in the formatter. ENG_PREFIXES={-24: 'y', -21: 'z', -18: 'a', -15: 'f', -12: 'p', -9: 'n', -6: 'µ', -3: 'm', 0: '', 3: 'k', 6: 'M', 9: 'G', 12: 'T', 15: 'P', 18: 'E', 21: 'Z', 24: 'Y'} format_eng(num)[source] Format a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples: >>> format_eng(0) # for self.places = 0 '0' >>> format_eng(1000000) # for self.places = 1 '1.0 M' >>> format_eng("-1e-6") # for self.places = 2 '-1.00 µ' get_useMathText()[source] get_usetex()[source] set_useMathText(val)[source] set_usetex(val)[source] propertyuseMathText propertyusetex classmatplotlib.ticker.FixedFormatter(seq)[source] Bases: matplotlib.ticker.Formatter Return fixed strings for tick labels based only on position, not value. Note FixedFormatter should only be used together with FixedLocator. Otherwise, the labels may end up in unexpected positions. Set the sequence seq of strings that will be used for labels. get_offset()[source] set_offset_string(ofs)[source] classmatplotlib.ticker.FixedLocator(locs, nbins=None)[source] Bases: matplotlib.ticker.Locator Tick locations are fixed. If nbins is not None, the array of possible positions will be subsampled to keep the number of ticks <= nbins +1. The subsampling will be done so as to include the smallest absolute value; for example, if zero is included in the array of possibilities, then it is guaranteed to be one of the chosen ticks. set_params(nbins=None)[source] Set parameters within this locator. tick_values(vmin, vmax)[source] Return the locations of the ticks. Note Because the values are fixed, vmin and vmax are not used in this method. classmatplotlib.ticker.FormatStrFormatter(fmt)[source] Bases: matplotlib.ticker.Formatter Use an old-style ('%' operator) format string to format the tick. The format string should have a single variable format (%) in it. It will be applied to the value (not the position) of the tick. Negative numeric values will use a dash not a unicode minus, use mathtext to get a unicode minus by wrappping the format specifier with $ (e.g. "$%g$"). classmatplotlib.ticker.Formatter[source] Bases: matplotlib.ticker.TickHelper Create a string based on a tick value and location. staticfix_minus(s)[source] Some classes may want to replace a hyphen for minus with the proper unicode symbol (U+2212) for typographical correctness. This is a helper method to perform such a replacement when it is enabled via rcParams["axes.unicode_minus"] (default: True). format_data(value)[source] Return the full string representation of the value with the position unspecified. format_data_short(value)[source] Return a short string version of the tick value. Defaults to the position-independent long value. format_ticks(values)[source] Return the tick labels for all the ticks at once. get_offset()[source] locs=[] set_locs(locs)[source] Set the locations of the ticks. This method is called before computing the tick labels because some formatters need to know all tick locations to do so. classmatplotlib.ticker.FuncFormatter(func)[source] Bases: matplotlib.ticker.Formatter Use a user-defined function for formatting. The function should take in two inputs (a tick value x and a position pos), and return a string containing the corresponding tick label. get_offset()[source] set_offset_string(ofs)[source] classmatplotlib.ticker.IndexLocator(base, offset)[source] Bases: matplotlib.ticker.Locator Place a tick on every multiple of some base number of points plotted, e.g., on every 5th point. It is assumed that you are doing index plotting; i.e., the axis is 0, len(data). This is mainly useful for x ticks. Place ticks every base data point, starting at offset. set_params(base=None, offset=None)[source] Set parameters within this locator tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] classmatplotlib.ticker.LinearLocator(numticks=None, presets=None)[source] Bases: matplotlib.ticker.Locator Determine the tick locations The first time this function is called it will try to set the number of ticks to make a nice tick partitioning. Thereafter the number of ticks will be fixed so that interactive navigation will be nice Use presets to set locs based on lom. A dict mapping vmin, vmax->locs propertynumticks set_params(numticks=None, presets=None)[source] Set parameters within this locator. tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] view_limits(vmin, vmax)[source] Try to choose the view limits intelligently. classmatplotlib.ticker.Locator[source] Bases: matplotlib.ticker.TickHelper Determine the tick locations; Note that the same locator should not be used across multiple Axis because the locator stores references to the Axis data and view limits. MAXTICKS=1000 nonsingular(v0, v1)[source] Adjust a range as needed to avoid singularities. This method gets called during autoscaling, with (v0, v1) set to the data limits on the axes if the axes contains any data, or (-inf, +inf) if not. If v0 == v1 (possibly up to some floating point slop), this method returns an expanded interval around this value. If (v0, v1) == (-inf, +inf), this method returns appropriate default view limits. Otherwise, (v0, v1) is returned without modification. raise_if_exceeds(locs)[source] Log at WARNING level if locs is longer than Locator.MAXTICKS. This is intended to be called immediately before returning locs from __call__ to inform users in case their Locator returns a huge number of ticks, causing Matplotlib to run out of memory. The "strange" name of this method dates back to when it would raise an exception instead of emitting a log. set_params(**kwargs)[source] Do nothing, and raise a warning. Any locator class not supporting the set_params() function will call this. tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] view_limits(vmin, vmax)[source] Select a scale for the range from vmin to vmax. Subclasses should override this method to change locator behaviour. classmatplotlib.ticker.LogFormatter(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)[source] Bases: matplotlib.ticker.Formatter Base class for formatting ticks on a log or symlog scale. It may be instantiated directly, or subclassed. Parameters basefloat, default: 10. Base of the logarithm used in all calculations. labelOnlyBasebool, default: False If True, label ticks only at integer powers of base. This is normally True for major ticks and False for minor ticks. minor_thresholds(subset, all), default: (1, 0.4) If labelOnlyBase is False, these two numbers control the labeling of ticks that are not at integer powers of base; normally these are the minor ticks. The controlling parameter is the log of the axis data range. In the typical case where base is 10 it is the number of decades spanned by the axis, so we can call it 'numdec'. If numdec <= all, all minor ticks will be labeled. If all < numdec <= subset, then only a subset of minor ticks will be labeled, so as to avoid crowding. If numdec > subset then no minor ticks will be labeled. linthreshNone or float, default: None If a symmetric log scale is in use, its linthresh parameter must be supplied here. Notes The set_locs method must be called to enable the subsetting logic controlled by the minor_thresholds parameter. In some cases such as the colorbar, there is no distinction between major and minor ticks; the tick locations might be set manually, or by a locator that puts ticks at integer powers of base and at intermediate locations. For this situation, disable the minor_thresholds logic by using minor_thresholds=(np.inf, np.inf), so that all ticks will be labeled. To disable labeling of minor ticks when 'labelOnlyBase' is False, use minor_thresholds=(0, 0). This is the default for the "classic" style. Examples To label a subset of minor ticks when the view limits span up to 2 decades, and all of the ticks when zoomed in to 0.5 decades or less, use minor_thresholds=(2, 0.5). To label all minor ticks when the view limits span up to 1.5 decades, use minor_thresholds=(1.5, 1.5). base(base)[source] Change the base for labeling. Warning Should always match the base used for LogLocator format_data(value)[source] Return the full string representation of the value with the position unspecified. format_data_short(value)[source] Return a short string version of the tick value. Defaults to the position-independent long value. label_minor(labelOnlyBase)[source] Switch minor tick labeling on or off. Parameters labelOnlyBasebool If True, label ticks only at integer powers of base. set_locs(locs=None)[source] Use axis view limits to control which ticks are labeled. The locs parameter is ignored in the present algorithm. classmatplotlib.ticker.LogFormatterExponent(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)[source] Bases: matplotlib.ticker.LogFormatter Format values for log axis using exponent = log_base(value). classmatplotlib.ticker.LogFormatterMathtext(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)[source] Bases: matplotlib.ticker.LogFormatter Format values for log axis using exponent = log_base(value). classmatplotlib.ticker.LogFormatterSciNotation(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)[source] Bases: matplotlib.ticker.LogFormatterMathtext Format values following scientific notation in a logarithmic axis. classmatplotlib.ticker.LogLocator(base=10.0, subs=(1.0,), numdecs=4, numticks=None)[source] Bases: matplotlib.ticker.Locator Determine the tick locations for log axes Place ticks on the locations : subs[j] * base**i Parameters basefloat, default: 10.0 The base of the log used, so ticks are placed at base**n. subsNone or str or sequence of float, default: (1.0,) Gives the multiples of integer powers of the base at which to place ticks. The default places ticks only at integer powers of the base. The permitted string values are 'auto' and 'all', both of which use an algorithm based on the axis view limits to determine whether and how to put ticks between integer powers of the base. With 'auto', ticks are placed only between integer powers; with 'all', the integer powers are included. A value of None is equivalent to 'auto'. numticksNone or int, default: None The maximum number of ticks to allow on a given axis. The default of None will try to choose intelligently as long as this Locator has already been assigned to an axis using get_tick_space, but otherwise falls back to 9. base(base)[source] Set the log base (major tick every base**i, i integer). nonsingular(vmin, vmax)[source] Adjust a range as needed to avoid singularities. This method gets called during autoscaling, with (v0, v1) set to the data limits on the axes if the axes contains any data, or (-inf, +inf) if not. If v0 == v1 (possibly up to some floating point slop), this method returns an expanded interval around this value. If (v0, v1) == (-inf, +inf), this method returns appropriate default view limits. Otherwise, (v0, v1) is returned without modification. set_params(base=None, subs=None, numdecs=None, numticks=None)[source] Set parameters within this locator. subs(subs)[source] Set the minor ticks for the log scaling every base**i*subs[j]. tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] view_limits(vmin, vmax)[source] Try to choose the view limits intelligently. classmatplotlib.ticker.LogitFormatter(*, use_overline=False, one_half='\x0crac{1}{2}', minor=False, minor_threshold=25, minor_number=6)[source] Bases: matplotlib.ticker.Formatter Probability formatter (using Math text). Parameters use_overlinebool, default: False If x > 1/2, with x = 1-v, indicate if x should be displayed as $overline{v}$. The default is to display $1-v$. one_halfstr, default: r"frac{1}{2}" The string used to represent 1/2. minorbool, default: False Indicate if the formatter is formatting minor ticks or not. Basically minor ticks are not labelled, except when only few ticks are provided, ticks with most space with neighbor ticks are labelled. See other parameters to change the default behavior. minor_thresholdint, default: 25 Maximum number of locs for labelling some minor ticks. This parameter have no effect if minor is False. minor_numberint, default: 6 Number of ticks which are labelled when the number of ticks is below the threshold. format_data_short(value)[source] Return a short string version of the tick value. Defaults to the position-independent long value. set_locs(locs)[source] Set the locations of the ticks. This method is called before computing the tick labels because some formatters need to know all tick locations to do so. set_minor_number(minor_number)[source] Set the number of minor ticks to label when some minor ticks are labelled. Parameters minor_numberint Number of ticks which are labelled when the number of ticks is below the threshold. set_minor_threshold(minor_threshold)[source] Set the threshold for labelling minors ticks. Parameters minor_thresholdint Maximum number of locations for labelling some minor ticks. This parameter have no effect if minor is False. set_one_half(one_half)[source] Set the way one half is displayed. one_halfstr, default: r"frac{1}{2}" The string used to represent 1/2. use_overline(use_overline)[source] Switch display mode with overline for labelling p>1/2. Parameters use_overlinebool, default: False If x > 1/2, with x = 1-v, indicate if x should be displayed as $overline{v}$. The default is to display $1-v$. classmatplotlib.ticker.LogitLocator(minor=False, *, nbins='auto')[source] Bases: matplotlib.ticker.MaxNLocator Determine the tick locations for logit axes Place ticks on the logit locations Parameters nbinsint or 'auto', optional Number of ticks. Only used if minor is False. minorbool, default: False Indicate if this locator is for minor ticks or not. propertyminor nonsingular(vmin, vmax)[source] Adjust a range as needed to avoid singularities. This method gets called during autoscaling, with (v0, v1) set to the data limits on the axes if the axes contains any data, or (-inf, +inf) if not. If v0 == v1 (possibly up to some floating point slop), this method returns an expanded interval around this value. If (v0, v1) == (-inf, +inf), this method returns appropriate default view limits. Otherwise, (v0, v1) is returned without modification. set_params(minor=None, **kwargs)[source] Set parameters within this locator. tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] classmatplotlib.ticker.MaxNLocator(nbins=None, **kwargs)[source] Bases: matplotlib.ticker.Locator Find nice tick locations with no more than N being within the view limits. Locations beyond the limits are added to support autoscaling. Parameters nbinsint or 'auto', default: 10 Maximum number of intervals; one less than max number of ticks. If the string 'auto', the number of bins will be automatically determined based on the length of the axis. stepsarray-like, optional Sequence of nice numbers starting with 1 and ending with 10; e.g., [1, 2, 4, 5, 10], where the values are acceptable tick multiples. i.e. for the example, 20, 40, 60 would be an acceptable set of ticks, as would 0.4, 0.6, 0.8, because they are multiples of 2. However, 30, 60, 90 would not be allowed because 3 does not appear in the list of steps. integerbool, default: False If True, ticks will take only integer values, provided at least min_n_ticks integers are found within the view limits. symmetricbool, default: False If True, autoscaling will result in a range symmetric about zero. prune{'lower', 'upper', 'both', None}, default: None Remove edge ticks -- useful for stacked or ganged plots where the upper tick of one axes overlaps with the lower tick of the axes above it, primarily when rcParams["axes.autolimit_mode"] (default: 'data') is 'round_numbers'. If prune=='lower', the smallest tick will be removed. If prune == 'upper', the largest tick will be removed. If prune == 'both', the largest and smallest ticks will be removed. If prune is None, no ticks will be removed. min_n_ticksint, default: 2 Relax nbins and integer constraints if necessary to obtain this minimum number of ticks. default_params={'integer': False, 'min_n_ticks': 2, 'nbins': 10, 'prune': None, 'steps': None, 'symmetric': False} set_params(**kwargs)[source] Set parameters for this locator. Parameters nbinsint or 'auto', optional see MaxNLocator stepsarray-like, optional see MaxNLocator integerbool, optional see MaxNLocator symmetricbool, optional see MaxNLocator prune{'lower', 'upper', 'both', None}, optional see MaxNLocator min_n_ticksint, optional see MaxNLocator tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] view_limits(dmin, dmax)[source] Select a scale for the range from vmin to vmax. Subclasses should override this method to change locator behaviour. classmatplotlib.ticker.MultipleLocator(base=1.0)[source] Bases: matplotlib.ticker.Locator Set a tick on each integer multiple of a base within the view interval. set_params(base)[source] Set parameters within this locator. tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] view_limits(dmin, dmax)[source] Set the view limits to the nearest multiples of base that contain the data. classmatplotlib.ticker.NullFormatter[source] Bases: matplotlib.ticker.Formatter Always return the empty string. classmatplotlib.ticker.NullLocator[source] Bases: matplotlib.ticker.Locator No ticks tick_values(vmin, vmax)[source] Return the locations of the ticks. Note Because the values are Null, vmin and vmax are not used in this method. classmatplotlib.ticker.PercentFormatter(xmax=100, decimals=None, symbol='%', is_latex=False)[source] Bases: matplotlib.ticker.Formatter Format numbers as a percentage. Parameters xmaxfloat Determines how the number is converted into a percentage. xmax is the data value that corresponds to 100%. Percentages are computed as x / xmax * 100. So if the data is already scaled to be percentages, xmax will be 100. Another common situation is where xmax is 1.0. decimalsNone or int The number of decimal places to place after the point. If None (the default), the number will be computed automatically. symbolstr or None A string that will be appended to the label. It may be None or empty to indicate that no symbol should be used. LaTeX special characters are escaped in symbol whenever latex mode is enabled, unless is_latex is True. is_latexbool If False, reserved LaTeX characters in symbol will be escaped. convert_to_pct(x)[source] format_pct(x, display_range)[source] Format the number as a percentage number with the correct number of decimals and adds the percent symbol, if any. If self.decimals is None, the number of digits after the decimal point is set based on the display_range of the axis as follows: display_range decimals sample >50 0 x = 34.5 => 35% >5 1 x = 34.5 => 34.5% >0.5 2 x = 34.5 => 34.50% ... ... ... This method will not be very good for tiny axis ranges or extremely large ones. It assumes that the values on the chart are percentages displayed on a reasonable scale. propertysymbol The configured percent symbol as a string. If LaTeX is enabled via rcParams["text.usetex"] (default: False), the special characters {'#', '$', '%', '&', '~', '_', '^', '\', '{', '}'} are automatically escaped in the string. classmatplotlib.ticker.ScalarFormatter(useOffset=None, useMathText=None, useLocale=None)[source] Bases: matplotlib.ticker.Formatter Format tick values as a number. Parameters useOffsetbool or float, default: rcParams["axes.formatter.useoffset"] (default: True) Whether to use offset notation. See set_useOffset. useMathTextbool, default: rcParams["axes.formatter.use_mathtext"] (default: False) Whether to use fancy math formatting. See set_useMathText. useLocalebool, default: rcParams["axes.formatter.use_locale"] (default: False). Whether to use locale settings for decimal sign and positive sign. See set_useLocale. Notes In addition to the parameters above, the formatting of scientific vs. floating point representation can be configured via set_scientific and set_powerlimits). Offset notation and scientific notation Offset notation and scientific notation look quite similar at first sight. Both split some information from the formatted tick values and display it at the end of the axis. The scientific notation splits up the order of magnitude, i.e. a multiplicative scaling factor, e.g. 1e6. The offset notation separates an additive constant, e.g. +1e6. The offset notation label is always prefixed with a + or - sign and is thus distinguishable from the order of magnitude label. The following plot with x limits 1_000_000 to 1_000_010 illustrates the different formatting. Note the labels at the right edge of the x axis. (Source code, png, pdf) format_data(value)[source] Return the full string representation of the value with the position unspecified. format_data_short(value)[source] Return a short string version of the tick value. Defaults to the position-independent long value. get_offset()[source] Return scientific notation, plus offset. get_useLocale()[source] Return whether locale settings are used for formatting. See also ScalarFormatter.set_useLocale get_useMathText()[source] Return whether to use fancy math formatting. See also ScalarFormatter.set_useMathText get_useOffset()[source] Return whether automatic mode for offset notation is active. This returns True if set_useOffset(True); it returns False if an explicit offset was set, e.g. set_useOffset(1000). See also ScalarFormatter.set_useOffset set_locs(locs)[source] Set the locations of the ticks. This method is called before computing the tick labels because some formatters need to know all tick locations to do so. set_powerlimits(lims)[source] Set size thresholds for scientific notation. Parameters lims(int, int) A tuple (min_exp, max_exp) containing the powers of 10 that determine the switchover threshold. For a number representable as \(a \times 10^\mathrm{exp}\) with \(1 <= |a| < 10\), scientific notation will be used if exp <= min_exp or exp >= max_exp. The default limits are controlled by rcParams["axes.formatter.limits"] (default: [-5, 6]). In particular numbers with exp equal to the thresholds are written in scientific notation. Typically, min_exp will be negative and max_exp will be positive. For example, formatter.set_powerlimits((-3, 4)) will provide the following formatting: \(1 \times 10^{-3}, 9.9 \times 10^{-3}, 0.01,\) \(9999, 1 \times 10^4\). See also ScalarFormatter.set_scientific set_scientific(b)[source] Turn scientific notation on or off. See also ScalarFormatter.set_powerlimits set_useLocale(val)[source] Set whether to use locale settings for decimal sign and positive sign. Parameters valbool or None None resets to rcParams["axes.formatter.use_locale"] (default: False). set_useMathText(val)[source] Set whether to use fancy math formatting. If active, scientific notation is formatted as \(1.2 \times 10^3\). Parameters valbool or None None resets to rcParams["axes.formatter.use_mathtext"] (default: False). set_useOffset(val)[source] Set whether to use offset notation. When formatting a set numbers whose value is large compared to their range, the formatter can separate an additive constant. This can shorten the formatted numbers so that they are less likely to overlap when drawn on an axis. Parameters valbool or float If False, do not use offset notation. If True (=automatic mode), use offset notation if it can make the residual numbers significantly shorter. The exact behavior is controlled by rcParams["axes.formatter.offset_threshold"] (default: 4). If a number, force an offset of the given value. Examples With active offset notation, the values 100_000, 100_002, 100_004, 100_006, 100_008 will be formatted as 0, 2, 4, 6, 8 plus an offset +1e5, which is written to the edge of the axis. propertyuseLocale Return whether locale settings are used for formatting. See also ScalarFormatter.set_useLocale propertyuseMathText Return whether to use fancy math formatting. See also ScalarFormatter.set_useMathText propertyuseOffset Return whether automatic mode for offset notation is active. This returns True if set_useOffset(True); it returns False if an explicit offset was set, e.g. set_useOffset(1000). See also ScalarFormatter.set_useOffset classmatplotlib.ticker.StrMethodFormatter(fmt)[source] Bases: matplotlib.ticker.Formatter Use a new-style format string (as used by str.format) to format the tick. The field used for the tick value must be labeled x and the field used for the tick position must be labeled pos. classmatplotlib.ticker.SymmetricalLogLocator(transform=None, subs=None, linthresh=None, base=None)[source] Bases: matplotlib.ticker.Locator Determine the tick locations for symmetric log axes. Parameters transformSymmetricalLogTransform, optional If set, defines the base and linthresh of the symlog transform. base, linthreshfloat, optional The base and linthresh of the symlog transform, as documented for SymmetricalLogScale. These parameters are only used if transform is not set. subssequence of float, default: [1] The multiples of integer powers of the base where ticks are placed, i.e., ticks are placed at [sub * base**i for i in ... for sub in subs]. Notes Either transform, or both base and linthresh, must be given. set_params(subs=None, numticks=None)[source] Set parameters within this locator. tick_values(vmin, vmax)[source] Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4] view_limits(vmin, vmax)[source] Try to choose the view limits intelligently. classmatplotlib.ticker.TickHelper[source] Bases: object axis=None create_dummy_axis(**kwargs)[source] set_axis(axis)[source] set_bounds(vmin, vmax)[source] [Deprecated] Notes Deprecated since version 3.5: set_data_interval(vmin, vmax)[source] [Deprecated] Notes Deprecated since version 3.5: set_view_interval(vmin, vmax)[source] [Deprecated] Notes Deprecated since version 3.5:
doc_29846
The Control widget is also known as the SpinBox widget. The user can adjust the value by pressing the two arrow buttons or by entering the value directly into the entry. The new value will be checked against the user-defined upper and lower limits.
doc_29847
Fits this SelfTrainingClassifier to a dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Array representing the data. y{array-like, sparse matrix} of shape (n_samples,) Array representing the labels. Unlabeled samples should have the label -1. Returns selfobject Returns an instance of self.
doc_29848
Outputs the record to the file, catering for rollover as described previously.
doc_29849
Return the alternate marker face color. See also set_markerfacecoloralt.
doc_29850
See Migration guide for more details. tf.compat.v1.raw_ops.ResourceSparseApplyAdadelta tf.raw_ops.ResourceSparseApplyAdadelta( var, accum, accum_update, lr, rho, epsilon, grad, indices, use_locking=False, name=None ) Args var A Tensor of type resource. accum A Tensor of type resource. Should be from a Variable(). accum_update A Tensor of type resource. Should be from a Variable(). lr A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. Learning rate. Must be a scalar. rho A Tensor. Must have the same type as lr. Decay factor. Must be a scalar. epsilon A Tensor. Must have the same type as lr. Constant factor. Must be a scalar. grad A Tensor. Must have the same type as lr. The gradient. indices A Tensor. Must be one of the following types: int32, int64. A vector of indices into the first dimension of var and accum. use_locking An optional bool. Defaults to False. If True, updating of the var and accum tensors will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. name A name for the operation (optional). Returns The created Operation.
doc_29851
Returns the quality of the key. Changelog New in version 0.6: In previous versions you had to use the item-lookup syntax (eg: obj[key] instead of obj.quality(key))
doc_29852
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_29853
Get the radix character (decimal dot, decimal comma, etc.).
doc_29854
Return True if pathname path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path’s parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants. It is not able to reliably detect bind mounts on the same filesystem. On Windows, a drive letter root and a share UNC are always mount points, and for any other path GetVolumePathName is called to see if it is different from the input path. New in version 3.4: Support for detecting non-root mount points on Windows. Changed in version 3.6: Accepts a path-like object.
doc_29855
Alias for set_linestyle.
doc_29856
Query or modify the heading options for the specified column. If kw is not given, returns a dict of the heading option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values. The valid options/values are: text: text The text to display in the column heading. image: imageName Specifies an image to display to the right of the column heading. anchor: anchor Specifies how the heading text should be aligned. One of the standard Tk anchor values. command: callback A callback to be invoked when the heading label is pressed. To configure the tree column heading, call this with column = “#0”.
doc_29857
See Migration guide for more details. tf.compat.v1.raw_ops.StringJoin tf.raw_ops.StringJoin( inputs, separator='', name=None ) with the given separator (default is an empty separator). Examples: s = ["hello", "world", "tensorflow"] tf.strings.join(s, " ") <tf.Tensor: shape=(), dtype=string, numpy=b'hello world tensorflow'> Args inputs A list of at least 1 Tensor objects with type string. A list of string tensors. The tensors must all have the same shape, or be scalars. Scalars may be mixed in; these will be broadcast to the shape of non-scalar inputs. separator An optional string. Defaults to "". string, an optional join separator. name A name for the operation (optional). Returns A Tensor of type string.
doc_29858
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.
doc_29859
Return self@value.
doc_29860
Test whether the artist contains the mouse event. Parameters mouseeventmatplotlib.backend_bases.MouseEvent Returns containsbool Whether any values are within the radius. detailsdict An artist-specific dictionary of details of the event context, such as which points are contained in the pick radius. See the individual Artist subclasses for details.
doc_29861
Add a horizontal line across the axis. Parameters yfloat, default: 0 y position in data coordinates of the horizontal line. xminfloat, default: 0 Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot. xmaxfloat, default: 1 Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot. Returns Line2D Other Parameters **kwargs Valid keyword arguments are Line2D properties, with the exception of 'transform': 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 antialiased or aa bool clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None color or c color dash_capstyle CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle JoinStyle or {'miter', 'round', 'bevel'} dashes sequence of floats (on/off ink in points) or (None, None) data (2, N) array or two 1D arrays drawstyle or ds {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure Figure fillstyle {'full', 'left', 'right', 'bottom', 'top', 'none'} gid str in_layout bool label object linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw float marker marker style string, Path or MarkerStyle markeredgecolor or mec color markeredgewidth or mew float markerfacecolor or mfc color markerfacecoloralt or mfcalt color markersize or ms float markevery None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects AbstractPathEffect picker float or callable[[Artist, Event], tuple[bool, dict]] pickradius float rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None solid_capstyle CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle JoinStyle or {'miter', 'round', 'bevel'} transform unknown url str visible bool xdata 1D array ydata 1D array zorder float See also hlines Add horizontal lines in data coordinates. axhspan Add a horizontal span (rectangle) across the axis. axline Add a line with an arbitrary slope. Examples draw a thick red hline at 'y' = 0 that spans the xrange: >>> axhline(linewidth=4, color='r') draw a default hline at 'y' = 1 that spans the xrange: >>> axhline(y=1) draw a default hline at 'y' = .5 that spans the middle half of the xrange: >>> axhline(y=.5, xmin=0.25, xmax=0.75) Examples using matplotlib.pyplot.axhline Infinite lines Zorder Demo
doc_29862
Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.
doc_29863
URL linking to a comment from the server explaining the function of this cookie, or None.
doc_29864
Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel’s hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns thetandarray of shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel
doc_29865
Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace. Previous calls to add_argument() determine exactly what objects are created and how they are assigned. See the documentation for add_argument() for details. args - List of strings to parse. The default is taken from sys.argv. namespace - An object to take the attributes. The default is a new empty Namespace object.
doc_29866
Appends a given parameter at the end of the list. Parameters parameter (nn.Parameter) – parameter to append
doc_29867
Make a horizontal bar plot. The bars are positioned at y with the given alignment. Their dimensions are given by width and height. The horizontal baseline is left (default 0). Many parameters can take either a single value applying to all bars or a sequence of values, one for each bar. Parameters yfloat or array-like The y coordinates of the bars. See also align for the alignment of the bars to the coordinates. widthfloat or array-like The width(s) of the bars. heightfloat or array-like, default: 0.8 The heights of the bars. leftfloat or array-like, default: 0 The x coordinates of the left sides of the bars. align{'center', 'edge'}, default: 'center' Alignment of the base to the y coordinates*: 'center': Center the bars on the y positions. 'edge': Align the bottom edges of the bars with the y positions. To align the bars on the top edge pass a negative height and align='edge'. Returns BarContainer Container with all the bars and optionally errorbars. Other Parameters colorcolor or list of color, optional The colors of the bar faces. edgecolorcolor or list of color, optional The colors of the bar edges. linewidthfloat or array-like, optional Width of the bar edge(s). If 0, don't draw edges. tick_labelstr or list of str, optional The tick labels of the bars. Default: None (Use default numeric labels.) xerr, yerrfloat or array-like of shape(N,) or shape(2, N), optional If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data: scalar: symmetric +/- values for all bars shape(N,): symmetric +/- values for each bar shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors. None: No errorbar. (default) See Different ways of specifying error bars for an example on the usage of xerr and yerr. ecolorcolor or list of color, default: 'black' The line color of the errorbars. capsizefloat, default: rcParams["errorbar.capsize"] (default: 0.0) The length of the error bar caps in points. error_kwdict, optional Dictionary of kwargs to be passed to the errorbar method. Values of ecolor or capsize defined here take precedence over the independent kwargs. logbool, default: False If True, set the x-axis to be log scale. **kwargsRectangle properties 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 angle unknown animated bool antialiased or aa bool or None bounds (left, bottom, width, height) capstyle CapStyle or {'butt', 'projecting', 'round'} clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None color color edgecolor or ec color or None facecolor or fc color or None figure Figure fill bool gid str hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} height unknown in_layout bool joinstyle JoinStyle or {'miter', 'round', 'bevel'} label object linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw float or None 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 unknown x unknown xy (float, float) y unknown zorder float See also bar Plot a vertical bar plot. Notes Stacked bars can be achieved by passing individual left values per bar. See Discrete distribution as horizontal bar chart .
doc_29868
Return True if the object is a coroutine created by an async def function. New in version 3.5.
doc_29869
See Migration guide for more details. tf.compat.v1.raw_ops.SparseToSparseSetOperation tf.raw_ops.SparseToSparseSetOperation( set1_indices, set1_values, set1_shape, set2_indices, set2_values, set2_shape, set_operation, validate_indices=True, name=None ) See SetOperationOp::SetOperationFromContext for values of set_operation. If validate_indices is True, SparseToSparseSetOperation validates the order and range of set1 and set2 indices. Input set1 is a SparseTensor represented by set1_indices, set1_values, and set1_shape. For set1 ranked n, 1st n-1 dimensions must be the same as set2. Dimension n contains values in a set, duplicates are allowed but ignored. Input set2 is a SparseTensor represented by set2_indices, set2_values, and set2_shape. For set2 ranked n, 1st n-1 dimensions must be the same as set1. Dimension n contains values in a set, duplicates are allowed but ignored. If validate_indices is True, this op validates the order and range of set1 and set2 indices. Output result is a SparseTensor represented by result_indices, result_values, and result_shape. For set1 and set2 ranked n, this has rank n and the same 1st n-1 dimensions as set1 and set2. The nth dimension contains the result of set_operation applied to the corresponding [0...n-1] dimension of set. Args set1_indices A Tensor of type int64. 2D Tensor, indices of a SparseTensor. Must be in row-major order. set1_values A Tensor. Must be one of the following types: int8, int16, int32, int64, uint8, uint16, string. 1D Tensor, values of a SparseTensor. Must be in row-major order. set1_shape A Tensor of type int64. 1D Tensor, shape of a SparseTensor. set1_shape[0...n-1] must be the same as set2_shape[0...n-1], set1_shape[n] is the max set size across 0...n-1 dimensions. set2_indices A Tensor of type int64. 2D Tensor, indices of a SparseTensor. Must be in row-major order. set2_values A Tensor. Must have the same type as set1_values. 1D Tensor, values of a SparseTensor. Must be in row-major order. set2_shape A Tensor of type int64. 1D Tensor, shape of a SparseTensor. set2_shape[0...n-1] must be the same as set1_shape[0...n-1], set2_shape[n] is the max set size across 0...n-1 dimensions. set_operation A string. validate_indices An optional bool. Defaults to True. name A name for the operation (optional). Returns A tuple of Tensor objects (result_indices, result_values, result_shape). result_indices A Tensor of type int64. result_values A Tensor. Has the same type as set1_values. result_shape A Tensor of type int64.
doc_29870
Perform Affinity Propagation Clustering of data. Read more in the User Guide. Parameters dampingfloat, default=0.5 Damping factor (between 0.5 and 1) is the extent to which the current value is maintained relative to incoming values (weighted 1 - damping). This in order to avoid numerical oscillations when updating these values (messages). max_iterint, default=200 Maximum number of iterations. convergence_iterint, default=15 Number of iterations with no change in the number of estimated clusters that stops the convergence. copybool, default=True Make a copy of input data. preferencearray-like of shape (n_samples,) or float, default=None Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities. affinity{‘euclidean’, ‘precomputed’}, default=’euclidean’ Which affinity to use. At the moment ‘precomputed’ and euclidean are supported. ‘euclidean’ uses the negative squared euclidean distance between points. verbosebool, default=False Whether to be verbose. random_stateint, RandomState instance or None, default=0 Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the Glossary. New in version 0.23: this parameter was previously hardcoded as 0. Attributes cluster_centers_indices_ndarray of shape (n_clusters,) Indices of cluster centers. cluster_centers_ndarray of shape (n_clusters, n_features) Cluster centers (if affinity != precomputed). labels_ndarray of shape (n_samples,) Labels of each point. affinity_matrix_ndarray of shape (n_samples, n_samples) Stores the affinity matrix used in fit. n_iter_int Number of iterations taken to converge. Notes For an example, see examples/cluster/plot_affinity_propagation.py. The algorithmic complexity of affinity propagation is quadratic in the number of points. When fit does not converge, cluster_centers_ becomes an empty array and all training samples will be labelled as -1. In addition, predict will then label every sample as -1. When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, fit will result in a single cluster center and label 0 for every sample. Otherwise, every training sample becomes its own cluster center and is assigned a unique label. References Brendan J. Frey and Delbert Dueck, “Clustering by Passing Messages Between Data Points”, Science Feb. 2007 Examples >>> from sklearn.cluster import AffinityPropagation >>> import numpy as np >>> X = np.array([[1, 2], [1, 4], [1, 0], ... [4, 2], [4, 4], [4, 0]]) >>> clustering = AffinityPropagation(random_state=5).fit(X) >>> clustering AffinityPropagation(random_state=5) >>> clustering.labels_ array([0, 0, 0, 1, 1, 1]) >>> clustering.predict([[0, 0], [4, 4]]) array([0, 1]) >>> clustering.cluster_centers_ array([[1, 2], [4, 2]]) Methods fit(X[, y]) Fit the clustering from features, or affinity matrix. fit_predict(X[, y]) Fit the clustering from features or affinity matrix, and return cluster labels. get_params([deep]) Get parameters for this estimator. predict(X) Predict the closest cluster each sample in X belongs to. set_params(**params) Set the parameters of this estimator. fit(X, y=None) [source] Fit the 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 feature matrix is provided, 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] Fit the 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 feature matrix is provided, 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. predict(X) [source] Predict the closest cluster each sample in X belongs to. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) New data to predict. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns labelsndarray of shape (n_samples,) Cluster labels. 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.
doc_29871
Initialize self. See help(type(self)) for accurate signature.
doc_29872
See Migration guide for more details. tf.compat.v1.image.resize_image_with_crop_or_pad, tf.compat.v1.image.resize_with_crop_or_pad tf.image.resize_with_crop_or_pad( image, target_height, target_width ) Resizes an image to a target width and height by either centrally cropping the image or padding it evenly with zeros. If width or height is greater than the specified target_width or target_height respectively, this op centrally crops along that dimension. If width or height is smaller than the specified target_width or target_height respectively, this op centrally pads with 0 along that dimension. Args image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels]. target_height Target height. target_width Target width. Raises ValueError if target_height or target_width are zero or negative. Returns Cropped and/or padded image. If images was 4-D, a 4-D float Tensor of shape [batch, new_height, new_width, channels]. If images was 3-D, a 3-D float Tensor of shape [new_height, new_width, channels].
doc_29873
Returns the character decomposition mapping assigned to the character chr as string. An empty string is returned in case no such mapping is defined.
doc_29874
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for "\n".join(wrap(text, ...)) In particular, fill() accepts exactly the same keyword arguments as wrap().
doc_29875
See Migration guide for more details. tf.compat.v1.sysconfig.get_compile_flags tf.sysconfig.get_compile_flags() Returns The compilation flags.
doc_29876
See Migration guide for more details. tf.compat.v1.estimator.TrainSpec tf.estimator.TrainSpec( input_fn, max_steps=None, hooks=None, saving_listeners=None ) TrainSpec determines the input data for the training, as well as the duration. Optional hooks run at various stages of training. Usage: train_spec = tf.estimator.TrainSpec( input_fn=lambda: 1, max_steps=100, hooks=[_StopAtSecsHook(stop_after_secs=10)], saving_listeners=[_NewCheckpointListenerForEvaluate(None, 20, None)]) train_spec.saving_listeners[0]._eval_throttle_secs 20 train_spec.hooks[0]._stop_after_secs 10 train_spec.max_steps 100 Args input_fn A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following: A 'tf.data.Dataset' object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. max_steps Int. Positive number of total steps for which to train model. If None, train forever. The training input_fn is not expected to generate OutOfRangeError or StopIteration exceptions. See the train_and_evaluate stop condition section for details. hooks Iterable of tf.train.SessionRunHook objects to run on all workers (including chief) during training. saving_listeners Iterable of tf.estimator.CheckpointSaverListener objects to run on chief during training. Raises ValueError If any of the input arguments is invalid. TypeError If any of the arguments is not of the expected type. Attributes input_fn max_steps hooks saving_listeners
doc_29877
Set padding of X data limits prior to autoscaling. m times the data interval will be added to each end of that interval before it is used in autoscaling. For example, if your data is in the range [0, 2], a factor of m = 0.1 will result in a range [-0.2, 2.2]. Negative values -0.5 < m < 0 will result in clipping of the data range. I.e. for a data range [0, 2], a factor of m = -0.1 will result in a range [0.2, 1.8]. Parameters mfloat greater than -0.5
doc_29878
self != 0
doc_29879
Setup for writing the movie file. Parameters figFigure The figure object that contains the information for frames. outfilestr The filename of the resulting movie file. dpifloat, default: fig.dpi The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file.
doc_29880
The header to issue if the help output has a section for undocumented commands (that is, there are do_*() methods without corresponding help_*() methods).
doc_29881
Return a list of the child Artists of this Artist.
doc_29882
Compute the per-sample average log-likelihood of the given data X. Parameters Xarray-like of shape (n_samples, n_dimensions) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns log_likelihoodfloat Log likelihood of the Gaussian mixture given X.
doc_29883
See set_ylim.
doc_29884
See Migration guide for more details. tf.compat.v1.raw_ops.Digamma tf.raw_ops.Digamma( x, name=None ) Gamma(x)), element-wise. Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64. name A name for the operation (optional). Returns A Tensor. Has the same type as x.
doc_29885
Observer module for computing the quantization parameters based on the running per channel min and max values. This observer uses the tensor min/max statistics to compute the per channel quantization parameters. The module records the running minimum and maximum of incoming tensors, and uses this statistic to compute the quantization parameters. Parameters ch_axis – Channel axis dtype – Quantized data type qscheme – Quantization scheme to be used reduce_range – Reduces the range of the quantized data type by 1 bit quant_min – Minimum quantization value. If unspecified, it will follow the 8-bit setup. quant_max – Maximum quantization value. If unspecified, it will follow the 8-bit setup. The quantization parameters are computed the same way as in MinMaxObserver, with the difference that the running min/max values are stored per channel. Scales and zero points are thus computed per channel as well. Note If the running minimum equals to the running maximum, the scales and zero_points are set to 1.0 and 0.
doc_29886
See Migration guide for more details. tf.compat.v1.raw_ops.IsBoostedTreesEnsembleInitialized tf.raw_ops.IsBoostedTreesEnsembleInitialized( tree_ensemble_handle, name=None ) Args tree_ensemble_handle A Tensor of type resource. Handle to the tree ensemble resource. name A name for the operation (optional). Returns A Tensor of type bool.
doc_29887
Complex number type composed of two extended-precision floating-point numbers. Character code 'G' Alias numpy.clongfloat Alias numpy.longcomplex Alias on this platform (Linux x86_64) numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.
doc_29888
The input stream for the uploaded file. This usually points to an open temporary file.
doc_29889
A function call. func is the function, which will often be a Name or Attribute object. Of the arguments: args holds a list of the arguments passed by position. keywords holds a list of keyword objects representing arguments passed by keyword. When creating a Call node, args and keywords are required, but they can be empty lists. starargs and kwargs are optional. >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4)) Expression( body=Call( func=Name(id='func', ctx=Load()), args=[ Name(id='a', ctx=Load()), Starred( value=Name(id='d', ctx=Load()), ctx=Load())], keywords=[ keyword( arg='b', value=Name(id='c', ctx=Load())), keyword( value=Name(id='e', ctx=Load()))]))
doc_29890
Allows the handler to completely override the parsing of the raw HTTP input. input_data is a file-like object that supports read()-ing. META is the same object as request.META. content_length is the length of the data in input_data. Don’t read more than content_length bytes from input_data. boundary is the MIME boundary for this request. encoding is the encoding of the request. Return None if you want upload handling to continue, or a tuple of (POST, FILES) if you want to return the new data structures suitable for the request directly.
doc_29891
tf.compat.v1.data.experimental.SqlDataset( driver_name, data_source_name, query, output_types ) Args driver_name A 0-D tf.string tensor containing the database type. Currently, the only supported value is 'sqlite'. data_source_name A 0-D tf.string tensor containing a connection string to connect to the database. query A 0-D tf.string tensor containing the SQL query to execute. output_types A tuple of tf.DType objects representing the types of the columns returned by query. Attributes element_spec The type specification of an element of this dataset. dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) dataset.element_spec TensorSpec(shape=(), dtype=tf.int32, name=None) output_classes Returns the class of each component of an element of this dataset. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.compat.v1.data.get_output_classes(dataset). output_shapes Returns the shape of each component of an element of this dataset. (deprecated)Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.compat.v1.data.get_output_shapes(dataset). output_types Returns the type of each component of an element of this dataset. (deprecated)Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.compat.v1.data.get_output_types(dataset). Methods apply View source apply( transformation_func ) Applies a transformation function to this dataset. apply enables chaining of custom Dataset transformations, which are represented as functions that take one Dataset argument and return a transformed Dataset. dataset = tf.data.Dataset.range(100) def dataset_fn(ds): return ds.filter(lambda x: x < 5) dataset = dataset.apply(dataset_fn) list(dataset.as_numpy_iterator()) [0, 1, 2, 3, 4] Args transformation_func A function that takes one Dataset argument and returns a Dataset. Returns Dataset The Dataset returned by applying transformation_func to this dataset. as_numpy_iterator View source as_numpy_iterator() Returns an iterator which converts all elements of the dataset to numpy. Use as_numpy_iterator to inspect the content of your dataset. To see element shapes and types, print dataset elements directly instead of using as_numpy_iterator. dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) for element in dataset: print(element) tf.Tensor(1, shape=(), dtype=int32) tf.Tensor(2, shape=(), dtype=int32) tf.Tensor(3, shape=(), dtype=int32) This method requires that you are running in eager mode and the dataset's element_spec contains only TensorSpec components. dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) for element in dataset.as_numpy_iterator(): print(element) 1 2 3 dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) print(list(dataset.as_numpy_iterator())) [1, 2, 3] as_numpy_iterator() will preserve the nested structure of dataset elements. dataset = tf.data.Dataset.from_tensor_slices({'a': ([1, 2], [3, 4]), 'b': [5, 6]}) list(dataset.as_numpy_iterator()) == [{'a': (1, 3), 'b': 5}, {'a': (2, 4), 'b': 6}] True Returns An iterable over the elements of the dataset, with their tensors converted to numpy arrays. Raises TypeError if an element contains a non-Tensor value. RuntimeError if eager execution is not enabled. batch View source batch( batch_size, drop_remainder=False ) Combines consecutive elements of this dataset into batches. dataset = tf.data.Dataset.range(8) dataset = dataset.batch(3) list(dataset.as_numpy_iterator()) [array([0, 1, 2]), array([3, 4, 5]), array([6, 7])] dataset = tf.data.Dataset.range(8) dataset = dataset.batch(3, drop_remainder=True) list(dataset.as_numpy_iterator()) [array([0, 1, 2]), array([3, 4, 5])] The components of the resulting element will have an additional outer dimension, which will be batch_size (or N % batch_size for the last element if batch_size does not divide the number of input elements N evenly and drop_remainder is False). If your program depends on the batches having the same outer dimension, you should set the drop_remainder argument to True to prevent the smaller batch from being produced. Args batch_size A tf.int64 scalar tf.Tensor, representing the number of consecutive elements of this dataset to combine in a single batch. drop_remainder (Optional.) A tf.bool scalar tf.Tensor, representing whether the last batch should be dropped in the case it has fewer than batch_size elements; the default behavior is not to drop the smaller batch. Returns Dataset A Dataset. cache View source cache( filename='' ) Caches the elements in this dataset. The first time the dataset is iterated over, its elements will be cached either in the specified file or in memory. Subsequent iterations will use the cached data. Note: For the cache to be finalized, the input dataset must be iterated through in its entirety. Otherwise, subsequent iterations will not use cached data. dataset = tf.data.Dataset.range(5) dataset = dataset.map(lambda x: x**2) dataset = dataset.cache() # The first time reading through the data will generate the data using # `range` and `map`. list(dataset.as_numpy_iterator()) [0, 1, 4, 9, 16] # Subsequent iterations read from the cache. list(dataset.as_numpy_iterator()) [0, 1, 4, 9, 16] When caching to a file, the cached data will persist across runs. Even the first iteration through the data will read from the cache file. Changing the input pipeline before the call to .cache() will have no effect until the cache file is removed or the filename is changed. dataset = tf.data.Dataset.range(5) dataset = dataset.cache("/path/to/file") # doctest: +SKIP list(dataset.as_numpy_iterator()) # doctest: +SKIP [0, 1, 2, 3, 4] dataset = tf.data.Dataset.range(10) dataset = dataset.cache("/path/to/file") # Same file! # doctest: +SKIP list(dataset.as_numpy_iterator()) # doctest: +SKIP [0, 1, 2, 3, 4] Note: cache will produce exactly the same elements during each iteration through the dataset. If you wish to randomize the iteration order, make sure to call shuffle after calling cache. Args filename A tf.string scalar tf.Tensor, representing the name of a directory on the filesystem to use for caching elements in this Dataset. If a filename is not provided, the dataset will be cached in memory. Returns Dataset A Dataset. cardinality View source cardinality() Returns the cardinality of the dataset, if known. cardinality may return tf.data.INFINITE_CARDINALITY if the dataset contains an infinite number of elements or tf.data.UNKNOWN_CARDINALITY if the analysis fails to determine the number of elements in the dataset (e.g. when the dataset source is a file). dataset = tf.data.Dataset.range(42) print(dataset.cardinality().numpy()) 42 dataset = dataset.repeat() cardinality = dataset.cardinality() print((cardinality == tf.data.INFINITE_CARDINALITY).numpy()) True dataset = dataset.filter(lambda x: True) cardinality = dataset.cardinality() print((cardinality == tf.data.UNKNOWN_CARDINALITY).numpy()) True Returns A scalar tf.int64 Tensor representing the cardinality of the dataset. If the cardinality is infinite or unknown, cardinality returns the named constants tf.data.INFINITE_CARDINALITY and tf.data.UNKNOWN_CARDINALITY respectively. concatenate View source concatenate( dataset ) Creates a Dataset by concatenating the given dataset with this dataset. a = tf.data.Dataset.range(1, 4) # ==> [ 1, 2, 3 ] b = tf.data.Dataset.range(4, 8) # ==> [ 4, 5, 6, 7 ] ds = a.concatenate(b) list(ds.as_numpy_iterator()) [1, 2, 3, 4, 5, 6, 7] # The input dataset and dataset to be concatenated should have the same # nested structures and output types. c = tf.data.Dataset.zip((a, b)) a.concatenate(c) Traceback (most recent call last): TypeError: Two datasets to concatenate have different types <dtype: 'int64'> and (tf.int64, tf.int64) d = tf.data.Dataset.from_tensor_slices(["a", "b", "c"]) a.concatenate(d) Traceback (most recent call last): TypeError: Two datasets to concatenate have different types <dtype: 'int64'> and <dtype: 'string'> Args dataset Dataset to be concatenated. Returns Dataset A Dataset. enumerate View source enumerate( start=0 ) Enumerates the elements of this dataset. It is similar to python's enumerate. dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) dataset = dataset.enumerate(start=5) for element in dataset.as_numpy_iterator(): print(element) (5, 1) (6, 2) (7, 3) # The nested structure of the input dataset determines the structure of # elements in the resulting dataset. dataset = tf.data.Dataset.from_tensor_slices([(7, 8), (9, 10)]) dataset = dataset.enumerate() for element in dataset.as_numpy_iterator(): print(element) (0, array([7, 8], dtype=int32)) (1, array([ 9, 10], dtype=int32)) Args start A tf.int64 scalar tf.Tensor, representing the start value for enumeration. Returns Dataset A Dataset. filter View source filter( predicate ) Filters this dataset according to predicate. dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) dataset = dataset.filter(lambda x: x < 3) list(dataset.as_numpy_iterator()) [1, 2] # `tf.math.equal(x, y)` is required for equality comparison def filter_fn(x): return tf.math.equal(x, 1) dataset = dataset.filter(filter_fn) list(dataset.as_numpy_iterator()) [1] Args predicate A function mapping a dataset element to a boolean. Returns Dataset The Dataset containing the elements of this dataset for which predicate is True. filter_with_legacy_function View source filter_with_legacy_function( predicate ) Filters this dataset according to predicate. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use `tf.data.Dataset.filter() Note: This is an escape hatch for existing uses of filter that do not work with V2 functions. New uses are strongly discouraged and existing uses should migrate to filter as this method will be removed in V2. Args predicate A function mapping a nested structure of tensors (having shapes and types defined by self.output_shapes and self.output_types) to a scalar tf.bool tensor. Returns Dataset The Dataset containing the elements of this dataset for which predicate is True. flat_map View source flat_map( map_func ) Maps map_func across this dataset and flattens the result. Use flat_map if you want to make sure that the order of your dataset stays the same. For example, to flatten a dataset of batches into a dataset of their elements: dataset = tf.data.Dataset.from_tensor_slices( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]) dataset = dataset.flat_map(lambda x: Dataset.from_tensor_slices(x)) list(dataset.as_numpy_iterator()) [1, 2, 3, 4, 5, 6, 7, 8, 9] tf.data.Dataset.interleave() is a generalization of flat_map, since flat_map produces the same output as tf.data.Dataset.interleave(cycle_length=1) Args map_func A function mapping a dataset element to a dataset. Returns Dataset A Dataset. from_generator View source @staticmethod from_generator( generator, output_types=None, output_shapes=None, args=None, output_signature=None ) Creates a Dataset whose elements are generated by generator. (deprecated arguments) Warning: SOME ARGUMENTS ARE DEPRECATED: (output_shapes, output_types). They will be removed in a future version. Instructions for updating: Use output_signature instead The generator argument must be a callable object that returns an object that supports the iter() protocol (e.g. a generator function). The elements generated by generator must be compatible with either the given output_signature argument or with the given output_types and (optionally) output_shapes arguments, whichiver was specified. The recommended way to call from_generator is to use the output_signature argument. In this case the output will be assumed to consist of objects with the classes, shapes and types defined by tf.TypeSpec objects from output_signature argument: def gen(): ragged_tensor = tf.ragged.constant([[1, 2], [3]]) yield 42, ragged_tensor dataset = tf.data.Dataset.from_generator( gen, output_signature=( tf.TensorSpec(shape=(), dtype=tf.int32), tf.RaggedTensorSpec(shape=(2, None), dtype=tf.int32))) list(dataset.take(1)) [(<tf.Tensor: shape=(), dtype=int32, numpy=42>, <tf.RaggedTensor [[1, 2], [3]]>)] There is also a deprecated way to call from_generator by either with output_types argument alone or together with output_shapes argument. In this case the output of the function will be assumed to consist of tf.Tensor objects with with the types defined by output_types and with the shapes which are either unknown or defined by output_shapes. Note: The current implementation of Dataset.from_generator() uses tf.numpy_function and inherits the same constraints. In particular, it requires the dataset and iterator related operations to be placed on a device in the same process as the Python program that called Dataset.from_generator(). The body of generator will not be serialized in a GraphDef, and you should not use this method if you need to serialize your model and restore it in a different environment. Note: If generator depends on mutable global variables or other external state, be aware that the runtime may invoke generator multiple times (in order to support repeating the Dataset) and at any time between the call to Dataset.from_generator() and the production of the first element from the generator. Mutating global variables or external state can cause undefined behavior, and we recommend that you explicitly cache any external state in generator before calling Dataset.from_generator(). Args generator A callable object that returns an object that supports the iter() protocol. If args is not specified, generator must take no arguments; otherwise it must take as many arguments as there are values in args. output_types (Optional.) A nested structure of tf.DType objects corresponding to each component of an element yielded by generator. output_shapes (Optional.) A nested structure of tf.TensorShape objects corresponding to each component of an element yielded by generator. args (Optional.) A tuple of tf.Tensor objects that will be evaluated and passed to generator as NumPy-array arguments. output_signature (Optional.) A nested structure of tf.TypeSpec objects corresponding to each component of an element yielded by generator. Returns Dataset A Dataset. from_sparse_tensor_slices View source @staticmethod from_sparse_tensor_slices( sparse_tensor ) Splits each rank-N tf.sparse.SparseTensor in this dataset row-wise. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.data.Dataset.from_tensor_slices(). Args sparse_tensor A tf.sparse.SparseTensor. Returns Dataset A Dataset of rank-(N-1) sparse tensors. from_tensor_slices View source @staticmethod from_tensor_slices( tensors ) Creates a Dataset whose elements are slices of the given tensors. The given tensors are sliced along their first dimension. This operation preserves the structure of the input tensors, removing the first dimension of each tensor and using it as the dataset dimension. All input tensors must have the same size in their first dimensions. # Slicing a 1D tensor produces scalar tensor elements. dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) list(dataset.as_numpy_iterator()) [1, 2, 3] # Slicing a 2D tensor produces 1D tensor elements. dataset = tf.data.Dataset.from_tensor_slices([[1, 2], [3, 4]]) list(dataset.as_numpy_iterator()) [array([1, 2], dtype=int32), array([3, 4], dtype=int32)] # Slicing a tuple of 1D tensors produces tuple elements containing # scalar tensors. dataset = tf.data.Dataset.from_tensor_slices(([1, 2], [3, 4], [5, 6])) list(dataset.as_numpy_iterator()) [(1, 3, 5), (2, 4, 6)] # Dictionary structure is also preserved. dataset = tf.data.Dataset.from_tensor_slices({"a": [1, 2], "b": [3, 4]}) list(dataset.as_numpy_iterator()) == [{'a': 1, 'b': 3}, {'a': 2, 'b': 4}] True # Two tensors can be combined into one Dataset object. features = tf.constant([[1, 3], [2, 1], [3, 3]]) # ==> 3x2 tensor labels = tf.constant(['A', 'B', 'A']) # ==> 3x1 tensor dataset = Dataset.from_tensor_slices((features, labels)) # Both the features and the labels tensors can be converted # to a Dataset object separately and combined after. features_dataset = Dataset.from_tensor_slices(features) labels_dataset = Dataset.from_tensor_slices(labels) dataset = Dataset.zip((features_dataset, labels_dataset)) # A batched feature and label set can be converted to a Dataset # in similar fashion. batched_features = tf.constant([[[1, 3], [2, 3]], [[2, 1], [1, 2]], [[3, 3], [3, 2]]], shape=(3, 2, 2)) batched_labels = tf.constant([['A', 'A'], ['B', 'B'], ['A', 'B']], shape=(3, 2, 1)) dataset = Dataset.from_tensor_slices((batched_features, batched_labels)) for element in dataset.as_numpy_iterator(): print(element) (array([[1, 3], [2, 3]], dtype=int32), array([[b'A'], [b'A']], dtype=object)) (array([[2, 1], [1, 2]], dtype=int32), array([[b'B'], [b'B']], dtype=object)) (array([[3, 3], [3, 2]], dtype=int32), array([[b'A'], [b'B']], dtype=object)) Note that if tensors contains a NumPy array, and eager execution is not enabled, the values will be embedded in the graph as one or more tf.constant operations. For large datasets (> 1 GB), this can waste memory and run into byte limits of graph serialization. If tensors contains one or more large NumPy arrays, consider the alternative described in this guide. Args tensors A dataset element, with each component having the same size in the first dimension. Returns Dataset A Dataset. from_tensors View source @staticmethod from_tensors( tensors ) Creates a Dataset with a single element, comprising the given tensors. from_tensors produces a dataset containing only a single element. To slice the input tensor into multiple elements, use from_tensor_slices instead. dataset = tf.data.Dataset.from_tensors([1, 2, 3]) list(dataset.as_numpy_iterator()) [array([1, 2, 3], dtype=int32)] dataset = tf.data.Dataset.from_tensors(([1, 2, 3], 'A')) list(dataset.as_numpy_iterator()) [(array([1, 2, 3], dtype=int32), b'A')] # You can use `from_tensors` to produce a dataset which repeats # the same example many times. example = tf.constant([1,2,3]) dataset = tf.data.Dataset.from_tensors(example).repeat(2) list(dataset.as_numpy_iterator()) [array([1, 2, 3], dtype=int32), array([1, 2, 3], dtype=int32)] Note that if tensors contains a NumPy array, and eager execution is not enabled, the values will be embedded in the graph as one or more tf.constant operations. For large datasets (> 1 GB), this can waste memory and run into byte limits of graph serialization. If tensors contains one or more large NumPy arrays, consider the alternative described in this guide. Args tensors A dataset element. Returns Dataset A Dataset. interleave View source interleave( map_func, cycle_length=None, block_length=None, num_parallel_calls=None, deterministic=None ) Maps map_func across this dataset, and interleaves the results. For example, you can use Dataset.interleave() to process many input files concurrently: # Preprocess 4 files concurrently, and interleave blocks of 16 records # from each file. filenames = ["/var/data/file1.txt", "/var/data/file2.txt", "/var/data/file3.txt", "/var/data/file4.txt"] dataset = tf.data.Dataset.from_tensor_slices(filenames) def parse_fn(filename): return tf.data.Dataset.range(10) dataset = dataset.interleave(lambda x: tf.data.TextLineDataset(x).map(parse_fn, num_parallel_calls=1), cycle_length=4, block_length=16) The cycle_length and block_length arguments control the order in which elements are produced. cycle_length controls the number of input elements that are processed concurrently. If you set cycle_length to 1, this transformation will handle one input element at a time, and will produce identical results to tf.data.Dataset.flat_map. In general, this transformation will apply map_func to cycle_length input elements, open iterators on the returned Dataset objects, and cycle through them producing block_length consecutive elements from each iterator, and consuming the next input element each time it reaches the end of an iterator. For example: dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ] # NOTE: New lines indicate "block" boundaries. dataset = dataset.interleave( lambda x: Dataset.from_tensors(x).repeat(6), cycle_length=2, block_length=4) list(dataset.as_numpy_iterator()) [1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5] Note: The order of elements yielded by this transformation is deterministic, as long as map_func is a pure function and deterministic=True. If map_func contains any stateful operations, the order in which that state is accessed is undefined. Performance can often be improved by setting num_parallel_calls so that interleave will use multiple threads to fetch elements. If determinism isn't required, it can also improve performance to set deterministic=False. filenames = ["/var/data/file1.txt", "/var/data/file2.txt", "/var/data/file3.txt", "/var/data/file4.txt"] dataset = tf.data.Dataset.from_tensor_slices(filenames) dataset = dataset.interleave(lambda x: tf.data.TFRecordDataset(x), cycle_length=4, num_parallel_calls=tf.data.AUTOTUNE, deterministic=False) Args map_func A function mapping a dataset element to a dataset. cycle_length (Optional.) The number of input elements that will be processed concurrently. If not set, the tf.data runtime decides what it should be based on available CPU. If num_parallel_calls is set to tf.data.AUTOTUNE, the cycle_length argument identifies the maximum degree of parallelism. block_length (Optional.) The number of consecutive elements to produce from each input element before cycling to another input element. If not set, defaults to 1. num_parallel_calls (Optional.) If specified, the implementation creates a threadpool, which is used to fetch inputs from cycle elements asynchronously and in parallel. The default behavior is to fetch inputs from cycle elements synchronously with no parallelism. If the value tf.data.AUTOTUNE is used, then the number of parallel calls is set dynamically based on available CPU. deterministic (Optional.) A boolean controlling whether determinism should be traded for performance by allowing elements to be produced out of order. If deterministic is None, the tf.data.Options.experimental_deterministic dataset option (True by default) is used to decide whether to produce elements deterministically. Returns Dataset A Dataset. list_files View source @staticmethod list_files( file_pattern, shuffle=None, seed=None ) A dataset of all files matching one or more glob patterns. The file_pattern argument should be a small number of glob patterns. If your filenames have already been globbed, use Dataset.from_tensor_slices(filenames) instead, as re-globbing every filename with list_files may result in poor performance with remote storage systems. Note: The default behavior of this method is to return filenames in a non-deterministic random shuffled order. Pass a seed or shuffle=False to get results in a deterministic order. Example: If we had the following files on our filesystem: /path/to/dir/a.txt /path/to/dir/b.py /path/to/dir/c.py If we pass "/path/to/dir/*.py" as the directory, the dataset would produce: /path/to/dir/b.py /path/to/dir/c.py Args file_pattern A string, a list of strings, or a tf.Tensor of string type (scalar or vector), representing the filename glob (i.e. shell wildcard) pattern(s) that will be matched. shuffle (Optional.) If True, the file names will be shuffled randomly. Defaults to True. seed (Optional.) A tf.int64 scalar tf.Tensor, representing the random seed that will be used to create the distribution. See tf.random.set_seed for behavior. Returns Dataset A Dataset of strings corresponding to file names. make_initializable_iterator View source make_initializable_iterator( shared_name=None ) Creates an iterator for elements of this dataset. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This is a deprecated API that should only be used in TF 1 graph mode and legacy TF 2 graph mode available through tf.compat.v1. In all other situations -- namely, eager mode and inside tf.function -- you can consume dataset elements using for elem in dataset: ... or by explicitly creating iterator via iterator = iter(dataset) and fetching its elements via values = next(iterator). Furthermore, this API is not available in TF 2. During the transition from TF 1 to TF 2 you can use tf.compat.v1.data.make_initializable_iterator(dataset) to create a TF 1 graph mode style iterator for a dataset created through TF 2 APIs. Note that this should be a transient state of your code base as there are in general no guarantees about the interoperability of TF 1 and TF 2 code. Note: The returned iterator will be in an uninitialized state, and you must run the iterator.initializer operation before using it: # Building graph ... dataset = ... iterator = dataset.make_initializable_iterator() next_value = iterator.get_next() # This is a Tensor. # ... from within a session ... sess.run(iterator.initializer) try: while True: value = sess.run(next_value) ... except tf.errors.OutOfRangeError: pass Args shared_name (Optional.) If non-empty, the returned iterator will be shared under the given name across multiple sessions that share the same devices (e.g. when using a remote server). Returns A tf.data.Iterator for elements of this dataset. Raises RuntimeError If eager execution is enabled. make_one_shot_iterator View source make_one_shot_iterator() Creates an iterator for elements of this dataset. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This is a deprecated API that should only be used in TF 1 graph mode and legacy TF 2 graph mode available through tf.compat.v1. In all other situations -- namely, eager mode and inside tf.function -- you can consume dataset elements using for elem in dataset: ... or by explicitly creating iterator via iterator = iter(dataset) and fetching its elements via values = next(iterator). Furthermore, this API is not available in TF 2. During the transition from TF 1 to TF 2 you can use tf.compat.v1.data.make_one_shot_iterator(dataset) to create a TF 1 graph mode style iterator for a dataset created through TF 2 APIs. Note that this should be a transient state of your code base as there are in general no guarantees about the interoperability of TF 1 and TF 2 code. Note: The returned iterator will be initialized automatically. A "one-shot" iterator does not currently support re-initialization. For that see make_initializable_iterator. Example: # Building graph ... dataset = ... next_value = dataset.make_one_shot_iterator().get_next() # ... from within a session ... try: while True: value = sess.run(next_value) ... except tf.errors.OutOfRangeError: pass Returns An tf.data.Iterator for elements of this dataset. map View source map( map_func, num_parallel_calls=None, deterministic=None ) Maps map_func across the elements of this dataset. This transformation applies map_func to each element of this dataset, and returns a new dataset containing the transformed elements, in the same order as they appeared in the input. map_func can be used to change both the values and the structure of a dataset's elements. For example, adding 1 to each element, or projecting a subset of element components. dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ] dataset = dataset.map(lambda x: x + 1) list(dataset.as_numpy_iterator()) [2, 3, 4, 5, 6] The input signature of map_func is determined by the structure of each element in this dataset. dataset = Dataset.range(5) # `map_func` takes a single argument of type `tf.Tensor` with the same # shape and dtype. result = dataset.map(lambda x: x + 1) # Each element is a tuple containing two `tf.Tensor` objects. elements = [(1, "foo"), (2, "bar"), (3, "baz")] dataset = tf.data.Dataset.from_generator( lambda: elements, (tf.int32, tf.string)) # `map_func` takes two arguments of type `tf.Tensor`. This function # projects out just the first component. result = dataset.map(lambda x_int, y_str: x_int) list(result.as_numpy_iterator()) [1, 2, 3] # Each element is a dictionary mapping strings to `tf.Tensor` objects. elements = ([{"a": 1, "b": "foo"}, {"a": 2, "b": "bar"}, {"a": 3, "b": "baz"}]) dataset = tf.data.Dataset.from_generator( lambda: elements, {"a": tf.int32, "b": tf.string}) # `map_func` takes a single argument of type `dict` with the same keys # as the elements. result = dataset.map(lambda d: str(d["a"]) + d["b"]) The value or values returned by map_func determine the structure of each element in the returned dataset. dataset = tf.data.Dataset.range(3) # `map_func` returns two `tf.Tensor` objects. def g(x): return tf.constant(37.0), tf.constant(["Foo", "Bar", "Baz"]) result = dataset.map(g) result.element_spec (TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(3,), dtype=tf.string, name=None)) # Python primitives, lists, and NumPy arrays are implicitly converted to # `tf.Tensor`. def h(x): return 37.0, ["Foo", "Bar"], np.array([1.0, 2.0], dtype=np.float64) result = dataset.map(h) result.element_spec (TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(2,), dtype=tf.string, name=None), TensorSpec(shape=(2,), dtype=tf.float64, name=None)) # `map_func` can return nested structures. def i(x): return (37.0, [42, 16]), "foo" result = dataset.map(i) result.element_spec ((TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(2,), dtype=tf.int32, name=None)), TensorSpec(shape=(), dtype=tf.string, name=None)) map_func can accept as arguments and return any type of dataset element. Note that irrespective of the context in which map_func is defined (eager vs. graph), tf.data traces the function and executes it as a graph. To use Python code inside of the function you have a few options: 1) Rely on AutoGraph to convert Python code into an equivalent graph computation. The downside of this approach is that AutoGraph can convert some but not all Python code. 2) Use tf.py_function, which allows you to write arbitrary Python code but will generally result in worse performance than 1). For example: d = tf.data.Dataset.from_tensor_slices(['hello', 'world']) # transform a string tensor to upper case string using a Python function def upper_case_fn(t: tf.Tensor): return t.numpy().decode('utf-8').upper() d = d.map(lambda x: tf.py_function(func=upper_case_fn, inp=[x], Tout=tf.string)) list(d.as_numpy_iterator()) [b'HELLO', b'WORLD'] 3) Use tf.numpy_function, which also allows you to write arbitrary Python code. Note that tf.py_function accepts tf.Tensor whereas tf.numpy_function accepts numpy arrays and returns only numpy arrays. For example: d = tf.data.Dataset.from_tensor_slices(['hello', 'world']) def upper_case_fn(t: np.ndarray): return t.decode('utf-8').upper() d = d.map(lambda x: tf.numpy_function(func=upper_case_fn, inp=[x], Tout=tf.string)) list(d.as_numpy_iterator()) [b'HELLO', b'WORLD'] Note that the use of tf.numpy_function and tf.py_function in general precludes the possibility of executing user-defined transformations in parallel (because of Python GIL). Performance can often be improved by setting num_parallel_calls so that map will use multiple threads to process elements. If deterministic order isn't required, it can also improve performance to set deterministic=False. dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ] dataset = dataset.map(lambda x: x + 1, num_parallel_calls=tf.data.AUTOTUNE, deterministic=False) Args map_func A function mapping a dataset element to another dataset element. num_parallel_calls (Optional.) A tf.int32 scalar tf.Tensor, representing the number elements to process asynchronously in parallel. If not specified, elements will be processed sequentially. If the value tf.data.AUTOTUNE is used, then the number of parallel calls is set dynamically based on available CPU. deterministic (Optional.) A boolean controlling whether determinism should be traded for performance by allowing elements to be produced out of order. If deterministic is None, the tf.data.Options.experimental_deterministic dataset option (True by default) is used to decide whether to produce elements deterministically. Returns Dataset A Dataset. map_with_legacy_function View source map_with_legacy_function( map_func, num_parallel_calls=None, deterministic=None ) Maps map_func across the elements of this dataset. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use `tf.data.Dataset.map() Note: This is an escape hatch for existing uses of map that do not work with V2 functions. New uses are strongly discouraged and existing uses should migrate to map as this method will be removed in V2. Args map_func A function mapping a nested structure of tensors (having shapes and types defined by self.output_shapes and self.output_types) to another nested structure of tensors. num_parallel_calls (Optional.) A tf.int32 scalar tf.Tensor, representing the number elements to process asynchronously in parallel. If not specified, elements will be processed sequentially. If the value tf.data.AUTOTUNE is used, then the number of parallel calls is set dynamically based on available CPU. deterministic (Optional.) A boolean controlling whether determinism should be traded for performance by allowing elements to be produced out of order. If deterministic is None, the tf.data.Options.experimental_deterministic dataset option (True by default) is used to decide whether to produce elements deterministically. Returns Dataset A Dataset. options View source options() Returns the options for this dataset and its inputs. Returns A tf.data.Options object representing the dataset options. padded_batch View source padded_batch( batch_size, padded_shapes=None, padding_values=None, drop_remainder=False ) Combines consecutive elements of this dataset into padded batches. This transformation combines multiple consecutive elements of the input dataset into a single element. Like tf.data.Dataset.batch, the components of the resulting element will have an additional outer dimension, which will be batch_size (or N % batch_size for the last element if batch_size does not divide the number of input elements N evenly and drop_remainder is False). If your program depends on the batches having the same outer dimension, you should set the drop_remainder argument to True to prevent the smaller batch from being produced. Unlike tf.data.Dataset.batch, the input elements to be batched may have different shapes, and this transformation will pad each component to the respective shape in padded_shapes. The padded_shapes argument determines the resulting shape for each dimension of each component in an output element: If the dimension is a constant, the component will be padded out to that length in that dimension. If the dimension is unknown, the component will be padded out to the maximum length of all elements in that dimension. A = (tf.data.Dataset .range(1, 5, output_type=tf.int32) .map(lambda x: tf.fill([x], x))) # Pad to the smallest per-batch size that fits all elements. B = A.padded_batch(2) for element in B.as_numpy_iterator(): print(element) [[1 0] [2 2]] [[3 3 3 0] [4 4 4 4]] # Pad to a fixed size. C = A.padded_batch(2, padded_shapes=5) for element in C.as_numpy_iterator(): print(element) [[1 0 0 0 0] [2 2 0 0 0]] [[3 3 3 0 0] [4 4 4 4 0]] # Pad with a custom value. D = A.padded_batch(2, padded_shapes=5, padding_values=-1) for element in D.as_numpy_iterator(): print(element) [[ 1 -1 -1 -1 -1] [ 2 2 -1 -1 -1]] [[ 3 3 3 -1 -1] [ 4 4 4 4 -1]] # Components of nested elements can be padded independently. elements = [([1, 2, 3], [10]), ([4, 5], [11, 12])] dataset = tf.data.Dataset.from_generator( lambda: iter(elements), (tf.int32, tf.int32)) # Pad the first component of the tuple to length 4, and the second # component to the smallest size that fits. dataset = dataset.padded_batch(2, padded_shapes=([4], [None]), padding_values=(-1, 100)) list(dataset.as_numpy_iterator()) [(array([[ 1, 2, 3, -1], [ 4, 5, -1, -1]], dtype=int32), array([[ 10, 100], [ 11, 12]], dtype=int32))] # Pad with a single value and multiple components. E = tf.data.Dataset.zip((A, A)).padded_batch(2, padding_values=-1) for element in E.as_numpy_iterator(): print(element) (array([[ 1, -1], [ 2, 2]], dtype=int32), array([[ 1, -1], [ 2, 2]], dtype=int32)) (array([[ 3, 3, 3, -1], [ 4, 4, 4, 4]], dtype=int32), array([[ 3, 3, 3, -1], [ 4, 4, 4, 4]], dtype=int32)) See also tf.data.experimental.dense_to_sparse_batch, which combines elements that may have different shapes into a tf.sparse.SparseTensor. Args batch_size A tf.int64 scalar tf.Tensor, representing the number of consecutive elements of this dataset to combine in a single batch. padded_shapes (Optional.) A nested structure of tf.TensorShape or tf.int64 vector tensor-like objects representing the shape to which the respective component of each input element should be padded prior to batching. Any unknown dimensions will be padded to the maximum size of that dimension in each batch. If unset, all dimensions of all components are padded to the maximum size in the batch. padded_shapes must be set if any component has an unknown rank. padding_values (Optional.) A nested structure of scalar-shaped tf.Tensor, representing the padding values to use for the respective components. None represents that the nested structure should be padded with default values. Defaults are 0 for numeric types and the empty string for string types. The padding_values should have the same structure as the input dataset. If padding_values is a single element and the input dataset has multiple components, then the same padding_values will be used to pad every component of the dataset. If padding_values is a scalar, then its value will be broadcasted to match the shape of each component. drop_remainder (Optional.) A tf.bool scalar tf.Tensor, representing whether the last batch should be dropped in the case it has fewer than batch_size elements; the default behavior is not to drop the smaller batch. Returns Dataset A Dataset. Raises ValueError If a component has an unknown rank, and the padded_shapes argument is not set. prefetch View source prefetch( buffer_size ) Creates a Dataset that prefetches elements from this dataset. Most dataset input pipelines should end with a call to prefetch. This allows later elements to be prepared while the current element is being processed. This often improves latency and throughput, at the cost of using additional memory to store prefetched elements. Note: Like other Dataset methods, prefetch operates on the elements of the input dataset. It has no concept of examples vs. batches. examples.prefetch(2) will prefetch two elements (2 examples), while examples.batch(20).prefetch(2) will prefetch 2 elements (2 batches, of 20 examples each). dataset = tf.data.Dataset.range(3) dataset = dataset.prefetch(2) list(dataset.as_numpy_iterator()) [0, 1, 2] Args buffer_size A tf.int64 scalar tf.Tensor, representing the maximum number of elements that will be buffered when prefetching. Returns Dataset A Dataset. range View source @staticmethod range( *args, **kwargs ) Creates a Dataset of a step-separated range of values. list(Dataset.range(5).as_numpy_iterator()) [0, 1, 2, 3, 4] list(Dataset.range(2, 5).as_numpy_iterator()) [2, 3, 4] list(Dataset.range(1, 5, 2).as_numpy_iterator()) [1, 3] list(Dataset.range(1, 5, -2).as_numpy_iterator()) [] list(Dataset.range(5, 1).as_numpy_iterator()) [] list(Dataset.range(5, 1, -2).as_numpy_iterator()) [5, 3] list(Dataset.range(2, 5, output_type=tf.int32).as_numpy_iterator()) [2, 3, 4] list(Dataset.range(1, 5, 2, output_type=tf.float32).as_numpy_iterator()) [1.0, 3.0] Args *args follows the same semantics as python's xrange. len(args) == 1 -> start = 0, stop = args[0], step = 1. len(args) == 2 -> start = args[0], stop = args[1], step = 1. len(args) == 3 -> start = args[0], stop = args[1], step = args[2]. **kwargs output_type: Its expected dtype. (Optional, default: tf.int64). Returns Dataset A RangeDataset. Raises ValueError if len(args) == 0. reduce View source reduce( initial_state, reduce_func ) Reduces the input dataset to a single element. The transformation calls reduce_func successively on every element of the input dataset until the dataset is exhausted, aggregating information in its internal state. The initial_state argument is used for the initial state and the final state is returned as the result. tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, _: x + 1).numpy() 5 tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, y: x + y).numpy() 10 Args initial_state An element representing the initial state of the transformation. reduce_func A function that maps (old_state, input_element) to new_state. It must take two arguments and return a new element The structure of new_state must match the structure of initial_state. Returns A dataset element corresponding to the final state of the transformation. repeat View source repeat( count=None ) Repeats this dataset so each original value is seen count times. dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) dataset = dataset.repeat(3) list(dataset.as_numpy_iterator()) [1, 2, 3, 1, 2, 3, 1, 2, 3] Note: If this dataset is a function of global state (e.g. a random number generator), then different repetitions may produce different elements. Args count (Optional.) A tf.int64 scalar tf.Tensor, representing the number of times the dataset should be repeated. The default behavior (if count is None or -1) is for the dataset be repeated indefinitely. Returns Dataset A Dataset. shard View source shard( num_shards, index ) Creates a Dataset that includes only 1/num_shards of this dataset. shard is deterministic. The Dataset produced by A.shard(n, i) will contain all elements of A whose index mod n = i. A = tf.data.Dataset.range(10) B = A.shard(num_shards=3, index=0) list(B.as_numpy_iterator()) [0, 3, 6, 9] C = A.shard(num_shards=3, index=1) list(C.as_numpy_iterator()) [1, 4, 7] D = A.shard(num_shards=3, index=2) list(D.as_numpy_iterator()) [2, 5, 8] This dataset operator is very useful when running distributed training, as it allows each worker to read a unique subset. When reading a single input file, you can shard elements as follows: d = tf.data.TFRecordDataset(input_file) d = d.shard(num_workers, worker_index) d = d.repeat(num_epochs) d = d.shuffle(shuffle_buffer_size) d = d.map(parser_fn, num_parallel_calls=num_map_threads) Important caveats: Be sure to shard before you use any randomizing operator (such as shuffle). Generally it is best if the shard operator is used early in the dataset pipeline. For example, when reading from a set of TFRecord files, shard before converting the dataset to input samples. This avoids reading every file on every worker. The following is an example of an efficient sharding strategy within a complete pipeline: d = Dataset.list_files(pattern) d = d.shard(num_workers, worker_index) d = d.repeat(num_epochs) d = d.shuffle(shuffle_buffer_size) d = d.interleave(tf.data.TFRecordDataset, cycle_length=num_readers, block_length=1) d = d.map(parser_fn, num_parallel_calls=num_map_threads) Args num_shards A tf.int64 scalar tf.Tensor, representing the number of shards operating in parallel. index A tf.int64 scalar tf.Tensor, representing the worker index. Returns Dataset A Dataset. Raises InvalidArgumentError if num_shards or index are illegal values. Note: error checking is done on a best-effort basis, and errors aren't guaranteed to be caught upon dataset creation. (e.g. providing in a placeholder tensor bypasses the early checking, and will instead result in an error during a session.run call.) shuffle View source shuffle( buffer_size, seed=None, reshuffle_each_iteration=None ) Randomly shuffles the elements of this dataset. This dataset fills a buffer with buffer_size elements, then randomly samples elements from this buffer, replacing the selected elements with new elements. For perfect shuffling, a buffer size greater than or equal to the full size of the dataset is required. For instance, if your dataset contains 10,000 elements but buffer_size is set to 1,000, then shuffle will initially select a random element from only the first 1,000 elements in the buffer. Once an element is selected, its space in the buffer is replaced by the next (i.e. 1,001-st) element, maintaining the 1,000 element buffer. reshuffle_each_iteration controls whether the shuffle order should be different for each epoch. In TF 1.X, the idiomatic way to create epochs was through the repeat transformation: dataset = tf.data.Dataset.range(3) dataset = dataset.shuffle(3, reshuffle_each_iteration=True) dataset = dataset.repeat(2) # doctest: +SKIP [1, 0, 2, 1, 2, 0] dataset = tf.data.Dataset.range(3) dataset = dataset.shuffle(3, reshuffle_each_iteration=False) dataset = dataset.repeat(2) # doctest: +SKIP [1, 0, 2, 1, 0, 2] In TF 2.0, tf.data.Dataset objects are Python iterables which makes it possible to also create epochs through Python iteration: dataset = tf.data.Dataset.range(3) dataset = dataset.shuffle(3, reshuffle_each_iteration=True) list(dataset.as_numpy_iterator()) # doctest: +SKIP [1, 0, 2] list(dataset.as_numpy_iterator()) # doctest: +SKIP [1, 2, 0] dataset = tf.data.Dataset.range(3) dataset = dataset.shuffle(3, reshuffle_each_iteration=False) list(dataset.as_numpy_iterator()) # doctest: +SKIP [1, 0, 2] list(dataset.as_numpy_iterator()) # doctest: +SKIP [1, 0, 2] Args buffer_size A tf.int64 scalar tf.Tensor, representing the number of elements from this dataset from which the new dataset will sample. seed (Optional.) A tf.int64 scalar tf.Tensor, representing the random seed that will be used to create the distribution. See tf.random.set_seed for behavior. reshuffle_each_iteration (Optional.) A boolean, which if true indicates that the dataset should be pseudorandomly reshuffled each time it is iterated over. (Defaults to True.) Returns Dataset A Dataset. skip View source skip( count ) Creates a Dataset that skips count elements from this dataset. dataset = tf.data.Dataset.range(10) dataset = dataset.skip(7) list(dataset.as_numpy_iterator()) [7, 8, 9] Args count A tf.int64 scalar tf.Tensor, representing the number of elements of this dataset that should be skipped to form the new dataset. If count is greater than the size of this dataset, the new dataset will contain no elements. If count is -1, skips the entire dataset. Returns Dataset A Dataset. take View source take( count ) Creates a Dataset with at most count elements from this dataset. dataset = tf.data.Dataset.range(10) dataset = dataset.take(3) list(dataset.as_numpy_iterator()) [0, 1, 2] Args count A tf.int64 scalar tf.Tensor, representing the number of elements of this dataset that should be taken to form the new dataset. If count is -1, or if count is greater than the size of this dataset, the new dataset will contain all elements of this dataset. Returns Dataset A Dataset. unbatch View source unbatch() Splits elements of a dataset into multiple elements. For example, if elements of the dataset are shaped [B, a0, a1, ...], where B may vary for each input element, then for each element in the dataset, the unbatched dataset will contain B consecutive elements of shape [a0, a1, ...]. elements = [ [1, 2, 3], [1, 2], [1, 2, 3, 4] ] dataset = tf.data.Dataset.from_generator(lambda: elements, tf.int64) dataset = dataset.unbatch() list(dataset.as_numpy_iterator()) [1, 2, 3, 1, 2, 1, 2, 3, 4] Note: unbatch requires a data copy to slice up the batched tensor into smaller, unbatched tensors. When optimizing performance, try to avoid unnecessary usage of unbatch. Returns A Dataset. window View source window( size, shift=None, stride=1, drop_remainder=False ) Combines (nests of) input elements into a dataset of (nests of) windows. A "window" is a finite dataset of flat elements of size size (or possibly fewer if there are not enough input elements to fill the window and drop_remainder evaluates to False). The shift argument determines the number of input elements by which the window moves on each iteration. If windows and elements are both numbered starting at 0, the first element in window k will be element k * shift of the input dataset. In particular, the first element of the first window will always be the first element of the input dataset. The stride argument determines the stride of the input elements, and the shift argument determines the shift of the window. For example: dataset = tf.data.Dataset.range(7).window(2) for window in dataset: print(list(window.as_numpy_iterator())) [0, 1] [2, 3] [4, 5] [6] dataset = tf.data.Dataset.range(7).window(3, 2, 1, True) for window in dataset: print(list(window.as_numpy_iterator())) [0, 1, 2] [2, 3, 4] [4, 5, 6] dataset = tf.data.Dataset.range(7).window(3, 1, 2, True) for window in dataset: print(list(window.as_numpy_iterator())) [0, 2, 4] [1, 3, 5] [2, 4, 6] Note that when the window transformation is applied to a dataset of nested elements, it produces a dataset of nested windows. nested = ([1, 2, 3, 4], [5, 6, 7, 8]) dataset = tf.data.Dataset.from_tensor_slices(nested).window(2) for window in dataset: def to_numpy(ds): return list(ds.as_numpy_iterator()) print(tuple(to_numpy(component) for component in window)) ([1, 2], [5, 6]) ([3, 4], [7, 8]) dataset = tf.data.Dataset.from_tensor_slices({'a': [1, 2, 3, 4]}) dataset = dataset.window(2) for window in dataset: def to_numpy(ds): return list(ds.as_numpy_iterator()) print({'a': to_numpy(window['a'])}) {'a': [1, 2]} {'a': [3, 4]} Args size A tf.int64 scalar tf.Tensor, representing the number of elements of the input dataset to combine into a window. Must be positive. shift (Optional.) A tf.int64 scalar tf.Tensor, representing the number of input elements by which the window moves in each iteration. Defaults to size. Must be positive. stride (Optional.) A tf.int64 scalar tf.Tensor, representing the stride of the input elements in the sliding window. Must be positive. The default value of 1 means "retain every input element". drop_remainder (Optional.) A tf.bool scalar tf.Tensor, representing whether the last windows should be dropped if their size is smaller than size. Returns Dataset A Dataset of (nests of) windows -- a finite datasets of flat elements created from the (nests of) input elements. with_options View source with_options( options ) Returns a new tf.data.Dataset with the given options set. The options are "global" in the sense they apply to the entire dataset. If options are set multiple times, they are merged as long as different options do not use different non-default values. ds = tf.data.Dataset.range(5) ds = ds.interleave(lambda x: tf.data.Dataset.range(5), cycle_length=3, num_parallel_calls=3) options = tf.data.Options() # This will make the interleave order non-deterministic. options.experimental_deterministic = False ds = ds.with_options(options) Args options A tf.data.Options that identifies the options the use. Returns Dataset A Dataset with the given options. Raises ValueError when an option is set more than once to a non-default value zip View source @staticmethod zip( datasets ) Creates a Dataset by zipping together the given datasets. This method has similar semantics to the built-in zip() function in Python, with the main difference being that the datasets argument can be an arbitrary nested structure of Dataset objects. # The nested structure of the `datasets` argument determines the # structure of elements in the resulting dataset. a = tf.data.Dataset.range(1, 4) # ==> [ 1, 2, 3 ] b = tf.data.Dataset.range(4, 7) # ==> [ 4, 5, 6 ] ds = tf.data.Dataset.zip((a, b)) list(ds.as_numpy_iterator()) [(1, 4), (2, 5), (3, 6)] ds = tf.data.Dataset.zip((b, a)) list(ds.as_numpy_iterator()) [(4, 1), (5, 2), (6, 3)] # The `datasets` argument may contain an arbitrary number of datasets. c = tf.data.Dataset.range(7, 13).batch(2) # ==> [ [7, 8], # [9, 10], # [11, 12] ] ds = tf.data.Dataset.zip((a, b, c)) for element in ds.as_numpy_iterator(): print(element) (1, 4, array([7, 8])) (2, 5, array([ 9, 10])) (3, 6, array([11, 12])) # The number of elements in the resulting dataset is the same as # the size of the smallest dataset in `datasets`. d = tf.data.Dataset.range(13, 15) # ==> [ 13, 14 ] ds = tf.data.Dataset.zip((a, d)) list(ds.as_numpy_iterator()) [(1, 13), (2, 14)] Args datasets A nested structure of datasets. Returns Dataset A Dataset. __bool__ View source __bool__() __iter__ View source __iter__() Creates an iterator for elements of this dataset. The returned iterator implements the Python Iterator protocol. Returns An tf.data.Iterator for the elements of this dataset. Raises RuntimeError If not inside of tf.function and not executing eagerly. __len__ View source __len__() Returns the length of the dataset if it is known and finite. This method requires that you are running in eager mode, and that the length of the dataset is known and non-infinite. When the length may be unknown or infinite, or if you are running in graph mode, use tf.data.Dataset.cardinality instead. Returns An integer representing the length of the dataset. Raises RuntimeError If the dataset length is unknown or infinite, or if eager execution is not enabled. __nonzero__ View source __nonzero__()
doc_29892
Warning This method does nothing, except raise a ValueError exception. A masked array does not own its data and therefore cannot safely be resized in place. Use the numpy.ma.resize function instead. This method is difficult to implement safely and may be deprecated in future releases of NumPy.
doc_29893
Set the spine to be linear.
doc_29894
See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.Rescaling tf.keras.layers.experimental.preprocessing.Rescaling( scale, offset=0.0, name=None, **kwargs ) For instance: To rescale an input in the [0, 255] range to be in the [0, 1] range, you would pass scale=1./255. To rescale an input in the [0, 255] range to be in the [-1, 1] range, you would pass scale=1./127.5, offset=-1. The rescaling is applied both during training and inference. Input shape: Arbitrary. Output shape: Same as input. Arguments scale Float, the scale to apply to the inputs. offset Float, the offset to apply to the inputs. name A string, the name of the layer. Methods adapt View source adapt( data, reset_state=True ) Fits the state of the preprocessing layer to the data being passed. 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, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False.
doc_29895
Shift index by desired number of time frequency increments. This method is for shifting the values of datetime-like indexes by a specified time increment a given number of times. Parameters periods:int, default 1 Number of periods (or increments) to shift by, can be positive or negative. freq:pandas.DateOffset, pandas.Timedelta or str, optional Frequency increment to shift by. If None, the index is shifted by its own freq attribute. Offset aliases are valid strings, e.g., ‘D’, ‘W’, ‘M’ etc. Returns pandas.Index Shifted index. See also Series.shift Shift values of Series. Notes This method is only implemented for datetime-like index classes, i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex. Examples Put the first 5 month starts of 2011 into an index. >>> month_starts = pd.date_range('1/1/2011', periods=5, freq='MS') >>> month_starts DatetimeIndex(['2011-01-01', '2011-02-01', '2011-03-01', '2011-04-01', '2011-05-01'], dtype='datetime64[ns]', freq='MS') Shift the index by 10 days. >>> month_starts.shift(10, freq='D') DatetimeIndex(['2011-01-11', '2011-02-11', '2011-03-11', '2011-04-11', '2011-05-11'], dtype='datetime64[ns]', freq=None) The default value of freq is the freq attribute of the index, which is ‘MS’ (month start) in this example. >>> month_starts.shift(10) DatetimeIndex(['2011-11-01', '2011-12-01', '2012-01-01', '2012-02-01', '2012-03-01'], dtype='datetime64[ns]', freq='MS')
doc_29896
get an available event poll() -> Event Returns next event on queue. If there is no event waiting on the queue, this will return an event with type NOEVENT.
doc_29897
See Migration guide for more details. tf.compat.v1.ragged.range tf.ragged.range( starts, limits=None, deltas=1, dtype=None, name=None, row_splits_dtype=tf.dtypes.int64 ) Each row of the returned RaggedTensor contains a single sequence: ragged.range(starts, limits, deltas)[i] == tf.range(starts[i], limits[i], deltas[i]) If start[i] < limits[i] and deltas[i] > 0, then output[i] will be an empty list. Similarly, if start[i] > limits[i] and deltas[i] < 0, then output[i] will be an empty list. This behavior is consistent with the Python range function, but differs from the tf.range op, which returns an error for these cases. Examples: tf.ragged.range([3, 5, 2]).to_list() [[0, 1, 2], [0, 1, 2, 3, 4], [0, 1]] tf.ragged.range([0, 5, 8], [3, 3, 12]).to_list() [[0, 1, 2], [], [8, 9, 10, 11]] tf.ragged.range([0, 5, 8], [3, 3, 12], 2).to_list() [[0, 2], [], [8, 10]] 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 Vector or scalar Tensor. Specifies the first entry for each range if limits is not None; otherwise, specifies the range limits, and the first entries default to 0. limits Vector or scalar Tensor. Specifies the exclusive upper limits for each range. deltas Vector or scalar Tensor. Specifies the increment for each range. Defaults to 1. dtype The type of the elements of the resulting tensor. If not specified, then a value is chosen based on the other args. name A name for the operation. row_splits_dtype dtype for the returned RaggedTensor's row_splits tensor. One of tf.int32 or tf.int64. Returns A RaggedTensor of type dtype with ragged_rank=1.
doc_29898
Sets the random number generator state. Parameters new_state (torch.ByteTensor) – The desired state
doc_29899
See Migration guide for more details. tf.compat.v1.math.unsorted_segment_prod, tf.compat.v1.unsorted_segment_prod tf.math.unsorted_segment_prod( data, segment_ids, num_segments, name=None ) Read the section on segmentation for an explanation of segments. This operator is similar to the unsorted segment sum operator found (here). Instead of computing the sum over segments, it computes the product of all entries belonging to a segment such that: \(output_i = \prod_{j...} data[j...]\) where the product is over tuples j... such that segment_ids[j...] == i. For example: c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) tf.unsorted_segment_prod(c, tf.constant([0, 1, 0]), num_segments=2) # ==> [[ 4, 6, 6, 4], # [5, 6, 7, 8]] If there is no entry for a given segment ID i, it outputs 1. If the given segment ID i is negative, then the corresponding value is dropped, and will not be included in the result. Args data A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. segment_ids A Tensor. Must be one of the following types: int32, int64. A tensor whose shape is a prefix of data.shape. num_segments A Tensor. Must be one of the following types: int32, int64. name A name for the operation (optional). Returns A Tensor. Has the same type as data.