_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_2300 | class sklearn.model_selection.GroupKFold(n_splits=5) [source]
K-fold iterator variant with non-overlapping groups. The same group will not appear in two different folds (the number of distinct groups has to be at least equal to the number of folds). The folds are approximately balanced in the sense that the number of distinct groups is approximately the same in each fold. Read more in the User Guide. Parameters
n_splitsint, default=5
Number of folds. Must be at least 2. Changed in version 0.22: n_splits default value changed from 3 to 5. See also
LeaveOneGroupOut
For splitting the data according to explicit domain-specific stratification of the dataset. Examples >>> import numpy as np
>>> from sklearn.model_selection import GroupKFold
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> y = np.array([1, 2, 3, 4])
>>> groups = np.array([0, 0, 2, 2])
>>> group_kfold = GroupKFold(n_splits=2)
>>> group_kfold.get_n_splits(X, y, groups)
2
>>> print(group_kfold)
GroupKFold(n_splits=2)
>>> for train_index, test_index in group_kfold.split(X, y, groups):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
... print(X_train, X_test, y_train, y_test)
...
TRAIN: [0 1] TEST: [2 3]
[[1 2]
[3 4]] [[5 6]
[7 8]] [1 2] [3 4]
TRAIN: [2 3] TEST: [0 1]
[[5 6]
[7 8]] [[1 2]
[3 4]] [3 4] [1 2]
Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]
Returns the number of splitting iterations in the cross-validator Parameters
Xobject
Always ignored, exists for compatibility.
yobject
Always ignored, exists for compatibility.
groupsobject
Always ignored, exists for compatibility. Returns
n_splitsint
Returns the number of splitting iterations in the cross-validator.
split(X, y=None, groups=None) [source]
Generate indices to split data into training and test set. Parameters
Xarray-like of shape (n_samples, n_features)
Training data, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,), default=None
The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,)
Group labels for the samples used while splitting the dataset into train/test set. Yields
trainndarray
The training set indices for that split.
testndarray
The testing set indices for that split.
Examples using sklearn.model_selection.GroupKFold
Visualizing cross-validation behavior in scikit-learn | |
doc_2301 | See Migration guide for more details. tf.compat.v1.raw_ops.DenseCountSparseOutput
tf.raw_ops.DenseCountSparseOutput(
values, weights, binary_output, minlength=-1, maxlength=-1, name=None
)
Counts the number of times each value occurs in the input.
Args
values A Tensor. Must be one of the following types: int32, int64. Tensor containing data to count.
weights A Tensor. Must be one of the following types: int32, int64, float32, float64. A Tensor of the same shape as indices containing per-index weight values. May also be the empty tensor if no weights are used.
binary_output A bool. Whether to output the number of occurrences of each value or 1.
minlength An optional int that is >= -1. Defaults to -1. Minimum value to count. Can be set to -1 for no minimum.
maxlength An optional int that is >= -1. Defaults to -1. Maximum value to count. Can be set to -1 for no maximum.
name A name for the operation (optional).
Returns A tuple of Tensor objects (output_indices, output_values, output_dense_shape). output_indices A Tensor of type int64.
output_values A Tensor. Has the same type as weights.
output_dense_shape A Tensor of type int64. | |
doc_2302 | Token value for "*=". | |
doc_2303 | Perform the lock operation operation on file descriptor fd (file objects providing a fileno() method are accepted as well). See the Unix manual flock(2) for details. (On some systems, this function is emulated using fcntl().) If the flock() fails, an OSError exception is raised. Raises an auditing event fcntl.flock with arguments fd, operation. | |
doc_2304 |
Check if the interval is closed on the right side. For the meaning of closed and open see Interval. Returns
bool
True if the Interval is closed on the left-side. | |
doc_2305 | Return a list containing the tty attributes for file descriptor fd, as follows: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] where cc is a list of the tty special characters (each a string of length 1, except the items with indices VMIN and VTIME, which are integers when these fields are defined). The interpretation of the flags and the speeds as well as the indexing in the cc array must be done using the symbolic constants defined in the termios module. | |
doc_2306 |
Get a copy of the iterator as a 1-D array. Examples >>> x = np.arange(6).reshape(2, 3)
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> fl = x.flat
>>> fl.copy()
array([0, 1, 2, 3, 4, 5]) | |
doc_2307 | By default, if an expected output block contains just 1, an actual output block containing just 1 or just True is considered to be a match, and similarly for 0 versus False. When DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution is allowed. The default behavior caters to that Python changed the return type of many functions from integer to boolean; doctests expecting “little integer” output still work in these cases. This option will probably go away, but not for several years. | |
doc_2308 | mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. | |
doc_2309 | Creates an index (B-Tree) in the database. | |
doc_2310 |
Collects the provided Future objects into a single combined Future that is completed when all of the sub-futures are completed. Parameters
futures (list) – a list of Future objects. Returns
Returns a Future object to a list of the passed in Futures. Example::
>>> import torch
>>>
>>> fut0 = torch.futures.Future()
>>> fut1 = torch.futures.Future()
>>>
>>> fut = torch.futures.collect_all([fut0, fut1])
>>>
>>> fut0.set_result(0)
>>> fut1.set_result(1)
>>>
>>> fut_list = fut.wait()
>>> print(f"fut0 result = {fut_list[0].wait()}")
>>> print(f"fut1 result = {fut_list[1].wait()}")
>>> # outputs:
>>> # fut0 result = 0
>>> # fut1 result = 1 | |
doc_2311 | Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None). Return type
Union[Tuple[str, bool], Tuple[None, None]] | |
doc_2312 |
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly. | |
doc_2313 | Instantiate the bytes object str with the supplied parameters, where str should be a parameterized string obtained from the terminfo database. E.g. tparm(tigetstr("cup"), 5, 3) could result in b'\033[6;4H', the exact result depending on terminal type. | |
doc_2314 |
Learn and apply the dimensionality reduction. Parameters
Xarray-like of shape (n_samples, n_features)
Training samples.
yarray-like of shape (n_samples,) or (n_samples, n_targets), default=None
Targets. Returns
outarray-like or tuple of array-like
The transformed data X_tranformed if Y is not None, (X_transformed, Y_transformed) otherwise. | |
doc_2315 |
Attributes
build_cost_model int64 build_cost_model
build_cost_model_after int64 build_cost_model_after
enable_bfloat16_sendrecv bool enable_bfloat16_sendrecv
enable_recv_scheduling bool enable_recv_scheduling
infer_shapes bool infer_shapes
optimizer_options OptimizerOptions optimizer_options
place_pruned_graph bool place_pruned_graph
rewrite_options RewriterConfig rewrite_options
timeline_step int32 timeline_step | |
doc_2316 | set |= other | ...
Update the set, adding elements from all others. | |
doc_2317 | See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.RandomFlip
tf.keras.layers.experimental.preprocessing.RandomFlip(
mode=HORIZONTAL_AND_VERTICAL, seed=None, name=None, **kwargs
)
This layer will flip the images based on the mode attribute. During inference time, the output will be identical to input. Call the layer with training=True to flip the input. Input shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'. Output shape: 4D tensor with shape: (samples, height, width, channels), data_format='channels_last'.
Attributes
mode String indicating which flip mode to use. Can be "horizontal", "vertical", or "horizontal_and_vertical". Defaults to "horizontal_and_vertical". "horizontal" is a left-right flip and "vertical" is a top-bottom flip.
seed Integer. Used to create a random seed.
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_2318 |
Bases: matplotlib.backend_tools.ToolBase Tool to toggle the major and minor grids of the figure. default_keymap=['G']
Keymap to associate with this tool. list[str]: List of keys that will trigger this tool when a keypress event is emitted on self.figure.canvas.
description='Toggle major and minor grids'
Description of the Tool. str: Tooltip used if the Tool is included in a Toolbar.
trigger(sender, event, data=None)[source]
Called when this tool gets used. This method is called by ToolManager.trigger_tool. Parameters
eventEvent
The canvas event that caused this tool to be called.
senderobject
Object that requested the tool to be triggered.
dataobject
Extra data. | |
doc_2319 |
Make a non-blocking RPC call to run function func on worker to. RPC messages are sent and received in parallel to execution of Python code. This method is thread-safe. This method will immediately return a Future that can be awaited on. Parameters
to (str or WorkerInfo or int) – name/rank/WorkerInfo of the destination worker.
func (callable) – a callable function, such as Python callables, builtin operators (e.g. add()) and annotated TorchScript functions.
args (tuple) – the argument tuple for the func invocation.
kwargs (dict) – is a dictionary of keyword arguments for the func invocation.
timeout (float, optional) – timeout in seconds to use for this RPC. If the RPC does not complete in this amount of time, an exception indicating it has timed out will be raised. A value of 0 indicates an infinite timeout, i.e. a timeout error will never be raised. If not provided, the default value set during initialization or with _set_rpc_timeout is used. Returns
Returns a Future object that can be waited on. When completed, the return value of func on args and kwargs can be retrieved from the Future object. Warning Using GPU tensors as arguments or return values of func is not supported since we don’t support sending GPU tensors over the wire. You need to explicitly copy GPU tensors to CPU before using them as arguments or return values of func. Warning The rpc_async API does not copy storages of argument tensors until sending them over the wire, which could be done by a different thread depending on the RPC backend type. The caller should make sure that the contents of those tensors stay intact until the returned Future completes. Example::
Make sure that MASTER_ADDR and MASTER_PORT are set properly on both workers. Refer to init_process_group() API for more details. For example, >>> export MASTER_ADDR=localhost
>>> export MASTER_PORT=5678
Then run the following code in two different processes: >>> # On worker 0:
>>> import torch
>>> import torch.distributed.rpc as rpc
>>> rpc.init_rpc("worker0", rank=0, world_size=2)
>>> fut1 = rpc.rpc_async("worker1", torch.add, args=(torch.ones(2), 3))
>>> fut2 = rpc.rpc_async("worker1", min, args=(1, 2))
>>> result = fut1.wait() + fut2.wait()
>>> rpc.shutdown()
>>> # On worker 1:
>>> import torch.distributed.rpc as rpc
>>> rpc.init_rpc("worker1", rank=1, world_size=2)
>>> rpc.shutdown()
Below is an example of running a TorchScript function using RPC. >>> # On both workers:
>>> @torch.jit.script
>>> def my_script_add(t1, t2):
>>> return torch.add(t1, t2)
>>> # On worker 0:
>>> import torch.distributed.rpc as rpc
>>> rpc.init_rpc("worker0", rank=0, world_size=2)
>>> fut = rpc.rpc_async("worker1", my_script_add, args=(torch.ones(2), 3))
>>> ret = fut.wait()
>>> rpc.shutdown()
>>> # On worker 1:
>>> import torch.distributed.rpc as rpc
>>> rpc.init_rpc("worker1", rank=1, world_size=2)
>>> rpc.shutdown() | |
doc_2320 | See torch.addbmm() | |
doc_2321 |
Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_str(strings_only=True). | |
doc_2322 | Append line to the history buffer, as if it was the last line typed. This calls add_history() in the underlying library. | |
doc_2323 |
A compatibility alias for tobytes, with exactly the same behavior. Despite its name, it returns bytes not strs. Deprecated since version 1.19.0. | |
doc_2324 | class asynchat.async_chat
This class is an abstract subclass of asyncore.dispatcher. To make practical use of the code you must subclass async_chat, providing meaningful collect_incoming_data() and found_terminator() methods. The asyncore.dispatcher methods can be used, although not all make sense in a message/response context. Like asyncore.dispatcher, async_chat defines a set of events that are generated by an analysis of socket conditions after a select() call. Once the polling loop has been started the async_chat object’s methods are called by the event-processing framework with no action on the part of the programmer. Two class attributes can be modified, to improve performance, or possibly even to conserve memory.
ac_in_buffer_size
The asynchronous input buffer size (default 4096).
ac_out_buffer_size
The asynchronous output buffer size (default 4096).
Unlike asyncore.dispatcher, async_chat allows you to define a FIFO queue of producers. A producer need have only one method, more(), which should return data to be transmitted on the channel. The producer indicates exhaustion (i.e. that it contains no more data) by having its more() method return the empty bytes object. At this point the async_chat object removes the producer from the queue and starts using the next producer, if any. When the producer queue is empty the handle_write() method does nothing. You use the channel object’s set_terminator() method to describe how to recognize the end of, or an important breakpoint in, an incoming transmission from the remote endpoint. To build a functioning async_chat subclass your input methods collect_incoming_data() and found_terminator() must handle the data that the channel receives asynchronously. The methods are described below.
async_chat.close_when_done()
Pushes a None on to the producer queue. When this producer is popped off the queue it causes the channel to be closed.
async_chat.collect_incoming_data(data)
Called with data holding an arbitrary amount of received data. The default method, which must be overridden, raises a NotImplementedError exception.
async_chat.discard_buffers()
In emergencies this method will discard any data held in the input and/or output buffers and the producer queue.
async_chat.found_terminator()
Called when the incoming data stream matches the termination condition set by set_terminator(). The default method, which must be overridden, raises a NotImplementedError exception. The buffered input data should be available via an instance attribute.
async_chat.get_terminator()
Returns the current terminator for the channel.
async_chat.push(data)
Pushes data on to the channel’s queue to ensure its transmission. This is all you need to do to have the channel write the data out to the network, although it is possible to use your own producers in more complex schemes to implement encryption and chunking, for example.
async_chat.push_with_producer(producer)
Takes a producer object and adds it to the producer queue associated with the channel. When all currently-pushed producers have been exhausted the channel will consume this producer’s data by calling its more() method and send the data to the remote endpoint.
async_chat.set_terminator(term)
Sets the terminating condition to be recognized on the channel. term may be any of three types of value, corresponding to three different ways to handle incoming protocol data.
term Description
string Will call found_terminator() when the string is found in the input stream
integer Will call found_terminator() when the indicated number of characters have been received
None The channel continues to collect data forever Note that any data following the terminator will be available for reading by the channel after found_terminator() is called.
asynchat Example The following partial example shows how HTTP requests can be read with async_chat. A web server might create an http_request_handler object for each incoming client connection. Notice that initially the channel terminator is set to match the blank line at the end of the HTTP headers, and a flag indicates that the headers are being read. Once the headers have been read, if the request is of type POST (indicating that further data are present in the input stream) then the Content-Length: header is used to set a numeric terminator to read the right amount of data from the channel. The handle_request() method is called once all relevant input has been marshalled, after setting the channel terminator to None to ensure that any extraneous data sent by the web client are ignored. import asynchat
class http_request_handler(asynchat.async_chat):
def __init__(self, sock, addr, sessions, log):
asynchat.async_chat.__init__(self, sock=sock)
self.addr = addr
self.sessions = sessions
self.ibuffer = []
self.obuffer = b""
self.set_terminator(b"\r\n\r\n")
self.reading_headers = True
self.handling = False
self.cgi_data = None
self.log = log
def collect_incoming_data(self, data):
"""Buffer the data"""
self.ibuffer.append(data)
def found_terminator(self):
if self.reading_headers:
self.reading_headers = False
self.parse_headers(b"".join(self.ibuffer))
self.ibuffer = []
if self.op.upper() == b"POST":
clen = self.headers.getheader("content-length")
self.set_terminator(int(clen))
else:
self.handling = True
self.set_terminator(None)
self.handle_request()
elif not self.handling:
self.set_terminator(None) # browsers sometimes over-send
self.cgi_data = parse(self.headers, b"".join(self.ibuffer))
self.handling = True
self.ibuffer = []
self.handle_request() | |
doc_2325 |
Repeat elements of an array. Refer to numpy.repeat for full documentation. See also numpy.repeat
equivalent function | |
doc_2326 |
Draw a Gouraud-shaded triangle. Parameters
gcGraphicsContextBase
The graphics context.
points(3, 2) array-like
Array of (x, y) points for the triangle.
colors(3, 4) array-like
RGBA colors for each point of the triangle.
transformmatplotlib.transforms.Transform
An affine transform to apply to the points. | |
doc_2327 | Return the last recorded polygon. >>> turtle.home()
>>> turtle.begin_poly()
>>> turtle.fd(100)
>>> turtle.left(20)
>>> turtle.fd(30)
>>> turtle.left(60)
>>> turtle.fd(50)
>>> turtle.end_poly()
>>> p = turtle.get_poly()
>>> register_shape("myFavouriteShape", p) | |
doc_2328 | A dictionary mapping endpoint names to view functions. To register a view function, use the route() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. | |
doc_2329 | tf.io.parse_single_example(
serialized, features, example_names=None, name=None
)
Similar to parse_example, except: For dense tensors, the returned Tensor is identical to the output of parse_example, except there is no batch dimension, the output shape is the same as the shape given in dense_shape. For SparseTensors, the first (batch) column of the indices matrix is removed (the indices matrix is a column vector), the values vector is unchanged, and the first (batch_size) entry of the shape vector is removed (it is now a single element vector). One might see performance advantages by batching Example protos with parse_example instead of using this function directly.
Args
serialized A scalar string Tensor, a single serialized Example.
features A dict mapping feature keys to FixedLenFeature or VarLenFeature values.
example_names (Optional) A scalar string Tensor, the associated name.
name A name for this operation (optional).
Returns A dict mapping feature keys to Tensor and SparseTensor values.
Raises
ValueError if any feature is invalid. | |
doc_2330 |
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_2331 |
Set whether ticks are drawn inside or outside the axes. | |
doc_2332 | tf.shape(
input, out_type=tf.dtypes.int32, name=None
)
See also tf.size, tf.rank. tf.shape returns a 1-D integer tensor representing the shape of input. For a scalar input, the tensor returned has a shape of (0,) and its value is the empty vector (i.e. []). For example:
tf.shape(1.)
<tf.Tensor: shape=(0,), dtype=int32, numpy=array([], dtype=int32)>
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
tf.shape(t)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([2, 2, 3], dtype=int32)>
Note: When using symbolic tensors, such as when using the Keras API, tf.shape() will return the shape of the symbolic tensor.
a = tf.keras.layers.Input((None, 10))
tf.shape(a)
<... shape=(3,) dtype=int32...>
In these cases, using tf.Tensor.shape will return more informative results.
a.shape
TensorShape([None, None, 10])
(The first None represents the as yet unknown batch size.) tf.shape and Tensor.shape should be identical in eager mode. Within tf.function or within a compat.v1 context, not all dimensions may be known until execution time. Hence when defining custom layers and models for graph mode, prefer the dynamic tf.shape(x) over the static x.shape.
Args
input A Tensor or SparseTensor.
out_type (Optional) The specified output type of the operation (int32 or int64). Defaults to tf.int32.
name A name for the operation (optional).
Returns A Tensor of type out_type. | |
doc_2333 |
Return the transpose, which is by definition self. | |
doc_2334 |
Call self as a function. | |
doc_2335 | Create a color choosing dialog. A call to this method will show the window, wait for the user to make a selection, and return the selected color (or None) to the caller. | |
doc_2336 | tf.distribute.MultiWorkerMirroredStrategy(
cluster_resolver=None, communication_options=None
)
This strategy implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to tf.distribute.MirroredStrategy, it replicates all variables and computations to each local device. The difference is that it uses a distributed collective implementation (e.g. all-reduce), so that multiple workers can work together. You need to launch your program on each worker and configure cluster_resolver correctly. For example, if you are using tf.distribute.cluster_resolver.TFConfigClusterResolver, each worker needs to have its corresponding task_type and task_id set in the TF_CONFIG environment variable. An example TF_CONFIG on worker-0 of a two worker cluster is: TF_CONFIG = '{"cluster": {"worker": ["localhost:12345", "localhost:23456"]}, "task": {"type": "worker", "index": 0} }'
Your program runs on each worker as-is. Note that collectives require each worker to participate. All tf.distribute and non tf.distribute API may use collectives internally, e.g. checkpointing and saving since reading a tf.Variable with tf.VariableSynchronization.ON_READ all-reduces the value. Therefore it's recommended to run exactly the same program on each worker. Dispatching based on task_type or task_id of the worker is error-prone. cluster_resolver.num_accelerators() determines the number of GPUs the strategy uses. If it's zero, the strategy uses the CPU. All workers need to use the same number of devices, otherwise the behavior is undefined. This strategy is not intended for TPU. Use tf.distribute.TPUStrategy instead. After setting up TF_CONFIG, using this strategy is similar to using tf.distribute.MirroredStrategy and tf.distribute.TPUStrategy. strategy = tf.distribute.MultiWorkerMirroredStrategy()
with strategy.scope():
model = tf.keras.Sequential([
tf.keras.layers.Dense(2, input_shape=(5,)),
])
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)
def dataset_fn(ctx):
x = np.random.random((2, 5)).astype(np.float32)
y = np.random.randint(2, size=(2, 1))
dataset = tf.data.Dataset.from_tensor_slices((x, y))
return dataset.repeat().batch(1, drop_remainder=True)
dist_dataset = strategy.distribute_datasets_from_function(dataset_fn)
model.compile()
model.fit(dist_dataset)
You can also write your own training loop: @tf.function
def train_step(iterator):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features, training=True)
loss = tf.keras.losses.sparse_categorical_crossentropy(
labels, logits)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
strategy.run(step_fn, args=(next(iterator),))
for _ in range(NUM_STEP):
train_step(iterator)
See Multi-worker training with Keras for a detailed tutorial. Saving You need to save and checkpoint on all workers instead of just one. This is because variables whose synchronization=ON_READ triggers aggregation during saving. It's recommended to save to a different path on each worker to avoid race conditions. Each worker saves the same thing. See Multi-worker training with Keras tutorial for examples. Known Issues
tf.distribute.cluster_resolver.TFConfigClusterResolver does not return the correct number of accelerators. The strategy uses all available GPUs if cluster_resolver is tf.distribute.cluster_resolver.TFConfigClusterResolver or None. In eager mode, the strategy needs to be created before calling any other Tensorflow API.
Args
cluster_resolver optional tf.distribute.cluster_resolver.ClusterResolver. If None, tf.distribute.cluster_resolver.TFConfigClusterResolver is used.
communication_options optional tf.distribute.experimental.CommunicationOptions. This configures the default options for cross device communications. It can be overridden by options provided to the communication APIs like tf.distribute.ReplicaContext.all_reduce. See tf.distribute.experimental.CommunicationOptions for details.
Attributes
cluster_resolver Returns the cluster resolver associated with this strategy. As a multi-worker strategy, tf.distribute.experimental.MultiWorkerMirroredStrategy provides the associated tf.distribute.cluster_resolver.ClusterResolver. If the user provides one in __init__, that instance is returned; if the user does not, a default TFConfigClusterResolver is provided.
extended tf.distribute.StrategyExtended with additional methods.
num_replicas_in_sync Returns number of replicas over which gradients are aggregated. Methods distribute_datasets_from_function View source
distribute_datasets_from_function(
dataset_fn, options=None
)
Distributes tf.data.Dataset instances created by calls to dataset_fn. The argument dataset_fn that users pass in is an input function that has a tf.distribute.InputContext argument and returns a tf.data.Dataset instance. It is expected that the returned dataset from dataset_fn is already batched by per-replica batch size (i.e. global batch size divided by the number of replicas in sync) and sharded. tf.distribute.Strategy.distribute_datasets_from_function does not batch or shard the tf.data.Dataset instance returned from the input function. dataset_fn will be called on the CPU device of each of the workers and each generates a dataset where every replica on that worker will dequeue one batch of inputs (i.e. if a worker has two replicas, two batches will be dequeued from the Dataset every step). This method can be used for several purposes. First, it allows you to specify your own batching and sharding logic. (In contrast, tf.distribute.experimental_distribute_dataset does batching and sharding for you.) For example, where experimental_distribute_dataset is unable to shard the input files, this method might be used to manually shard the dataset (avoiding the slow fallback behavior in experimental_distribute_dataset). In cases where the dataset is infinite, this sharding can be done by creating dataset replicas that differ only in their random seed. The dataset_fn should take an tf.distribute.InputContext instance where information about batching and input replication can be accessed. You can use element_spec property of the tf.distribute.DistributedDataset returned by this API to query the tf.TypeSpec of the elements returned by the iterator. This can be used to set the input_signature property of a tf.function. Follow tf.distribute.DistributedDataset.element_spec to see an example. Key Point: The tf.data.Dataset returned by dataset_fn should have a per-replica batch size, unlike experimental_distribute_dataset, which uses the global batch size. This may be computed using input_context.get_per_replica_batch_size.
Note: If you are using TPUStrategy, the order in which the data is processed by the workers when using tf.distribute.Strategy.experimental_distribute_dataset or tf.distribute.Strategy.distribute_datasets_from_function is not guaranteed. This is typically required if you are using tf.distribute to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to this snippet for an example of how to order outputs.
Note: Stateful dataset transformations are currently not supported with tf.distribute.experimental_distribute_dataset or tf.distribute.distribute_datasets_from_function. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a map_fn that uses tf.random.uniform to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
For a tutorial on more usage and properties of this method, refer to the tutorial on distributed input). If you are interested in last partial batch handling, read this section.
Args
dataset_fn A function taking a tf.distribute.InputContext instance and returning a tf.data.Dataset.
options tf.distribute.InputOptions used to control options on how this dataset is distributed.
Returns A tf.distribute.DistributedDataset.
experimental_distribute_dataset View source
experimental_distribute_dataset(
dataset, options=None
)
Creates tf.distribute.DistributedDataset from tf.data.Dataset. The returned tf.distribute.DistributedDataset can be iterated over similar to regular datasets. NOTE: The user cannot add any more transformations to a tf.distribute.DistributedDataset. You can only create an iterator or examine the tf.TypeSpec of the data generated by it. See API docs of tf.distribute.DistributedDataset to learn more. The following is an example:
global_batch_size = 2
# Passing the devices is optional.
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
# Create a dataset
dataset = tf.data.Dataset.range(4).batch(global_batch_size)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def replica_fn(input):
return input*2
result = []
# Iterate over the `tf.distribute.DistributedDataset`
for x in dist_dataset:
# process dataset elements
result.append(strategy.run(replica_fn, args=(x,)))
print(result)
[PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([0])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([2])>
}, PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([4])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([6])>
}]
Three key actions happending under the hood of this method are batching, sharding, and prefetching. In the code snippet above, dataset is batched by global_batch_size, and calling experimental_distribute_dataset on it rebatches dataset to a new batch size that is equal to the global batch size divided by the number of replicas in sync. We iterate through it using a Pythonic for loop. x is a tf.distribute.DistributedValues containing data for all replicas, and each replica gets data of the new batch size. tf.distribute.Strategy.run will take care of feeding the right per-replica data in x to the right replica_fn executed on each replica. Sharding contains autosharding across multiple workers and within every worker. First, in multi-worker distributed training (i.e. when you use tf.distribute.experimental.MultiWorkerMirroredStrategy or tf.distribute.TPUStrategy), autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right tf.data.experimental.AutoShardPolicy is set). This is to ensure that at each step, a global batch size of non-overlapping dataset elements will be processed by each worker. Autosharding has a couple of different options that can be specified using tf.data.experimental.DistributeOptions. Then, sharding within each worker means the method will split the data among all the worker devices (if more than one a present). This will happen regardless of multi-worker autosharding.
Note: for autosharding across multiple workers, the default mode is tf.data.experimental.AutoShardPolicy.AUTO. This mode will attempt to shard the input dataset by files if the dataset is being created out of reader datasets (e.g. tf.data.TFRecordDataset, tf.data.TextLineDataset, etc.) or otherwise shard the dataset by data, where each of the workers will read the entire dataset and only process the shard assigned to it. However, if you have less than one input file per worker, we suggest that you disable dataset autosharding across workers by setting the tf.data.experimental.DistributeOptions.auto_shard_policy to be tf.data.experimental.AutoShardPolicy.OFF.
By default, this method adds a prefetch transformation at the end of the user provided tf.data.Dataset instance. The argument to the prefetch transformation which is buffer_size is equal to the number of replicas in sync. If the above batch splitting and dataset sharding logic is undesirable, please use tf.distribute.Strategy.distribute_datasets_from_function instead, which does not do any automatic batching or sharding for you.
Note: If you are using TPUStrategy, the order in which the data is processed by the workers when using tf.distribute.Strategy.experimental_distribute_dataset or tf.distribute.Strategy.distribute_datasets_from_function is not guaranteed. This is typically required if you are using tf.distribute to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to this snippet for an example of how to order outputs.
Note: Stateful dataset transformations are currently not supported with tf.distribute.experimental_distribute_dataset or tf.distribute.distribute_datasets_from_function. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a map_fn that uses tf.random.uniform to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
For a tutorial on more usage and properties of this method, refer to the tutorial on distributed input. If you are interested in last partial batch handling, read this section.
Args
dataset tf.data.Dataset that will be sharded across all replicas using the rules stated above.
options tf.distribute.InputOptions used to control options on how this dataset is distributed.
Returns A tf.distribute.DistributedDataset.
experimental_distribute_values_from_function View source
experimental_distribute_values_from_function(
value_fn
)
Generates tf.distribute.DistributedValues from value_fn. This function is to generate tf.distribute.DistributedValues to pass into run, reduce, or other methods that take distributed values when not using datasets.
Args
value_fn The function to run to generate values. It is called for each replica with tf.distribute.ValueContext as the sole argument. It must return a Tensor or a type that can be converted to a Tensor.
Returns A tf.distribute.DistributedValues containing a value for each replica.
Example usage: Return constant value per replica:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def value_fn(ctx):
return tf.constant(1.)
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
local_result = strategy.experimental_local_results(distributed_values)
local_result
(<tf.Tensor: shape=(), dtype=float32, numpy=1.0>,
<tf.Tensor: shape=(), dtype=float32, numpy=1.0>)
Distribute values in array based on replica_id:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
array_value = np.array([3., 2., 1.])
def value_fn(ctx):
return array_value[ctx.replica_id_in_sync_group]
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
local_result = strategy.experimental_local_results(distributed_values)
local_result
(3.0, 2.0)
Specify values using num_replicas_in_sync:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def value_fn(ctx):
return ctx.num_replicas_in_sync
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
local_result = strategy.experimental_local_results(distributed_values)
local_result
(2, 2)
Place values on devices and distribute: strategy = tf.distribute.TPUStrategy()
worker_devices = strategy.extended.worker_devices
multiple_values = []
for i in range(strategy.num_replicas_in_sync):
with tf.device(worker_devices[i]):
multiple_values.append(tf.constant(1.0))
def value_fn(ctx):
return multiple_values[ctx.replica_id_in_sync_group]
distributed_values = strategy.
experimental_distribute_values_from_function(
value_fn)
experimental_local_results View source
experimental_local_results(
value
)
Returns the list of all local per-replica values contained in value.
Note: This only returns values on the worker initiated by this client. When using a tf.distribute.Strategy like tf.distribute.experimental.MultiWorkerMirroredStrategy, each worker will be its own client, and this function will only return values computed on that worker.
Args
value A value returned by experimental_run(), run(), extended.call_for_each_replica(), or a variable created in scope.
Returns A tuple of values contained in value. If value represents a single value, this returns (value,).
gather View source
gather(
value, axis
)
Gather value across replicas along axis to the current device. Given a tf.distribute.DistributedValues or tf.Tensor-like object value, this API gathers and concatenates value across replicas along the axis-th dimension. The result is copied to the "current" device which would typically be the CPU of the worker on which the program is running. For tf.distribute.TPUStrategy, it is the first TPU host. For multi-client MultiWorkerMirroredStrategy, this is CPU of each worker. This API can only be called in the cross-replica context. For a counterpart in the replica context, see tf.distribute.ReplicaContext.all_gather.
Note: For all strategies except tf.distribute.TPUStrategy, the input value on different replicas must have the same rank, and their shapes must be the same in all dimensions except the axis-th dimension. In other words, their shapes cannot be different in a dimension d where d does not equal to the axis argument. For example, given a tf.distribute.DistributedValues with component tensors of shape (1, 2, 3) and (1, 3, 3) on two replicas, you can call gather(..., axis=1, ...) on it, but not gather(..., axis=0, ...) or gather(..., axis=2, ...). However, for tf.distribute.TPUStrategy.gather, all tensors must have exactly the same rank and same shape.
Note: Given a tf.distribute.DistributedValues value, its component tensors must have a non-zero rank. Otherwise, consider using tf.expand_dims before gathering them.
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# A DistributedValues with component tensor of shape (2, 1) on each replica
distributed_values = strategy.experimental_distribute_values_from_function(lambda _: tf.identity(tf.constant([[1], [2]])))
@tf.function
def run():
return strategy.gather(distributed_values, axis=0)
run()
<tf.Tensor: shape=(4, 1), dtype=int32, numpy=
array([[1],
[2],
[1],
[2]], dtype=int32)>
Consider the following example for more combinations:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1", "GPU:2", "GPU:3"])
single_tensor = tf.reshape(tf.range(6), shape=(1,2,3))
distributed_values = strategy.experimental_distribute_values_from_function(lambda _: tf.identity(single_tensor))
@tf.function
def run(axis):
return strategy.gather(distributed_values, axis=axis)
axis=0
run(axis)
<tf.Tensor: shape=(4, 2, 3), dtype=int32, numpy=
array([[[0, 1, 2],
[3, 4, 5]],
[[0, 1, 2],
[3, 4, 5]],
[[0, 1, 2],
[3, 4, 5]],
[[0, 1, 2],
[3, 4, 5]]], dtype=int32)>
axis=1
run(axis)
<tf.Tensor: shape=(1, 8, 3), dtype=int32, numpy=
array([[[0, 1, 2],
[3, 4, 5],
[0, 1, 2],
[3, 4, 5],
[0, 1, 2],
[3, 4, 5],
[0, 1, 2],
[3, 4, 5]]], dtype=int32)>
axis=2
run(axis)
<tf.Tensor: shape=(1, 2, 12), dtype=int32, numpy=
array([[[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5]]], dtype=int32)>
Args
value a tf.distribute.DistributedValues instance, e.g. returned by Strategy.run, to be combined into a single tensor. It can also be a regular tensor when used with tf.distribute.OneDeviceStrategy or the default strategy. The tensors that constitute the DistributedValues can only be dense tensors with non-zero rank, NOT a tf.IndexedSlices.
axis 0-D int32 Tensor. Dimension along which to gather. Must be in the range [0, rank(value)).
Returns A Tensor that's the concatenation of value across replicas along axis dimension.
reduce View source
reduce(
reduce_op, value, axis
)
Reduce value across replicas and return result on current device.
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
total = strategy.reduce("SUM", per_replica_result, axis=None)
total
<tf.Tensor: shape=(), dtype=int32, numpy=1>
To see how this would look with multiple replicas, consider the same example with MirroredStrategy with 2 GPUs: strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
# Check devices on which per replica result is:
strategy.experimental_local_results(per_replica_result)[0].device
# /job:localhost/replica:0/task:0/device:GPU:0
strategy.experimental_local_results(per_replica_result)[1].device
# /job:localhost/replica:0/task:0/device:GPU:1
total = strategy.reduce("SUM", per_replica_result, axis=None)
# Check device on which reduced result is:
total.device
# /job:localhost/replica:0/task:0/device:CPU:0
This API is typically used for aggregating the results returned from different replicas, for reporting etc. For example, loss computed from different replicas can be averaged using this API before printing.
Note: The result is copied to the "current" device - which would typically be the CPU of the worker on which the program is running. For TPUStrategy, it is the first TPU host. For multi client MultiWorkerMirroredStrategy, this is CPU of each worker.
There are a number of different tf.distribute APIs for reducing values across replicas:
tf.distribute.ReplicaContext.all_reduce: This differs from Strategy.reduce in that it is for replica context and does not copy the results to the host device. all_reduce should be typically used for reductions inside the training step such as gradients.
tf.distribute.StrategyExtended.reduce_to and tf.distribute.StrategyExtended.batch_reduce_to: These APIs are more advanced versions of Strategy.reduce as they allow customizing the destination of the result. They are also called in cross replica context. What should axis be? Given a per-replica value returned by run, say a per-example loss, the batch will be divided across all the replicas. This function allows you to aggregate across replicas and optionally also across batch elements by specifying the axis parameter accordingly. For example, if you have a global batch size of 8 and 2 replicas, values for examples [0, 1, 2, 3] will be on replica 0 and [4, 5, 6, 7] will be on replica 1. With axis=None, reduce will aggregate only across replicas, returning [0+4, 1+5, 2+6, 3+7]. This is useful when each replica is computing a scalar or some other value that doesn't have a "batch" dimension (like a gradient or loss). strategy.reduce("sum", per_replica_result, axis=None)
Sometimes, you will want to aggregate across both the global batch and all replicas. You can get this behavior by specifying the batch dimension as the axis, typically axis=0. In this case it would return a scalar 0+1+2+3+4+5+6+7. strategy.reduce("sum", per_replica_result, axis=0)
If there is a last partial batch, you will need to specify an axis so that the resulting shape is consistent across replicas. So if the last batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you would get a shape mismatch unless you specify axis=0. If you specify tf.distribute.ReduceOp.MEAN, using axis=0 will use the correct denominator of 6. Contrast this with computing reduce_mean to get a scalar value on each replica and this function to average those means, which will weigh some values 1/8 and others 1/4.
Args
reduce_op a tf.distribute.ReduceOp value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN".
value a tf.distribute.DistributedValues instance, e.g. returned by Strategy.run, to be combined into a single tensor. It can also be a regular tensor when used with OneDeviceStrategy or default strategy.
axis specifies the dimension to reduce along within each replica's tensor. Should typically be set to the batch dimension, or None to only reduce across replicas (e.g. if the tensor has no batch dimension).
Returns A Tensor.
run View source
run(
fn, args=(), kwargs=None, options=None
)
Invokes fn on each replica, with the given arguments. This method is the primary way to distribute your computation with a tf.distribute object. It invokes fn on each replica. If args or kwargs have tf.distribute.DistributedValues, such as those produced by a tf.distribute.DistributedDataset from tf.distribute.Strategy.experimental_distribute_dataset or tf.distribute.Strategy.distribute_datasets_from_function, when fn is executed on a particular replica, it will be executed with the component of tf.distribute.DistributedValues that correspond to that replica. fn is invoked under a replica context. fn may call tf.distribute.get_replica_context() to access members such as all_reduce. Please see the module-level docstring of tf.distribute for the concept of replica context. All arguments in args or kwargs should either be Python values of a nested structure of tensors, e.g. a list of tensors, in which case args and kwargs will be passed to the fn invoked on each replica. Or args or kwargs can be tf.distribute.DistributedValues containing tensors or composite tensors, i.e. tf.compat.v1.TensorInfo.CompositeTensor, in which case each fn call will get the component of a tf.distribute.DistributedValues corresponding to its replica. Key Point: Depending on the implementation of tf.distribute.Strategy and whether eager execution is enabled, fn may be called one or more times. If fn is annotated with tf.function or tf.distribute.Strategy.run is called inside a tf.function (eager execution is disabled inside a tf.function by default), fn is called once per replica to generate a Tensorflow graph, which will then be reused for execution with new inputs. Otherwise, if eager execution is enabled, fn will be called once per replica every step just like regular python code. Example usage: Constant tensor input.
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
tensor_input = tf.constant(3.0)
@tf.function
def replica_fn(input):
return input*2.0
result = strategy.run(replica_fn, args=(tensor_input,))
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>,
1: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>
}
DistributedValues input.
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
@tf.function
def run():
def value_fn(value_context):
return value_context.num_replicas_in_sync
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn2(input):
return input*2
return strategy.run(replica_fn2, args=(distributed_values,))
result = run()
result
<tf.Tensor: shape=(), dtype=int32, numpy=4>
Use tf.distribute.ReplicaContext to allreduce values.
strategy = tf.distribute.MirroredStrategy(["gpu:0", "gpu:1"])
@tf.function
def run():
def value_fn(value_context):
return tf.constant(value_context.replica_id_in_sync_group)
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn(input):
return tf.distribute.get_replica_context().all_reduce("sum", input)
return strategy.run(replica_fn, args=(distributed_values,))
result = run()
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=int32, numpy=1>,
1: <tf.Tensor: shape=(), dtype=int32, numpy=1>
}
Args
fn The function to run on each replica.
args Optional positional arguments to fn. Its element can be a Python value, a tensor or a tf.distribute.DistributedValues.
kwargs Optional keyword arguments to fn. Its element can be a Python value, a tensor or a tf.distribute.DistributedValues.
options An optional instance of tf.distribute.RunOptions specifying the options to run fn.
Returns Merged return value of fn across replicas. The structure of the return value is the same as the return value from fn. Each element in the structure can either be tf.distribute.DistributedValues, Tensor objects, or Tensors (for example, if running on a single replica).
scope View source
scope()
Context manager to make the strategy current and distribute variables. This method returns a context manager, and is used as follows:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# Variable created inside scope:
with strategy.scope():
mirrored_variable = tf.Variable(1.)
mirrored_variable
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=1.0>
}
# Variable created outside scope:
regular_variable = tf.Variable(1.)
regular_variable
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
What happens when Strategy.scope is entered?
strategy is installed in the global context as the "current" strategy. Inside this scope, tf.distribute.get_strategy() will now return this strategy. Outside this scope, it returns the default no-op strategy. Entering the scope also enters the "cross-replica context". See tf.distribute.StrategyExtended for an explanation on cross-replica and replica contexts. Variable creation inside scope is intercepted by the strategy. Each strategy defines how it wants to affect the variable creation. Sync strategies like MirroredStrategy, TPUStrategy and MultiWorkerMiroredStrategy create variables replicated on each replica, whereas ParameterServerStrategy creates variables on the parameter servers. This is done using a custom tf.variable_creator_scope. In some strategies, a default device scope may also be entered: in MultiWorkerMiroredStrategy, a default device scope of "/CPU:0" is entered on each worker.
Note: Entering a scope does not automatically distribute a computation, except in the case of high level training framework like keras model.fit. If you're not using model.fit, you need to use strategy.run API to explicitly distribute that computation. See an example in the custom training loop tutorial.
What should be in scope and what should be outside? There are a number of requirements on what needs to happen inside the scope. However, in places where we have information about which strategy is in use, we often enter the scope for the user, so they don't have to do it explicitly (i.e. calling those either inside or outside the scope is OK). Anything that creates variables that should be distributed variables must be in strategy.scope. This can be either by directly putting it in scope, or relying on another API like strategy.run or model.fit to enter it for you. Any variable that is created outside scope will not be distributed and may have performance implications. Common things that create variables in TF: models, optimizers, metrics. These should always be created inside the scope. Another source of variable creation can be a checkpoint restore - when variables are created lazily. Note that any variable created inside a strategy captures the strategy information. So reading and writing to these variables outside the strategy.scope can also work seamlessly, without the user having to enter the scope. Some strategy APIs (such as strategy.run and strategy.reduce) which require to be in a strategy's scope, enter the scope for you automatically, which means when using those APIs you don't need to enter the scope yourself. When a tf.keras.Model is created inside a strategy.scope, we capture this information. When high level training frameworks methods such as model.compile, model.fit etc are then called on this model, we automatically enter the scope, as well as use this strategy to distribute the training etc. See detailed example in distributed keras tutorial. Note that simply calling the model(..) is not impacted - only high level training framework APIs are. model.compile, model.fit, model.evaluate, model.predict and model.save can all be called inside or outside the scope. The following can be either inside or outside the scope: Creating the input datasets Defining tf.functions that represent your training step Saving APIs such as tf.saved_model.save. Loading creates variables, so that should go inside the scope if you want to train the model in a distributed way. Checkpoint saving. As mentioned above - checkpoint.restore may sometimes need to be inside scope if it creates variables.
Returns A context manager. | |
doc_2337 |
Applies a 1D convolution over a quantized 1D input composed of several input planes. See Conv1d for details and output shape. Parameters
input – quantized input tensor of shape (minibatch,in_channels,iW)(\text{minibatch} , \text{in\_channels} , iW)
weight – quantized filters of shape (out_channels,in_channelsgroups,iW)(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , iW)
bias – non-quantized bias tensor of shape (out_channels)(\text{out\_channels}) . The tensor type must be torch.float.
stride – the stride of the convolving kernel. Can be a single number or a tuple (sW,). Default: 1
padding – implicit paddings on both sides of the input. Can be a single number or a tuple (padW,). Default: 0
dilation – the spacing between kernel elements. Can be a single number or a tuple (dW,). Default: 1
groups – split input into groups, in_channels\text{in\_channels} should be divisible by the number of groups. Default: 1
padding_mode – the padding mode to use. Only “zeros” is supported for quantized convolution at the moment. Default: “zeros”
scale – quantization scale for the output. Default: 1.0
zero_point – quantization zero_point for the output. Default: 0
dtype – quantization data type to use. Default: torch.quint8
Examples: >>> from torch.nn.quantized import functional as qF
>>> filters = torch.randn(33, 16, 3, dtype=torch.float)
>>> inputs = torch.randn(20, 16, 50, dtype=torch.float)
>>> bias = torch.randn(33, dtype=torch.float)
>>>
>>> scale, zero_point = 1.0, 0
>>> dtype_inputs = torch.quint8
>>> dtype_filters = torch.qint8
>>>
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
>>> qF.conv1d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point) | |
doc_2338 | Returns the log-transformed bounds on the theta. Returns
boundsndarray of shape (n_dims, 2)
The log-transformed bounds on the kernel’s hyperparameters theta | |
doc_2339 | Same as the non-lazy versions above, but using lazy execution. See lazy translations documentation. | |
doc_2340 |
Swap the bytes of the array elements Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually. Parameters
inplacebool, optional
If True, swap bytes in-place, default is False. Returns
outndarray
The byteswapped array. If inplace is True, this is a view to self. Examples >>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> list(map(hex, A))
['0x1', '0x100', '0x2233']
>>> A.byteswap(inplace=True)
array([ 256, 1, 13090], dtype=int16)
>>> list(map(hex, A))
['0x100', '0x1', '0x3322']
Arrays of byte-strings are not swapped >>> A = np.array([b'ceg', b'fac'])
>>> A.byteswap()
array([b'ceg', b'fac'], dtype='|S3')
A.newbyteorder().byteswap() produces an array with the same values
but different representation in memory >>> A = np.array([1, 2, 3])
>>> A.view(np.uint8)
array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
0, 0], dtype=uint8)
>>> A.newbyteorder().byteswap(inplace=True)
array([1, 2, 3])
>>> A.view(np.uint8)
array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
0, 3], dtype=uint8) | |
doc_2341 |
Copy properties from other to self. | |
doc_2342 | Raised when an operation is performed on a future that is not allowed in the current state. New in version 3.8. | |
doc_2343 |
Add a table to an Axes. At least one of cellText or cellColours must be specified. These parameters must be 2D lists, in which the outer lists define the rows and the inner list define the column values per row. Each row must have the same number of elements. The table can optionally have row and column headers, which are configured using rowLabels, rowColours, rowLoc and colLabels, colColours, colLoc respectively. For finer grained control over tables, use the Table class and add it to the axes with Axes.add_table. Parameters
cellText2D list of str, optional
The texts to place into the table cells. Note: Line breaks in the strings are currently not accounted for and will result in the text exceeding the cell boundaries.
cellColours2D list of colors, optional
The background colors of the cells.
cellLoc{'left', 'center', 'right'}, default: 'right'
The alignment of the text within the cells.
colWidthslist of float, optional
The column widths in units of the axes. If not given, all columns will have a width of 1 / ncols.
rowLabelslist of str, optional
The text of the row header cells.
rowColourslist of colors, optional
The colors of the row header cells.
rowLoc{'left', 'center', 'right'}, default: 'left'
The text alignment of the row header cells.
colLabelslist of str, optional
The text of the column header cells.
colColourslist of colors, optional
The colors of the column header cells.
colLoc{'left', 'center', 'right'}, default: 'left'
The text alignment of the column header cells.
locstr, optional
The position of the cell with respect to ax. This must be one of the codes.
bboxBbox, optional
A bounding box to draw the table into. If this is not None, this overrides loc.
edgessubstring of 'BRTL' or {'open', 'closed', 'horizontal', 'vertical'}
The cell edges to be drawn with a line. See also visible_edges. Returns
Table
The created table. Other Parameters
**kwargs
Table 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
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
figure Figure
fontsize float
gid str
in_layout bool
label object
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float
Examples using matplotlib.pyplot.table
Table Demo | |
doc_2344 |
Set the offset of the lines used to mark each event. | |
doc_2345 | Given a Tensor quantized by linear (affine) per-channel quantization, returns a Tensor of scales of the underlying quantizer. It has the number of elements that matches the corresponding dimensions (from q_per_channel_axis) of the tensor. | |
doc_2346 |
Predict using the linear model. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape (n_samples,)
Returns predicted values. | |
doc_2347 |
Return the font style. Values are: 'normal', 'italic' or 'oblique'. | |
doc_2348 | Upon unpickling, if the class defines __setstate__(), it is called with the unpickled state. In that case, there is no requirement for the state object to be a dictionary. Otherwise, the pickled state must be a dictionary and its items are assigned to the new instance’s dictionary. Note If __getstate__() returns a false value, the __setstate__() method will not be called upon unpickling. | |
doc_2349 | alias of ConvTranspose2d | |
doc_2350 | Return the protocol that was selected during the TLS handshake. If SSLContext.set_alpn_protocols() was not called, if the other party does not support ALPN, if this socket does not support any of the client’s proposed protocols, or if the handshake has not happened yet, None is returned. New in version 3.5. | |
doc_2351 |
Predict probability estimates. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Returns
Y_probarray-like of shape (n_samples, n_classes) | |
doc_2352 | See Migration guide for more details. tf.compat.v1.raw_ops.PrefetchDataset
tf.raw_ops.PrefetchDataset(
input_dataset, buffer_size, output_types, output_shapes, slack_period=0,
legacy_autotune=True, buffer_size_min=0, name=None
)
Args
input_dataset A Tensor of type variant.
buffer_size A Tensor of type int64. The maximum number of elements to buffer in an iterator over this dataset.
output_types A list of tf.DTypes that has length >= 1.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1.
slack_period An optional int. Defaults to 0.
legacy_autotune An optional bool. Defaults to True.
buffer_size_min An optional int. Defaults to 0.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_2353 | @tf_contextlib.contextmanager
tf.compat.v1.op_scope(
values, name, default_name=None
) | |
doc_2354 |
Read an array from an NPY file. Parameters
fpfile_like object
If this is not a real file object, then this may take extra memory and time.
allow_picklebool, optional
Whether to allow writing pickled data. Default: False Changed in version 1.16.3: Made default False in response to CVE-2019-6446.
pickle_kwargsdict
Additional keyword arguments to pass to pickle.load. These are only useful when loading object arrays saved on Python 2 when using Python 3. Returns
arrayndarray
The array from the data on disk. Raises
ValueError
If the data is invalid, or allow_pickle=False and the file contains an object array. | |
doc_2355 |
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat | |
doc_2356 |
Determine if each string entirely matches a regular expression. New in version 1.1.0. Parameters
pat:str
Character sequence or regular expression.
case:bool, default True
If True, case sensitive.
flags:int, default 0 (no flags)
Regex module flags, e.g. re.IGNORECASE.
na:scalar, optional
Fill value for missing values. The default depends on dtype of the array. For object-dtype, numpy.nan is used. For StringDtype, pandas.NA is used. Returns
Series/Index/array of boolean values
See also match
Similar, but also returns True when only a prefix of the string matches the regular expression. extract
Extract matched groups. | |
doc_2357 | See Migration guide for more details. tf.compat.v1.keras.datasets.boston_housing.load_data
tf.keras.datasets.boston_housing.load_data(
path='boston_housing.npz', test_split=0.2, seed=113
)
This is a dataset taken from the StatLib library which is maintained at Carnegie Mellon University. Samples contain 13 attributes of houses at different locations around the Boston suburbs in the late 1970s. Targets are the median values of the houses at a location (in k$). The attributes themselves are defined in the StatLib website.
Arguments
path path where to cache the dataset locally (relative to ~/.keras/datasets).
test_split fraction of the data to reserve as test set.
seed Random seed for shuffling the data before computing the test split.
Returns Tuple of Numpy arrays: (x_train, y_train), (x_test, y_test). x_train, x_test: numpy arrays with shape (num_samples, 13) containing either the training samples (for x_train), or test samples (for y_train). y_train, y_test: numpy arrays of shape (num_samples,) containing the target scalars. The targets are float scalars typically between 10 and 50 that represent the home prices in k$. | |
doc_2358 | This exception is raised on all errors, such as unknown number of bytes per sample, etc. | |
doc_2359 |
Recursively add files under data_path to data_files list. Recursively add files under data_path to the list of data_files to be installed (and distributed). The data_path can be either a relative path-name, or an absolute path-name, or a 2-tuple where the first argument shows where in the install directory the data directory should be installed to. Parameters
data_pathseq or str
Argument can be either 2-sequence (<datadir suffix>, <path to data directory>) path to data directory where python datadir suffix defaults to package dir. Notes Rules for installation paths: foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar
(gun, foo/bar) -> parent/gun
foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b
(gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun
(gun/*, foo/*) -> parent/gun/a, parent/gun/b
/foo/bar -> (bar, /foo/bar) -> parent/bar
(gun, /foo/bar) -> parent/gun
(fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar
Examples For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat: >>> self.add_data_dir('fun')
>>> self.add_data_dir(('sun', 'fun'))
>>> self.add_data_dir(('gun', '/full/path/to/fun'))
Will install data-files to the locations: <package install directory>/
fun/
foo.dat
bar/
car.dat
sun/
foo.dat
bar/
car.dat
gun/
foo.dat
car.dat | |
doc_2360 | See Migration guide for more details. tf.compat.v1.raw_ops.BatchIFFT2D
tf.raw_ops.BatchIFFT2D(
input, name=None
)
Args
input A Tensor of type complex64.
name A name for the operation (optional).
Returns A Tensor of type complex64. | |
doc_2361 | A page representing an individual object. If the object has a date value in the future, the view will throw a 404 error by default, unless you set allow_future to True. Ancestors (MRO) django.views.generic.detail.SingleObjectTemplateResponseMixin django.views.generic.base.TemplateResponseMixin django.views.generic.dates.BaseDateDetailView django.views.generic.dates.YearMixin django.views.generic.dates.MonthMixin django.views.generic.dates.DayMixin django.views.generic.dates.DateMixin django.views.generic.detail.BaseDetailView django.views.generic.detail.SingleObjectMixin django.views.generic.base.View Context Includes the single object associated with the model specified in the DateDetailView. Notes Uses a default template_name_suffix of _detail. Example myapp/urls.py: from django.urls import path
from django.views.generic.dates import DateDetailView
urlpatterns = [
path('<int:year>/<str:month>/<int:day>/<int:pk>/',
DateDetailView.as_view(model=Article, date_field="pub_date"),
name="archive_date_detail"),
]
Example myapp/article_detail.html: <h1>{{ object.title }}</h1> | |
doc_2362 |
Return whether arbitrary affine transformations in draw_image() are supported (True for most vector backends). | |
doc_2363 |
Return the alpha value used for blending - not supported on all backends. | |
doc_2364 |
Performs a single optimization step. This will call torch.optim.Optimizer.step() on each worker containing parameters to be optimized, and will block until all workers return. The provided context_id will be used to retrieve the corresponding context that contains the gradients that should be applied to the parameters. Parameters
context_id – the autograd context id for which we should run the optimizer step. | |
doc_2365 |
Returns a true division of the inputs, element-wise. Unlike ‘floor division’, true division adjusts the output type to present the best answer, regardless of input types. Parameters
x1array_like
Dividend array.
x2array_like
Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs
For other keyword-only arguments, see the ufunc docs. Returns
outndarray or scalar
This is a scalar if both x1 and x2 are scalars. Notes In Python, // is the floor division operator and / the true division operator. The true_divide(x1, x2) function is equivalent to true division in Python. Examples >>> x = np.arange(5)
>>> np.true_divide(x, 4)
array([ 0. , 0.25, 0.5 , 0.75, 1. ])
>>> x/4
array([ 0. , 0.25, 0.5 , 0.75, 1. ])
>>> x//4
array([0, 0, 0, 0, 1])
The / operator can be used as a shorthand for np.true_divide on ndarrays. >>> x = np.arange(5)
>>> x / 4
array([0. , 0.25, 0.5 , 0.75, 1. ]) | |
doc_2366 | See Migration guide for more details. tf.compat.v1.mlir.experimental.convert_graph_def
tf.mlir.experimental.convert_graph_def(
graph_def, pass_pipeline='tf-standard-pipeline'
)
This API is only intended for inspecting the internals of TensorFlow and the string returned is at the moment intended for debugging purposes.
Args
graph_def An object of type graph_pb2.GraphDef or a textual proto representation of a valid GraphDef.
pass_pipeline A textual description of an MLIR Pass Pipeline to run on the module, see MLIR documentation for the textual pass pipeline syntax.
Returns A textual representation of the MLIR module corresponding to the graphdef.
Raises
InvalidArgumentError if graph_def is invalid or cannot be converted to MLIR. | |
doc_2367 |
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly. | |
doc_2368 | New in Django 4.0. The render method is called by __str__ as well as the as_p(), as_ul(), and as_table() methods. All arguments are optional and will default to:
template_name: template_name
context: Value returned by get_context()
renderer: Value returned by renderer | |
doc_2369 | Returns a URL string or bytes depending on the type of the information stored. This is just a convenience function for calling url_unparse() for this URL. Return type
str | |
doc_2370 |
Set memory fraction for a process. The fraction is used to limit an caching allocator to allocated memory on a CUDA device. The allowed value equals the total visible memory multiplied fraction. If trying to allocate more than the allowed value in a process, will raise an out of memory error in allocator. Parameters
fraction (float) – Range: 0~1. Allowed memory equals total_memory * fraction.
device (torch.device or int, optional) – selected device. If it is None the default CUDA device is used. Note In general, the total available free memory is less than the total capacity. | |
doc_2371 |
Return the minimum of the values over the requested axis. If you want the index of the minimum, use idxmin. This is the equivalent of the numpy.ndarray method argmin. Parameters
axis:{index (0), columns (1)}
Axis for the function to be applied on.
skipna:bool, default True
Exclude NA/null values when computing the result.
level:int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series.
numeric_only:bool, default None
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. **kwargs
Additional keyword arguments to be passed to the function. Returns
Series or DataFrame (if level specified)
See also Series.sum
Return the sum. Series.min
Return the minimum. Series.max
Return the maximum. Series.idxmin
Return the index of the minimum. Series.idxmax
Return the index of the maximum. DataFrame.sum
Return the sum over the requested axis. DataFrame.min
Return the minimum over the requested axis. DataFrame.max
Return the maximum over the requested axis. DataFrame.idxmin
Return the index of the minimum over the requested axis. DataFrame.idxmax
Return the index of the maximum over the requested axis. Examples
>>> idx = pd.MultiIndex.from_arrays([
... ['warm', 'warm', 'cold', 'cold'],
... ['dog', 'falcon', 'fish', 'spider']],
... names=['blooded', 'animal'])
>>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx)
>>> s
blooded animal
warm dog 4
falcon 2
cold fish 0
spider 8
Name: legs, dtype: int64
>>> s.min()
0 | |
doc_2372 |
Convert coefficient matrix to sparse format. Converts the coef_ member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation. The intercept_ member is not converted. Returns
self
Fitted estimator. Notes For non-sparse models, i.e. when there are not many zeros in coef_, this may actually increase memory usage, so use this method with care. A rule of thumb is that the number of zero elements, which can be computed with (coef_ == 0).sum(), must be more than 50% for this to provide significant benefits. After calling this method, further fitting with the partial_fit method (if any) will not work until you call densify. | |
doc_2373 |
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible(). Parameters
bbool | |
doc_2374 | tf.feature_column.make_parse_example_spec(
feature_columns
)
The returned dictionary can be used as arg 'features' in tf.io.parse_example. Typical usage example: # Define features and transformations
feature_a = tf.feature_column.categorical_column_with_vocabulary_file(...)
feature_b = tf.feature_column.numeric_column(...)
feature_c_bucketized = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("feature_c"), ...)
feature_a_x_feature_c = tf.feature_column.crossed_column(
columns=["feature_a", feature_c_bucketized], ...)
feature_columns = set(
[feature_b, feature_c_bucketized, feature_a_x_feature_c])
features = tf.io.parse_example(
serialized=serialized_examples,
features=tf.feature_column.make_parse_example_spec(feature_columns))
For the above example, make_parse_example_spec would return the dict: {
"feature_a": parsing_ops.VarLenFeature(tf.string),
"feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32),
"feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32)
}
Args
feature_columns An iterable containing all feature columns. All items should be instances of classes derived from FeatureColumn.
Returns A dict mapping each feature key to a FixedLenFeature or VarLenFeature value.
Raises
ValueError If any of the given feature_columns is not a FeatureColumn instance. | |
doc_2375 |
template_name: 'django/forms/widgets/select_date.html'
Wrapper around three Select widgets: one each for month, day, and year. Takes several optional arguments:
years
An optional list/tuple of years to use in the “year” select box. The default is a list containing the current year and the next 9 years.
months
An optional dict of months to use in the “months” select box. The keys of the dict correspond to the month number (1-indexed) and the values are the displayed months: MONTHS = {
1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'),
5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'),
9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec')
}
empty_label
If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label', 'month_label', 'day_label'). # A custom empty label with string
field1 = forms.DateField(widget=SelectDateWidget(empty_label="Nothing"))
# A custom empty label with tuple
field1 = forms.DateField(
widget=SelectDateWidget(
empty_label=("Choose Year", "Choose Month", "Choose Day"),
),
) | |
doc_2376 | Set the flags specified by flags and unset all others. Parameter flags should be the concatenation in any order of zero or more occurrences of each of 'R', 'O', 'D', 'F', and 'A'. | |
doc_2377 | Like erase(), but also cause the whole window to be repainted upon next call to refresh(). | |
doc_2378 |
Return a view of the array with axis1 and axis2 interchanged. Refer to numpy.swapaxes for full documentation. See also numpy.swapaxes
equivalent function | |
doc_2379 | Pause the receiving end of the transport. No data will be passed to the protocol’s protocol.data_received() method until resume_reading() is called. Changed in version 3.7: The method is idempotent, i.e. it can be called when the transport is already paused or closed. | |
doc_2380 | os.O_RSYNC
os.O_SYNC
os.O_NDELAY
os.O_NONBLOCK
os.O_NOCTTY
os.O_CLOEXEC
The above constants are only available on Unix. Changed in version 3.3: Add O_CLOEXEC constant. | |
doc_2381 |
Predict probability for each possible outcome. Compute the probability estimates for each single sample in X and each possible outcome seen during training (categorical distribution). Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
probabilitiesndarray of shape (n_samples, n_classes)
Normalized probability distributions across class labels. | |
doc_2382 | Accept: application/json
Might receive an error response indicating that the DELETE method is not allowed on that resource: HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
Content-Length: 42
{"detail": "Method 'DELETE' not allowed."}
Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY setting. An example validation error might look like this: HTTP/1.1 400 Bad Request
Content-Type: application/json
Content-Length: 94
{"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}
Custom exception handling You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so: HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
Content-Length: 62
{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
In order to alter the style of the response, you could write the following custom exception handler: from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
return response
The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view']. The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example: REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework: REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails. API Reference APIException Signature: APIException() The base class for all exceptions raised inside an APIView class or @api_view. To provide a custom exception, subclass APIException and set the .status_code, .default_detail, and default_code attributes on the class. For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so: from rest_framework.exceptions import APIException
class ServiceUnavailable(APIException):
status_code = 503
default_detail = 'Service temporarily unavailable, try again later.'
default_code = 'service_unavailable'
Inspecting API exceptions There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project. The available attributes and methods are:
.detail - Return the textual description of the error.
.get_codes() - Return the code identifier of the error.
.get_full_details() - Return both the textual description and the code identifier. In most cases the error detail will be a simple item: >>> print(exc.detail)
You do not have permission to perform this action.
>>> print(exc.get_codes())
permission_denied
>>> print(exc.get_full_details())
{'message':'You do not have permission to perform this action.','code':'permission_denied'}
In the case of validation errors the error detail will be either a list or dictionary of items: >>> print(exc.detail)
{"name":"This field is required.","age":"A valid integer is required."}
>>> print(exc.get_codes())
{"name":"required","age":"invalid"}
>>> print(exc.get_full_details())
{"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}
ParseError Signature: ParseError(detail=None, code=None) Raised if the request contains malformed data when accessing request.data. By default this exception results in a response with the HTTP status code "400 Bad Request". AuthenticationFailed Signature: AuthenticationFailed(detail=None, code=None) Raised when an incoming request includes incorrect authentication. By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details. NotAuthenticated Signature: NotAuthenticated(detail=None, code=None) Raised when an unauthenticated request fails the permission checks. By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details. PermissionDenied Signature: PermissionDenied(detail=None, code=None) Raised when an authenticated request fails the permission checks. By default this exception results in a response with the HTTP status code "403 Forbidden". NotFound Signature: NotFound(detail=None, code=None) Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404 Django exception. By default this exception results in a response with the HTTP status code "404 Not Found". MethodNotAllowed Signature: MethodNotAllowed(method, detail=None, code=None) Raised when an incoming request occurs that does not map to a handler method on the view. By default this exception results in a response with the HTTP status code "405 Method Not Allowed". NotAcceptable Signature: NotAcceptable(detail=None, code=None) Raised when an incoming request occurs with an Accept header that cannot be satisfied by any of the available renderers. By default this exception results in a response with the HTTP status code "406 Not Acceptable". UnsupportedMediaType Signature: UnsupportedMediaType(media_type, detail=None, code=None) Raised if there are no parsers that can handle the content type of the request data when accessing request.data. By default this exception results in a response with the HTTP status code "415 Unsupported Media Type". Throttled Signature: Throttled(wait=None, detail=None, code=None) Raised when an incoming request fails the throttling checks. By default this exception results in a response with the HTTP status code "429 Too Many Requests". ValidationError Signature: ValidationError(detail, code=None) The ValidationError exception is slightly different from the other APIException classes: The detail argument is mandatory, not optional. The detail argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the validate() method of a serializer. For example. raise serializers.ValidationError({'name': 'Please enter a valid name.'})
By convention you should import the serializers module and use a fully qualified ValidationError style, in order to differentiate it from Django's built-in validation error. For example. raise serializers.ValidationError('This field must be an integer value.')
The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument: serializer.is_valid(raise_exception=True)
The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. By default this exception results in a response with the HTTP status code "400 Bad Request". Generic Error Views Django REST Framework provides two error views suitable for providing generic JSON 500 Server Error and 400 Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an API-only application.) Use these as per Django's Customizing error views documentation. rest_framework.exceptions.server_error Returns a response with status code 500 and application/json content type. Set as handler500: handler500 = 'rest_framework.exceptions.server_error'
rest_framework.exceptions.bad_request Returns a response with status code 400 and application/json content type. Set as handler400: handler400 = 'rest_framework.exceptions.bad_request'
exceptions.py | |
doc_2383 | Return the symbol’s name. | |
doc_2384 | See torch.gather() | |
doc_2385 | nnn should be a three-digit HTTP error code. This method is also not defined in BaseHandler, but will be called, if it exists, on an instance of a subclass, when an HTTP error with code nnn occurs. Subclasses should override this method to handle specific HTTP errors. Arguments, return values and exceptions raised should be the same as for http_error_default(). | |
doc_2386 |
Return a list of CPU features that required to be detected sorted from the lowest to highest interest. | |
doc_2387 |
Alias for set_linestyle. | |
doc_2388 |
Return the cube-root of an array, element-wise. New in version 1.10.0. Parameters
xarray_like
The values whose cube-roots are required.
outndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs
For other keyword-only arguments, see the ufunc docs. Returns
yndarray
An array of the same shape as x, containing the cube cube-root of each element in x. If out was provided, y is a reference to it. This is a scalar if x is a scalar. Examples >>> np.cbrt([1,8,27])
array([ 1., 2., 3.]) | |
doc_2389 | See torch.isreal() | |
doc_2390 | Test whether filename matches pattern, returning True or False; the comparison is case-sensitive and does not apply os.path.normcase(). | |
doc_2391 |
Get the Path of the polygon. | |
doc_2392 | Returns selected language’s BiDi layout:
False = left-to-right layout
True = right-to-left layout | |
doc_2393 |
Return a new path resampled to length N x steps. Codes other than LINETO are not handled correctly. | |
doc_2394 | Reference pixel red into a 2d array. pixels_red (Surface) -> array Create a new 2D array that directly references the red values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied. This can only work on 24-bit or 32-bit Surfaces. The Surface this array references will remain locked for the lifetime of the array. | |
doc_2395 | See Migration guide for more details. tf.compat.v1.diag_part, tf.compat.v1.linalg.tensor_diag_part
tf.linalg.tensor_diag_part(
input, name=None
)
This operation returns a tensor with the diagonal part of the input. The diagonal part is computed as follows: Assume input has dimensions [D1,..., Dk, D1,..., Dk], then the output is a tensor of rank k with dimensions [D1,..., Dk] where: diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]. For a rank 2 tensor, linalg.diag_part and linalg.tensor_diag_part produce the same result. For rank 3 and higher, linalg.diag_part extracts the diagonal of each inner-most matrix in the tensor. An example where they differ is given below.
x = [[[[1111,1112],[1121,1122]],
[[1211,1212],[1221,1222]]],
[[[2111, 2112], [2121, 2122]],
[[2211, 2212], [2221, 2222]]]
]
tf.linalg.tensor_diag_part(x)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1111, 1212],
[2121, 2222]], dtype=int32)>
tf.linalg.diag_part(x).shape
TensorShape([2, 2, 2])
Args
input A Tensor with rank 2k.
name A name for the operation (optional).
Returns A Tensor containing diagonals of input. Has the same type as input, and rank k. | |
doc_2396 |
Transform X using one-hot encoding. Parameters
Xarray-like, shape [n_samples, n_features]
The data to encode. Returns
X_outsparse matrix if sparse=True else a 2-d array
Transformed input. | |
doc_2397 | Dump the class data as a string in the format of a netrc file. (This discards comments and may reorder the entries.) | |
doc_2398 |
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly. | |
doc_2399 | This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behavior is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the format ‘%Y-%m-%d %H:%M:%S,uuu’ is used, where the uuu part is a millisecond value and the other letters are as per the time.strftime() documentation. An example time in this format is 2003-01-23 00:29:50,411. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the converter attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the converter attribute in the Formatter class. Changed in version 3.3: Previously, the default format was hard-coded as in this example: 2010-09-06 22:38:15,292 where the part before the comma is handled by a strptime format string ('%Y-%m-%d %H:%M:%S'), and the part after the comma is a millisecond value. Because strptime does not have a format placeholder for milliseconds, the millisecond value is appended using another format string, '%s,%03d' — and both of these format strings have been hardcoded into this method. With the change, these strings are defined as class-level attributes which can be overridden at the instance level when desired. The names of the attributes are default_time_format (for the strptime format string) and default_msec_format (for appending the millisecond value). Changed in version 3.9: The default_msec_format can be None. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.