_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_27800 | tf.compat.v1.distribute.Strategy(
extended
)
See the guide for overview and examples.
Note: Not all tf.distribute.Strategy implementations currently support TensorFlow's partitioned variables (where a single variable is split across multiple devices) at this time.
Attributes
cluster_resolver Returns the cluster resolver associated with this strategy. In general, when using a multi-worker tf.distribute strategy such as tf.distribute.experimental.MultiWorkerMirroredStrategy or tf.distribute.TPUStrategy(), there is a tf.distribute.cluster_resolver.ClusterResolver associated with the strategy used, and such an instance is returned by this property. Strategies that intend to have an associated tf.distribute.cluster_resolver.ClusterResolver must set the relevant attribute, or override this property; otherwise, None is returned by default. Those strategies should also provide information regarding what is returned by this property. Single-worker strategies usually do not have a tf.distribute.cluster_resolver.ClusterResolver, and in those cases this property will return None. The tf.distribute.cluster_resolver.ClusterResolver may be useful when the user needs to access information such as the cluster spec, task type or task id. For example,
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"],
'ps': ["localhost:34567"]
},
'task': {'type': 'worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set this
# as a worker above, this block will run on this particular instance.
elif strategy.cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. Since we
# set this as a worker above, this block will not run on this particular
# instance.
For more information, please see tf.distribute.cluster_resolver.ClusterResolver's API docstring.
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_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,).
experimental_make_numpy_dataset View source
experimental_make_numpy_dataset(
numpy_input, session=None
)
Makes a tf.data.Dataset for input provided via a numpy array. This avoids adding numpy_input as a large constant in the graph, and copies the data to the machine or machines that will be processing the input. Note that you will likely need to use tf.distribute.Strategy.experimental_distribute_dataset with the returned dataset to further distribute it with the strategy. Example: numpy_input = np.ones([10], dtype=np.float32)
dataset = strategy.experimental_make_numpy_dataset(numpy_input)
dist_dataset = strategy.experimental_distribute_dataset(dataset)
Args
numpy_input A nest of NumPy input arrays that will be converted into a dataset. Note that lists of Numpy arrays are stacked, as that is normal tf.data.Dataset behavior.
session (TensorFlow v1.x graph execution only) A session used for initialization.
Returns A tf.data.Dataset representing numpy_input.
experimental_run View source
experimental_run(
fn, input_iterator=None
)
Runs ops in fn on each replica, with inputs from input_iterator. DEPRECATED: This method is not available in TF 2.x. Please switch to using run instead. When eager execution is enabled, executes ops specified by fn on each replica. Otherwise, builds a graph to execute the ops on each replica. Each replica will take a single, different input from the inputs provided by one get_next call on the input iterator. fn may call tf.distribute.get_replica_context() to access members such as replica_id_in_sync_group. Key Point: Depending on the tf.distribute.Strategy implementation being used, and whether eager execution is enabled, fn may be called one or more times (once for each replica).
Args
fn The function to run. The inputs to the function must match the outputs of input_iterator.get_next(). The output must be a tf.nest of Tensors.
input_iterator (Optional) input iterator from which the inputs are taken.
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 PerReplica (if the values are unsynchronized), Mirrored (if the values are kept in sync), or Tensor (if running on a single replica).
make_dataset_iterator View source
make_dataset_iterator(
dataset
)
Makes an iterator for input provided via dataset. DEPRECATED: This method is not available in TF 2.x. Data from the given dataset will be distributed evenly across all the compute replicas. We will assume that the input dataset is batched by the global batch size. With this assumption, we will make a best effort to divide each batch across all the replicas (one or more workers). If this effort fails, an error will be thrown, and the user should instead use make_input_fn_iterator which provides more control to the user, and does not try to divide a batch across replicas. The user could also use make_input_fn_iterator if they want to customize which input is fed to which replica/worker etc.
Args
dataset tf.data.Dataset that will be distributed evenly across all replicas.
Returns An tf.distribute.InputIterator which returns inputs for each step of the computation. User should call initialize on the returned iterator.
make_input_fn_iterator View source
make_input_fn_iterator(
input_fn, replication_mode=tf.distribute.InputReplicationMode.PER_WORKER
)
Returns an iterator split across replicas created from an input function. DEPRECATED: This method is not available in TF 2.x. The input_fn should take an tf.distribute.InputContext object where information about batching and input sharding can be accessed: def input_fn(input_context):
batch_size = input_context.get_per_replica_batch_size(global_batch_size)
d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)
return d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
with strategy.scope():
iterator = strategy.make_input_fn_iterator(input_fn)
replica_results = strategy.experimental_run(replica_fn, iterator)
The tf.data.Dataset returned by input_fn should have a per-replica batch size, which may be computed using input_context.get_per_replica_batch_size.
Args
input_fn A function taking a tf.distribute.InputContext object and returning a tf.data.Dataset.
replication_mode an enum value of tf.distribute.InputReplicationMode. Only PER_WORKER is supported currently, which means there will be a single call to input_fn per worker. Replicas will dequeue from the local tf.data.Dataset on their worker.
Returns An iterator object that should first be .initialize()-ed. It may then either be passed to strategy.experimental_run() or you can iterator.get_next() to get the next value to pass to strategy.extended.call_for_each_replica().
reduce View source
reduce(
reduce_op, value, axis=None
)
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.
update_config_proto View source
update_config_proto(
config_proto
)
Returns a copy of config_proto modified for use with this strategy. DEPRECATED: This method is not available in TF 2.x. The updated config has something needed to run a strategy, e.g. configuration to run collective ops, or device filters to improve distributed training performance.
Args
config_proto a tf.ConfigProto object.
Returns The updated copy of the config_proto. | |
doc_27801 |
Returns
transformTransform
The transform used for drawing y-axis labels, which will add pad_points of padding (in points) between the axis and the label. The x-direction is in axis coordinates and the y-direction is in data coordinates
valign{'center', 'top', 'bottom', 'baseline', 'center_baseline'}
The text vertical alignment.
halign{'center', 'left', 'right'}
The text horizontal alignment. Notes This transformation is primarily used by the Axis class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations. | |
doc_27802 | tf.eigvals
tf.linalg.eigvals(
tensor, name=None
)
Note: If your program backpropagates through this function, you should replace it with a call to tf.linalg.eig (possibly ignoring the second output) to avoid computing the eigen decomposition twice. This is because the eigenvectors are used to compute the gradient w.r.t. the eigenvalues. See _SelfAdjointEigV2Grad in linalg_grad.py.
Args
tensor Tensor of shape [..., N, N].
name string, optional name of the operation.
Returns
e Eigenvalues. Shape is [..., N]. The vector e[..., :] contains the N eigenvalues of tensor[..., :, :]. | |
doc_27803 |
Univariate linear regression tests. Linear model for testing the individual effect of each of many regressors. This is a scoring function to be used in a feature selection procedure, not a free standing feature selection procedure. This is done in 2 steps: The correlation between each regressor and the target is computed, that is, ((X[:, i] - mean(X[:, i])) * (y - mean_y)) / (std(X[:, i]) * std(y)). It is converted to an F score then to a p-value. For more on usage see the User Guide. Parameters
X{array-like, sparse matrix} shape = (n_samples, n_features)
The set of regressors that will be tested sequentially.
yarray of shape(n_samples).
The data matrix
centerbool, default=True
If true, X and y will be centered. Returns
Farray, shape=(n_features,)
F values of features.
pvalarray, shape=(n_features,)
p-values of F-scores. See also
mutual_info_regression
Mutual information for a continuous target.
f_classif
ANOVA F-value between label/feature for classification tasks.
chi2
Chi-squared stats of non-negative features for classification tasks.
SelectKBest
Select features based on the k highest scores.
SelectFpr
Select features based on a false positive rate test.
SelectFdr
Select features based on an estimated false discovery rate.
SelectFwe
Select features based on family-wise error rate.
SelectPercentile
Select features based on percentile of the highest scores. | |
doc_27804 |
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_27805 |
Generate missing values indicator for X. Parameters
X{array-like, sparse matrix}, shape (n_samples, n_features)
The input data to complete. Returns
Xt{ndarray or sparse matrix}, shape (n_samples, n_features) or (n_samples, n_features_with_missing)
The missing indicator for input data. The data type of Xt will be boolean. | |
doc_27806 |
Getter for the precision matrix. Returns
precision_array-like of shape (n_features, n_features)
The precision matrix associated to the current covariance object. | |
doc_27807 | Computes the solution x to the matrix equation matmul(input, x) = other with a square matrix, or batches of such matrices, input and one or more right-hand side vectors other. If input is batched and other is not, then other is broadcast to have the same batch dimensions as input. The resulting tensor has the same shape as the (possibly broadcast) other. Supports input of float, double, cfloat and cdouble dtypes. Note If input is a non-square or non-invertible matrix, or a batch containing non-square matrices or one or more non-invertible matrices, then a RuntimeError will be thrown. Note When given inputs on a CUDA device, this function synchronizes that device with the CPU. Parameters
input (Tensor) – the square n×nn \times n matrix or the batch of such matrices of size (∗,n,n)(*, n, n) where * is one or more batch dimensions.
other (Tensor) – right-hand side tensor of shape (∗,n)(*, n) or (∗,n,k)(*, n, k) , where kk is the number of right-hand side vectors. Keyword Arguments
out (Tensor, optional) – The output tensor. Ignored if None. Default: None Examples: >>> A = torch.eye(3)
>>> b = torch.randn(3)
>>> x = torch.linalg.solve(A, b)
>>> torch.allclose(A @ x, b)
True
Batched input: >>> A = torch.randn(2, 3, 3)
>>> b = torch.randn(3, 1)
>>> x = torch.linalg.solve(A, b)
>>> torch.allclose(A @ x, b)
True
>>> b = torch.rand(3) # b is broadcast internally to (*A.shape[:-2], 3)
>>> x = torch.linalg.solve(A, b)
>>> x.shape
torch.Size([2, 3])
>>> Ax = A @ x.unsqueeze(-1)
>>> torch.allclose(Ax, b.unsqueeze(-1).expand_as(Ax))
True | |
doc_27808 |
Align the xlabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row. Parameters
axslist of Axes
Optional list of (or ndarray) Axes to align the xlabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_ylabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with rotated xtick labels: fig, axs = plt.subplots(1, 2)
for tick in axs[0].get_xticklabels():
tick.set_rotation(55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels() | |
doc_27809 | A message with mbox-specific behaviors. Parameter message has the same meaning as with the Message constructor. Messages in an mbox mailbox are stored together in a single file. The sender’s envelope address and the time of delivery are typically stored in a line beginning with “From ” that is used to indicate the start of a message, though there is considerable variation in the exact format of this data among mbox implementations. Flags that indicate the state of the message, such as whether it has been read or marked as important, are typically stored in Status and X-Status headers. Conventional flags for mbox messages are as follows:
Flag Meaning Explanation
R Read Read
O Old Previously detected by MUA
D Deleted Marked for subsequent deletion
F Flagged Marked as important
A Answered Replied to The “R” and “O” flags are stored in the Status header, and the “D”, “F”, and “A” flags are stored in the X-Status header. The flags and headers typically appear in the order mentioned. mboxMessage instances offer the following methods:
get_from()
Return a string representing the “From ” line that marks the start of the message in an mbox mailbox. The leading “From ” and the trailing newline are excluded.
set_from(from_, time_=None)
Set the “From ” line to from_, which should be specified without a leading “From ” or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a time.struct_time instance, a tuple suitable for passing to time.strftime(), or True (to use time.gmtime()).
get_flags()
Return a string specifying the flags that are currently set. If the message complies with the conventional format, the result is the concatenation in the following order of zero or one occurrence of each of 'R', 'O', 'D', 'F', and 'A'.
set_flags(flags)
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'.
add_flag(flag)
Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character.
remove_flag(flag)
Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character. | |
doc_27810 | Returns a new tensor with each of the elements of input rounded to the closest integer. Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([ 0.9920, 0.6077, 0.9734, -1.0362])
>>> torch.round(a)
tensor([ 1., 1., 1., -1.]) | |
doc_27811 | A base view for displaying a list of objects. It is not intended to be used directly, but rather as a parent class of the django.views.generic.list.ListView or other views representing lists of objects. Ancestors (MRO) This view inherits methods and attributes from the following views: django.views.generic.list.MultipleObjectMixin django.views.generic.base.View Methods
get(request, *args, **kwargs)
Adds object_list to the context. If allow_empty is True then display an empty list. If allow_empty is False then raise a 404 error. | |
doc_27812 | returns the dimensions of the images being recorded get_size() -> (width, height) Returns the current dimensions of the images being captured by the camera. This will return the actual size, which may be different than the one specified during initialization if the camera did not support that size. | |
doc_27813 |
Bases: matplotlib.patches.BoxStyle._Base A box in the shape of a left-pointing arrow. Parameters
padfloat, default: 0.3
The amount of padding around the original box. __call__(x0, y0, width, height, mutation_size, mutation_aspect=<deprecated parameter>)[source]
Given the location and size of the box, return the path of the box around it. Parameters
x0, y0, width, heightfloat
Location and size of the box.
mutation_sizefloat
A reference scale for the mutation. Returns
Path | |
doc_27814 | Return the hyperbolic cosine of x. | |
doc_27815 |
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_27816 | Adds a response header to the headers buffer and logs the accepted request. The HTTP response line is written to the internal buffer, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively. If the server does not intend to send any other headers using the send_header() method, then send_response() should be followed by an end_headers() call. Changed in version 3.3: Headers are stored to an internal buffer and end_headers() needs to be called explicitly. | |
doc_27817 |
Estimate 2D geometric transformation parameters. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. Parameters
ttype{‘euclidean’, similarity’, ‘affine’, ‘piecewise-affine’, ‘projective’, ‘polynomial’}
Type of transform.
kwargsarray or int
Function parameters (src, dst, n, angle): NAME / TTYPE FUNCTION PARAMETERS
'euclidean' `src, `dst`
'similarity' `src, `dst`
'affine' `src, `dst`
'piecewise-affine' `src, `dst`
'projective' `src, `dst`
'polynomial' `src, `dst`, `order` (polynomial order,
default order is 2)
Also see examples below. Returns
tformGeometricTransform
Transform object containing the transformation parameters and providing access to forward and inverse transformation functions. Examples >>> import numpy as np
>>> from skimage import transform
>>> # estimate transformation parameters
>>> src = np.array([0, 0, 10, 10]).reshape((2, 2))
>>> dst = np.array([12, 14, 1, -20]).reshape((2, 2))
>>> tform = transform.estimate_transform('similarity', src, dst)
>>> np.allclose(tform.inverse(tform(src)), src)
True
>>> # warp image using the estimated transformation
>>> from skimage import data
>>> image = data.camera()
>>> warp(image, inverse_map=tform.inverse)
>>> # create transformation with explicit parameters
>>> tform2 = transform.SimilarityTransform(scale=1.1, rotation=1,
... translation=(10, 20))
>>> # unite transformations, applied in order from left to right
>>> tform3 = tform + tform2
>>> np.allclose(tform3(src), tform2(tform(src)))
True | |
doc_27818 | The format in which this field’s initial value will be displayed. | |
doc_27819 |
Return whether x is in the open (x0, x1) interval. | |
doc_27820 |
Return the line width in points. | |
doc_27821 |
alias of numpy.half | |
doc_27822 | tf.compat.v1.create_partitioned_variables(
shape, slicing, initializer, dtype=tf.dtypes.float32, trainable=True,
collections=None, name=None, reuse=None
)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.get_variable with a partitioner set. Currently only one dimension of the full variable can be sliced, and the full variable can be reconstructed by the concatenation of the returned list along that dimension.
Args
shape List of integers. The shape of the full variable.
slicing List of integers. How to partition the variable. Must be of the same length as shape. Each value indicate how many slices to create in the corresponding dimension. Presently only one of the values can be more than 1; that is, the variable can only be sliced along one dimension. For convenience, The requested number of partitions does not have to divide the corresponding dimension evenly. If it does not, the shapes of the partitions are incremented by 1 starting from partition 0 until all slack is absorbed. The adjustment rules may change in the future, but as you can save/restore these variables with different slicing specifications this should not be a problem.
initializer A Tensor of shape shape or a variable initializer function. If a function, it will be called once for each slice, passing the shape and data type of the slice as parameters. The function must return a tensor with the same shape as the slice.
dtype Type of the variables. Ignored if initializer is a Tensor.
trainable If True also add all the variables to the graph collection GraphKeys.TRAINABLE_VARIABLES.
collections List of graph collections keys to add the variables to. Defaults to [GraphKeys.GLOBAL_VARIABLES].
name Optional name for the full variable. Defaults to "PartitionedVariable" and gets uniquified automatically.
reuse Boolean or None; if True and name is set, it would reuse previously created variables. if False it will create new variables. if None, it would inherit the parent scope reuse.
Returns A list of Variables corresponding to the slicing.
Raises
ValueError If any of the arguments is malformed. | |
doc_27823 | Returns the indices of the buckets to which each value in the input belongs, where the boundaries of the buckets are set by boundaries. Return a new tensor with the same size as input. If right is False (default), then the left boundary is closed. More formally, the returned index satisfies the following rules:
right returned index satisfies
False boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]
True boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i] Parameters
input (Tensor or Scalar) – N-D tensor or a Scalar containing the search value(s).
boundaries (Tensor) – 1-D tensor, must contain a monotonically increasing sequence. Keyword Arguments
out_int32 (bool, optional) – indicate the output data type. torch.int32 if True, torch.int64 otherwise. Default value is False, i.e. default output data type is torch.int64.
right (bool, optional) – if False, return the first suitable location that is found. If True, return the last such index. If no suitable index found, return 0 for non-numerical value (eg. nan, inf) or the size of boundaries (one pass the last index). In other words, if False, gets the lower bound index for each value in input from boundaries. If True, gets the upper bound index instead. Default value is False.
out (Tensor, optional) – the output tensor, must be the same size as input if provided. Example: >>> boundaries = torch.tensor([1, 3, 5, 7, 9])
>>> boundaries
tensor([1, 3, 5, 7, 9])
>>> v = torch.tensor([[3, 6, 9], [3, 6, 9]])
>>> v
tensor([[3, 6, 9],
[3, 6, 9]])
>>> torch.bucketize(v, boundaries)
tensor([[1, 3, 4],
[1, 3, 4]])
>>> torch.bucketize(v, boundaries, right=True)
tensor([[2, 3, 5],
[2, 3, 5]]) | |
doc_27824 |
Get whether axis ticks and gridlines are above or below most artists. Returns
bool or 'line'
See also set_axisbelow | |
doc_27825 | 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_27826 | Create and return a TarInfo object from string buffer buf. Raises HeaderError if the buffer is invalid. | |
doc_27827 | See Migration guide for more details. tf.compat.v1.io.parse_single_sequence_example, tf.compat.v1.parse_single_sequence_example
tf.io.parse_single_sequence_example(
serialized, context_features=None, sequence_features=None, example_name=None,
name=None
)
Parses a single serialized SequenceExample proto given in serialized. This op parses a serialized sequence example into a tuple of dictionaries, each mapping keys to Tensor and SparseTensor objects. The first dictionary contains mappings for keys appearing in context_features, and the second dictionary contains mappings for keys appearing in sequence_features. At least one of context_features and sequence_features must be provided and non-empty. The context_features keys are associated with a SequenceExample as a whole, independent of time / frame. In contrast, the sequence_features keys provide a way to access variable-length data within the FeatureList section of the SequenceExample proto. While the shapes of context_features values are fixed with respect to frame, the frame dimension (the first dimension) of sequence_features values may vary between SequenceExample protos, and even between feature_list keys within the same SequenceExample. context_features contains VarLenFeature, RaggedFeature, and FixedLenFeature objects. Each VarLenFeature is mapped to a SparseTensor; each RaggedFeature is mapped to a RaggedTensor; and each FixedLenFeature is mapped to a Tensor, of the specified type, shape, and default value. sequence_features contains VarLenFeature, RaggedFeature, and FixedLenSequenceFeature objects. Each VarLenFeature is mapped to a SparseTensor; each RaggedFeature is mapped to a RaggedTensor; and each FixedLenSequenceFeature is mapped to a Tensor, each of the specified type. The shape will be (T,) + df.dense_shape for FixedLenSequenceFeature df, where T is the length of the associated FeatureList in the SequenceExample. For instance, FixedLenSequenceFeature([]) yields a scalar 1-D Tensor of static shape [None] and dynamic shape [T], while FixedLenSequenceFeature([k]) (for int k >= 1) yields a 2-D matrix Tensor of static shape [None, k] and dynamic shape [T, k]. Each SparseTensor corresponding to sequence_features represents a ragged vector. Its indices are [time, index], where time is the FeatureList entry and index is the value's index in the list of values associated with that time. FixedLenFeature entries with a default_value and FixedLenSequenceFeature entries with allow_missing=True are optional; otherwise, we will fail if that Feature or FeatureList is missing from any example in serialized. example_name may contain a descriptive name for the corresponding serialized proto. This may be useful for debugging purposes, but it has no effect on the output. If not None, example_name must be a scalar. Note that the batch version of this function, tf.parse_sequence_example, is written for better memory efficiency and will be faster on large SequenceExamples.
Args
serialized A scalar (0-D Tensor) of type string, a single binary serialized SequenceExample proto.
context_features A dict mapping feature keys to FixedLenFeature or VarLenFeature or RaggedFeature values. These features are associated with a SequenceExample as a whole.
sequence_features A dict mapping feature keys to FixedLenSequenceFeature or VarLenFeature or RaggedFeature values. These features are associated with data within the FeatureList section of the SequenceExample proto.
example_name A scalar (0-D Tensor) of strings (optional), the name of the serialized proto.
name A name for this operation (optional).
Returns A tuple of two dicts, each mapping keys to Tensors and SparseTensors and RaggedTensors. The first dict contains the context key/values. The second dict contains the feature_list key/values.
Raises
ValueError if any feature is invalid. | |
doc_27828 | See Migration guide for more details. tf.compat.v1.raw_ops.Cos
tf.raw_ops.Cos(
x, name=None
)
Given an input tensor, this function computes cosine of every element in the tensor. Input range is (-inf, inf) and output range is [-1,1]. If input lies outside the boundary, nan is returned. x = tf.constant([-float("inf"), -9, -0.5, 1, 1.2, 200, 10000, float("inf")])
tf.math.cos(x) ==> [nan -0.91113025 0.87758255 0.5403023 0.36235774 0.48718765 -0.95215535 nan]
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, complex64, complex128.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x. | |
doc_27829 | Return True if a core dump was generated for the process, otherwise return False. This function should be employed only if WIFSIGNALED() is true. Availability: Unix. | |
doc_27830 |
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values. | |
doc_27831 | See Migration guide for more details. tf.compat.v1.keras.layers.Activation
tf.keras.layers.Activation(
activation, **kwargs
)
Arguments
activation Activation function, such as tf.nn.relu, or string name of built-in activation function, such as "relu". Usage:
layer = tf.keras.layers.Activation('relu')
output = layer([-3.0, -1.0, 0.0, 2.0])
list(output.numpy())
[0.0, 0.0, 0.0, 2.0]
layer = tf.keras.layers.Activation(tf.nn.relu)
output = layer([-3.0, -1.0, 0.0, 2.0])
list(output.numpy())
[0.0, 0.0, 0.0, 2.0]
Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the batch axis) when using this layer as the first layer in a model. Output shape: Same shape as input. | |
doc_27832 |
Apply a function to 1-D slices along the given axis. Execute func1d(a, *args, **kwargs) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis. This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii, jj, and kk to a tuple of indices: Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nk):
f = func1d(arr[ii + s_[:,] + kk])
Nj = f.shape
for jj in ndindex(Nj):
out[ii + jj + kk] = f[jj]
Equivalently, eliminating the inner loop, this can be expressed as: Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nk):
out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
Parameters
func1dfunction (M,) -> (Nj…)
This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis.
axisinteger
Axis along which arr is sliced.
arrndarray (Ni…, M, Nk…)
Input array.
argsany
Additional arguments to func1d.
kwargsany
Additional named arguments to func1d. New in version 1.9.0. Returns
outndarray (Ni…, Nj…, Nk…)
The output array. The shape of out is identical to the shape of arr, except along the axis dimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of func1d. So if func1d returns a scalar out will have one fewer dimensions than arr. See also apply_over_axes
Apply a function repeatedly over multiple axes. Examples >>> def my_func(a):
... """Average first and last element of a 1-D array"""
... return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([2., 5., 8.])
For a function that returns a 1D array, the number of dimensions in outarr is the same as arr. >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
[3, 4, 9],
[2, 5, 6]])
For a function that returns a higher dimensional array, those dimensions are inserted in place of the axis dimension. >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(np.diag, -1, b)
array([[[1, 0, 0],
[0, 2, 0],
[0, 0, 3]],
[[4, 0, 0],
[0, 5, 0],
[0, 0, 6]],
[[7, 0, 0],
[0, 8, 0],
[0, 0, 9]]]) | |
doc_27833 | The maximum size (in bytes) of a core file that the current process can create. This may result in the creation of a partial core file if a larger core would be required to contain the entire process image. | |
doc_27834 |
Set the zorder threshold for rasterization for vector graphics output. All artists with a zorder below the given value will be rasterized if they support rasterization. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
zfloat or None
The zorder below which artists are rasterized. If None rasterization based on zorder is deactivated.
Examples using matplotlib.axes.Axes.set_rasterization_zorder
Rasterization for vector graphics | |
doc_27835 | See Migration guide for more details. tf.compat.v1.histogram_fixed_width
tf.histogram_fixed_width(
values, value_range, nbins=100, dtype=tf.dtypes.int32, name=None
)
Given the tensor values, this operation returns a rank 1 histogram counting the number of entries in values that fell into every bin. The bins are equal width and determined by the arguments value_range and nbins.
Args
values Numeric Tensor.
value_range Shape [2] Tensor of same dtype as values. values <= value_range[0] will be mapped to hist[0], values >= value_range[1] will be mapped to hist[-1].
nbins Scalar int32 Tensor. Number of histogram bins.
dtype dtype for returned histogram.
name A name for this operation (defaults to 'histogram_fixed_width').
Returns A 1-D Tensor holding histogram of values.
Raises
TypeError If any unsupported dtype is provided.
tf.errors.InvalidArgumentError If value_range does not satisfy value_range[0] < value_range[1]. Examples:
# Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)
nbins = 5
value_range = [0.0, 5.0]
new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15]
hist = tf.histogram_fixed_width(new_values, value_range, nbins=5)
hist.numpy()
array([2, 1, 1, 0, 2], dtype=int32) | |
doc_27836 | Replace &, <, >, ", and ' with HTML-safe sequences. None is escaped to an empty string. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead. Parameters
s (Any) – Return type
str | |
doc_27837 | tf.math.log_softmax
tf.nn.log_softmax(
logits, axis=None, name=None
)
For each batch i and class j we have logsoftmax = logits - log(reduce_sum(exp(logits), axis))
Args
logits A non-empty Tensor. Must be one of the following types: half, float32, float64.
axis The dimension softmax would be performed on. The default is -1 which indicates the last dimension.
name A name for the operation (optional).
Returns A Tensor. Has the same type as logits. Same shape as logits.
Raises
InvalidArgumentError if logits is empty or axis is beyond the last dimension of logits. | |
doc_27838 |
Forward fill the values. Parameters
limit:int, optional
Limit of how many values to fill. Returns
Series or DataFrame
Object with missing values filled. See also Series.ffill
Returns Series with minimum number of char in object. DataFrame.ffill
Object with missing values filled or None if inplace=True. Series.fillna
Fill NaN values of a Series. DataFrame.fillna
Fill NaN values of a DataFrame. | |
doc_27839 | By default, Django’s admin uses a select-box interface (<select>) for fields that are ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down. raw_id_fields is a list of fields you would like to change into an Input widget for either a ForeignKey or ManyToManyField: class BookInline(admin.TabularInline):
model = Book
raw_id_fields = ("pages",) | |
doc_27840 |
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y. | |
doc_27841 |
Return the visibility. | |
doc_27842 | 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_27843 |
Return local percentile of an image. Returns the value of the p0 lower percentile of the local greyvalue distribution. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters
image2-D array (uint8, uint16)
Input image.
selem2-D array
The neighborhood expressed as a 2-D array of 1’s and 0’s.
out2-D array (same dtype as input)
If None, a new array is allocated.
maskndarray
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
shift_x, shift_yint
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
p0float in [0, …, 1]
Set the percentile value. Returns
out2-D array (same dtype as input image)
Output image. | |
doc_27844 | Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string (''). Note This function may return invalid paths because it works a character at a time. To obtain a valid path, see commonpath(). >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'
>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'
Changed in version 3.6: Accepts a path-like object. | |
doc_27845 | See Migration guide for more details. tf.compat.v1.raw_ops.TensorArrayGradV2
tf.raw_ops.TensorArrayGradV2(
handle, flow_in, source, name=None
)
Args
handle A Tensor of type string.
flow_in A Tensor of type float32.
source A string.
name A name for the operation (optional).
Returns A Tensor of type string. | |
doc_27846 |
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves. | |
doc_27847 |
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats | |
doc_27848 | See Migration guide for more details. tf.compat.v1.raw_ops.DenseToSparseSetOperation
tf.raw_ops.DenseToSparseSetOperation(
set1, set2_indices, set2_values, set2_shape, set_operation,
validate_indices=True, name=None
)
See SetOperationOp::SetOperationFromContext for values of set_operation. Input set2 is a SparseTensor represented by set2_indices, set2_values, and set2_shape. For set2 ranked n, 1st n-1 dimensions must be the same as set1. Dimension n contains values in a set, duplicates are allowed but ignored. If validate_indices is True, this op validates the order and range of set2 indices. Output result is a SparseTensor represented by result_indices, result_values, and result_shape. For set1 and set2 ranked n, this has rank n and the same 1st n-1 dimensions as set1 and set2. The nth dimension contains the result of set_operation applied to the corresponding [0...n-1] dimension of set.
Args
set1 A Tensor. Must be one of the following types: int8, int16, int32, int64, uint8, uint16, string. Tensor with rank n. 1st n-1 dimensions must be the same as set2. Dimension n contains values in a set, duplicates are allowed but ignored.
set2_indices A Tensor of type int64. 2D Tensor, indices of a SparseTensor. Must be in row-major order.
set2_values A Tensor. Must have the same type as set1. 1D Tensor, values of a SparseTensor. Must be in row-major order.
set2_shape A Tensor of type int64. 1D Tensor, shape of a SparseTensor. set2_shape[0...n-1] must be the same as the 1st n-1 dimensions of set1, result_shape[n] is the max set size across n-1 dimensions.
set_operation A string.
validate_indices An optional bool. Defaults to True.
name A name for the operation (optional).
Returns A tuple of Tensor objects (result_indices, result_values, result_shape). result_indices A Tensor of type int64.
result_values A Tensor. Has the same type as set1.
result_shape A Tensor of type int64. | |
doc_27849 | Returns a copy of the object using copy.deepcopy(). This copy will be mutable even if the original was not. | |
doc_27850 | Returns worker information of the node that owns this RRef. | |
doc_27851 |
Return the largest n elements. Parameters
n:int, default 5
Return this many descending sorted values.
keep:{‘first’, ‘last’, ‘all’}, default ‘first’
When there are duplicate values that cannot all fit in a Series of n elements: first : return the first n occurrences in order of appearance. last : return the last n occurrences in reverse order of appearance. all : keep all occurrences. This can result in a Series of size larger than n. Returns
Series
The n largest values in the Series, sorted in decreasing order. See also Series.nsmallest
Get the n smallest elements. Series.sort_values
Sort Series by values. Series.head
Return the first n rows. Notes Faster than .sort_values(ascending=False).head(n) for small n relative to the size of the Series object. Examples
>>> countries_population = {"Italy": 59000000, "France": 65000000,
... "Malta": 434000, "Maldives": 434000,
... "Brunei": 434000, "Iceland": 337000,
... "Nauru": 11300, "Tuvalu": 11300,
... "Anguilla": 11300, "Montserrat": 5200}
>>> s = pd.Series(countries_population)
>>> s
Italy 59000000
France 65000000
Malta 434000
Maldives 434000
Brunei 434000
Iceland 337000
Nauru 11300
Tuvalu 11300
Anguilla 11300
Montserrat 5200
dtype: int64
The n largest elements where n=5 by default.
>>> s.nlargest()
France 65000000
Italy 59000000
Malta 434000
Maldives 434000
Brunei 434000
dtype: int64
The n largest elements where n=3. Default keep value is ‘first’ so Malta will be kept.
>>> s.nlargest(3)
France 65000000
Italy 59000000
Malta 434000
dtype: int64
The n largest elements where n=3 and keeping the last duplicates. Brunei will be kept since it is the last with value 434000 based on the index order.
>>> s.nlargest(3, keep='last')
France 65000000
Italy 59000000
Brunei 434000
dtype: int64
The n largest elements where n=3 with all duplicates kept. Note that the returned Series has five elements due to the three duplicates.
>>> s.nlargest(3, keep='all')
France 65000000
Italy 59000000
Malta 434000
Maldives 434000
Brunei 434000
dtype: int64 | |
doc_27852 | tf.profiler.experimental.Trace(
name, **kwargs
)
A trace event will start when entering the context, and stop and save the result to the profiler when exiting the context. Open TensorBoard Profile tab and choose trace viewer to view the trace event in the timeline. Trace events are created only when the profiler is enabled. More information on how to use the profiler can be found at https://tensorflow.org/guide/profiler Example usage: tf.profiler.experimental.start('logdir')
for step in range(num_steps):
# Creates a trace event for each training step with the step number.
with tf.profiler.experimental.Trace("Train", step_num=step):
train_fn()
tf.profiler.experimental.stop()
Args
name The name of the trace event.
**kwargs Keyword arguments added to the trace event. Both the key and value are of types that can be converted to strings, which will be interpreted by the profiler according to the traceme name. Example usage:
tf.profiler.experimental.start('logdir')
for step in range(num_steps):
# Creates a trace event for each training step with the
# step number.
with tf.profiler.experimental.Trace("Train", step_num=step):
train_fn()
tf.profiler.experimental.stop()
The example above uses the keyword argument "step_num" to specify the training step being traced.
Methods set_metadata View source
set_metadata(
**kwargs
)
Sets metadata in this trace event.
Args
**kwargs metadata in key-value pairs. This method enables setting metadata in a trace event after it is created. Example usage:
def call(function):
with tf.profiler.experimental.Trace("call",
function_name=function.name) as tm:
binary, in_cache = jit_compile(function)
tm.set_metadata(in_cache=in_cache)
execute(binary)
In this example, we want to trace how much time spent on calling a function, which includes compilation and execution. The compilation can be either getting a cached copy of the binary or actually generating the binary, which is indicated by the boolean "in_cache" returned by jit_compile(). We need to use set_metadata() to pass in_cache because we did not know the in_cache value when the trace was created (and we cannot create the trace after jit_compile(), because we want to measure the entire duration of call()). __enter__ View source
__enter__()
__exit__ View source
__exit__(
exc_type, exc_val, exc_tb
) | |
doc_27853 |
Adds many scalar data to summary. Parameters
main_tag (string) – The parent name for the tags
tag_scalar_dict (dict) – Key-value pair storing the tag and corresponding values
global_step (int) – Global step value to record
walltime (float) – Optional override default walltime (time.time()) seconds after epoch of event Examples: from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter()
r = 5
for i in range(100):
writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r),
'xcosx':i*np.cos(i/r),
'tanx': np.tan(i/r)}, i)
writer.close()
# This call adds three values to the same scalar plot with the tag
# 'run_14h' in TensorBoard's scalar section.
Expected result: | |
doc_27854 | When this namespace is specified, the name string is a URL. | |
doc_27855 | The view part of the view – the method that accepts a request argument plus arguments, and returns an HTTP response. The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on. By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example. | |
doc_27856 |
Binarize labels in a one-vs-all fashion. Several regression and binary classification algorithms are available in scikit-learn. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme. This function makes it possible to compute this transformation for a fixed set of class labels known ahead of time. Parameters
yarray-like
Sequence of integer labels or multilabel data to encode.
classesarray-like of shape (n_classes,)
Uniquely holds the label for each class.
neg_labelint, default=0
Value with which negative labels must be encoded.
pos_labelint, default=1
Value with which positive labels must be encoded.
sparse_outputbool, default=False,
Set to true if output binary array is desired in CSR sparse format. Returns
Y{ndarray, sparse matrix} of shape (n_samples, n_classes)
Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format. See also
LabelBinarizer
Class used to wrap the functionality of label_binarize and allow for fitting to classes independently of the transform operation. Examples >>> from sklearn.preprocessing import label_binarize
>>> label_binarize([1, 6], classes=[1, 2, 4, 6])
array([[1, 0, 0, 0],
[0, 0, 0, 1]])
The class ordering is preserved: >>> label_binarize([1, 6], classes=[1, 6, 4, 2])
array([[1, 0, 0, 0],
[0, 1, 0, 0]])
Binary targets transform to a column vector >>> label_binarize(['yes', 'no', 'no', 'yes'], classes=['no', 'yes'])
array([[1],
[0],
[0],
[1]]) | |
doc_27857 |
Convert b to bool or raise. | |
doc_27858 | See torch.greater(). | |
doc_27859 | Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call. When the logging module is imported, it registers this function as an exit handler (see atexit), so normally there’s no need to do that manually. | |
doc_27860 | Returns a string containing the base set by a previous call to SetBase(), or None if SetBase() hasn’t been called. | |
doc_27861 | Parameters
y – a number (integer or float) Set the turtle’s second coordinate to y, leave first coordinate unchanged. >>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00) | |
doc_27862 | A Popen creationflags parameter to specify that a new process is not associated with the job. New in version 3.7. | |
doc_27863 |
Call image_filter with widget args and kwargs Note: display_filtered_image is automatically called. | |
doc_27864 | sklearn.metrics.median_absolute_error(y_true, y_pred, *, multioutput='uniform_average', sample_weight=None) [source]
Median absolute error regression loss. Median absolute error output is non-negative floating point. The best value is 0.0. Read more in the User Guide. Parameters
y_truearray-like of shape = (n_samples) or (n_samples, n_outputs)
Ground truth (correct) target values.
y_predarray-like of shape = (n_samples) or (n_samples, n_outputs)
Estimated target values.
multioutput{‘raw_values’, ‘uniform_average’} or array-like of shape (n_outputs,), default=’uniform_average’
Defines aggregating of multiple output values. Array-like value defines weights used to average errors. ‘raw_values’ :
Returns a full set of errors in case of multioutput input. ‘uniform_average’ :
Errors of all outputs are averaged with uniform weight.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. New in version 0.24. Returns
lossfloat or ndarray of floats
If multioutput is ‘raw_values’, then mean absolute error is returned for each output separately. If multioutput is ‘uniform_average’ or an ndarray of weights, then the weighted average of all output errors is returned. Examples >>> from sklearn.metrics import median_absolute_error
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> median_absolute_error(y_true, y_pred)
0.5
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> median_absolute_error(y_true, y_pred)
0.75
>>> median_absolute_error(y_true, y_pred, multioutput='raw_values')
array([0.5, 1. ])
>>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])
0.85
Examples using sklearn.metrics.median_absolute_error
Common pitfalls in interpretation of coefficients of linear models
Effect of transforming the targets in regression model | |
doc_27865 | See Migration guide for more details. tf.compat.v1.raw_ops.MaxPool3DGrad
tf.raw_ops.MaxPool3DGrad(
orig_input, orig_output, grad, ksize, strides, padding,
data_format='NDHWC', name=None
)
Args
orig_input A Tensor. Must be one of the following types: half, bfloat16, float32. The original input tensor.
orig_output A Tensor. Must have the same type as orig_input. The original output tensor.
grad A Tensor. Must be one of the following types: half, bfloat16, float32. Output backprop of shape [batch, depth, rows, cols, channels].
ksize A list of ints that has length >= 5. 1-D tensor of length 5. The size of the window for each dimension of the input tensor. Must have ksize[0] = ksize[4] = 1.
strides A list of ints that has length >= 5. 1-D tensor of length 5. The stride of the sliding window for each dimension of input. Must have strides[0] = strides[4] = 1.
padding A string from: "SAME", "VALID". The type of padding algorithm to use.
data_format An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width].
name A name for the operation (optional).
Returns A Tensor. Has the same type as grad. | |
doc_27866 | See Migration guide for more details. tf.compat.v1.ragged.stack_dynamic_partitions
tf.ragged.stack_dynamic_partitions(
data, partitions, num_partitions, name=None
)
Returns a RaggedTensor output with num_partitions rows, where the row output[i] is formed by stacking all slices data[j1...jN] such that partitions[j1...jN] = i. Slices of data are stacked in row-major order. If num_partitions is an int (not a Tensor), then this is equivalent to tf.ragged.stack(tf.dynamic_partition(data, partitions, num_partitions)). Example:
data = ['a', 'b', 'c', 'd', 'e']
partitions = [ 3, 0, 2, 2, 3]
num_partitions = 5
tf.ragged.stack_dynamic_partitions(data, partitions, num_partitions)
<tf.RaggedTensor [[b'b'], [], [b'c', b'd'], [b'a', b'e'], []]>
Args
data A Tensor or RaggedTensor containing the values to stack.
partitions An int32 or int64 Tensor or RaggedTensor specifying the partition that each slice of data should be added to. partitions.shape must be a prefix of data.shape. Values must be greater than or equal to zero, and less than num_partitions. partitions is not required to be sorted.
num_partitions An int32 or int64 scalar specifying the number of partitions to output. This determines the number of rows in output.
name A name prefix for the returned tensor (optional).
Returns A RaggedTensor containing the stacked partitions. The returned tensor has the same dtype as data, and its shape is [num_partitions, (D)] + data.shape[partitions.rank:], where (D) is a ragged dimension whose length is the number of data slices stacked for each partition. | |
doc_27867 |
Creates a criterion that measures the triplet loss given input tensors aa , pp , and nn (representing anchor, positive, and negative examples, respectively), and a nonnegative, real-valued function (“distance function”) used to compute the relationship between the anchor and positive example (“positive distance”) and the anchor and negative example (“negative distance”). The unreduced loss (i.e., with reduction set to 'none') can be described as: ℓ(a,p,n)=L={l1,…,lN}⊤,li=max{d(ai,pi)−d(ai,ni)+margin,0}\ell(a, p, n) = L = \{l_1,\dots,l_N\}^\top, \quad l_i = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}
where NN is the batch size; dd is a nonnegative, real-valued function quantifying the closeness of two tensors, referred to as the distance_function; and marginmargin is a nonnegative margin representing the minimum difference between the positive and negative distances that is required for the loss to be 0. The input tensors have NN elements each and can be of any shape that the distance function can handle. If reduction is not 'none' (default 'mean'), then: ℓ(x,y)={mean(L),if reduction=‘mean’;sum(L),if reduction=‘sum’.\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}
See also TripletMarginLoss, which computes the triplet loss for input tensors using the lpl_p distance as the distance function. Parameters
distance_function (callable, optional) – A nonnegative, real-valued function that quantifies the closeness of two tensors. If not specified, nn.PairwiseDistance will be used. Default: None
margin (float, optional) – A nonnegative margin representing the minimum difference between the positive and negative distances required for the loss to be 0. Larger margins penalize cases where the negative examples are not distant enough from the anchors, relative to the positives. Default: 11 .
swap (bool, optional) – Whether to use the distance swap described in the paper Learning shallow convolutional feature descriptors with triplet losses by V. Balntas, E. Riba et al. If True, and if the positive example is closer to the negative example than the anchor is, swaps the positive example and the anchor in the loss computation. Default: False.
reduction (string, optional) – Specifies the (optional) reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied, 'mean': the sum of the output will be divided by the number of elements in the output, 'sum': the output will be summed. Default: 'mean'
Shape:
Input: (N,∗)(N, *) where ∗* represents any number of additional dimensions as supported by the distance function. Output: A Tensor of shape (N)(N) if reduction is 'none', or a scalar otherwise. Examples: >>> # Initialize embeddings
>>> embedding = nn.Embedding(1000, 128)
>>> anchor_ids = torch.randint(0, 1000, (1,))
>>> positive_ids = torch.randint(0, 1000, (1,))
>>> negative_ids = torch.randint(0, 1000, (1,))
>>> anchor = embedding(anchor_ids)
>>> positive = embedding(positive_ids)
>>> negative = embedding(negative_ids)
>>>
>>> # Built-in Distance Function
>>> triplet_loss = \
>>> nn.TripletMarginWithDistanceLoss(distance_function=nn.PairwiseDistance())
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
>>>
>>> # Custom Distance Function
>>> def l_infinity(x1, x2):
>>> return torch.max(torch.abs(x1 - x2), dim=1).values
>>>
>>> triplet_loss = \
>>> nn.TripletMarginWithDistanceLoss(distance_function=l_infinity, margin=1.5)
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
>>>
>>> # Custom Distance Function (Lambda)
>>> triplet_loss = \
>>> nn.TripletMarginWithDistanceLoss(
>>> distance_function=lambda x, y: 1.0 - F.cosine_similarity(x, y))
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
Reference:
V. Balntas, et al.: Learning shallow convolutional feature descriptors with triplet losses: http://www.bmva.org/bmvc/2016/papers/paper119/index.html | |
doc_27868 | Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match. | |
doc_27869 |
Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1). Rebuilds arrays divided by dsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. Parameters
tupsequence of arrays
The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape. Returns
stackedndarray
The array formed by stacking the given arrays, will be at least 3-D. See also concatenate
Join a sequence of arrays along an existing axis. stack
Join a sequence of arrays along a new axis. block
Assemble an nd-array from nested lists of blocks. vstack
Stack arrays in sequence vertically (row wise). hstack
Stack arrays in sequence horizontally (column wise). column_stack
Stack 1-D arrays as columns into a 2-D array. dsplit
Split array along third axis. Notes The function is applied to both the _data and the _mask, if any. Examples >>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]]) | |
doc_27870 | Allow use of default values for colors on terminals supporting this feature. Use this to support transparency in your application. The default color is assigned to the color number -1. After calling this function, init_pair(x,
curses.COLOR_RED, -1) initializes, for instance, color pair x to a red foreground color on the default background. | |
doc_27871 | Attributes
extra_context
A dictionary to include in the context. This is a convenient way of specifying some context in as_view(). Example usage: from django.views.generic import TemplateView
TemplateView.as_view(extra_context={'title': 'Custom Title'})
Methods
get_context_data(**kwargs)
Returns a dictionary representing the template context. The keyword arguments provided will make up the returned context. Example usage: def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['number'] = random.randrange(1, 100)
return context
The template context of all class-based generic views include a view variable that points to the View instance. Use alters_data where appropriate Note that having the view instance in the template context may expose potentially hazardous methods to template authors. To prevent methods like this from being called in the template, set alters_data=True on those methods. For more information, read the documentation on rendering a template context. | |
doc_27872 | See torch.ceil() | |
doc_27873 | Return the docstring of the given node (which must be a FunctionDef, AsyncFunctionDef, ClassDef, or Module node), or None if it has no docstring. If clean is true, clean up the docstring’s indentation with inspect.cleandoc(). Changed in version 3.5: AsyncFunctionDef is now supported. | |
doc_27874 |
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats | |
doc_27875 |
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
antialiased or aa bool or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
color color
edgecolor or ec color or None
facecolor or fc color or None
figure Figure
fill bool
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw float or None
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float | |
doc_27876 |
Return a format string formatting the coordinate. | |
doc_27877 | Works like a regular dict but the get() method can perform type conversions. MultiDict and CombinedMultiDict are subclasses of this class and provide the same feature. Changelog New in version 0.5.
get(key, default=None, type=None)
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found: >>> d = TypeConversionDict(foo='42', bar='blub')
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1
Parameters
key – The key to be looked up.
default – The default value to be returned if the key can’t be looked up. If not further specified None is returned.
type – A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the default value is returned. | |
doc_27878 | See Migration guide for more details. tf.compat.v1.estimator.LatestExporter
tf.estimator.LatestExporter(
name, serving_input_receiver_fn, assets_extra=None, as_text=False,
exports_to_keep=5
)
In addition to exporting, this class also garbage collects stale exports.
Args
name unique name of this Exporter that is going to be used in the export path.
serving_input_receiver_fn a function that takes no arguments and returns a ServingInputReceiver.
assets_extra An optional dict specifying how to populate the assets.extra directory within the exported SavedModel. Each key should give the destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
as_text whether to write the SavedModel proto in text format. Defaults to False.
exports_to_keep Number of exports to keep. Older exports will be garbage-collected. Defaults to 5. Set to None to disable garbage collection.
Raises
ValueError if any arguments is invalid.
Attributes
name Directory name. A directory name under the export base directory where exports of this type are written. Should not be None nor empty.
Methods export View source
export(
estimator, export_path, checkpoint_path, eval_result, is_the_final_export
)
Exports the given Estimator to a specific format.
Args
estimator the Estimator to export.
export_path A string containing a directory where to write the export.
checkpoint_path The checkpoint path to export.
eval_result The output of Estimator.evaluate on this checkpoint.
is_the_final_export This boolean is True when this is an export in the end of training. It is False for the intermediate exports during the training. When passing Exporter to tf.estimator.train_and_evaluate is_the_final_export is always False if TrainSpec.max_steps is None.
Returns The string path to the exported directory or None if export is skipped. | |
doc_27879 |
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends. | |
doc_27880 | The PUT action is also handled and passes all parameters through to post(). | |
doc_27881 |
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values. | |
doc_27882 | This behaves exactly like walk(), except that it yields a 4-tuple (dirpath, dirnames, filenames, dirfd), and it supports dir_fd. dirpath, dirnames and filenames are identical to walk() output, and dirfd is a file descriptor referring to the directory dirpath. This function always supports paths relative to directory descriptors and not following symlinks. Note however that, unlike other functions, the fwalk() default value for follow_symlinks is False. Note Since fwalk() yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. with dup()) if you want to keep them longer. This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory: import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
print(root, "consumes", end="")
print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
end="")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
In the next example, walking the tree bottom-up is essential: rmdir() doesn’t allow deleting a directory before the directory is empty: # Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
for name in files:
os.unlink(name, dir_fd=rootfd)
for name in dirs:
os.rmdir(name, dir_fd=rootfd)
Raises an auditing event os.fwalk with arguments top, topdown, onerror, follow_symlinks, dir_fd. Availability: Unix. New in version 3.3. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: Added support for bytes paths. | |
doc_27883 | See Migration guide for more details. tf.compat.v1.estimator.experimental.stop_if_lower_hook
tf.estimator.experimental.stop_if_lower_hook(
estimator, metric_name, threshold, eval_dir=None, min_steps=0,
run_every_secs=60, run_every_steps=None
)
Usage example: estimator = ...
# Hook to stop training if loss becomes lower than 100.
hook = early_stopping.stop_if_lower_hook(estimator, "loss", 100)
train_spec = tf.estimator.TrainSpec(..., hooks=[hook])
tf.estimator.train_and_evaluate(estimator, train_spec, ...)
Caveat: Current implementation supports early-stopping both training and evaluation in local mode. In distributed mode, training can be stopped but evaluation (where it's a separate job) will indefinitely wait for new model checkpoints to evaluate, so you will need other means to detect and stop it. Early-stopping evaluation in distributed mode requires changes in train_and_evaluate API and will be addressed in a future revision.
Args
estimator A tf.estimator.Estimator instance.
metric_name str, metric to track. "loss", "accuracy", etc.
threshold Numeric threshold for the given metric.
eval_dir If set, directory containing summary files with eval metrics. By default, estimator.eval_dir() will be used.
min_steps int, stop is never requested if global step is less than this value. Defaults to 0.
run_every_secs If specified, calls should_stop_fn at an interval of run_every_secs seconds. Defaults to 60 seconds. Either this or run_every_steps must be set.
run_every_steps If specified, calls should_stop_fn every run_every_steps steps. Either this or run_every_secs must be set.
Returns An early-stopping hook of type SessionRunHook that periodically checks if the given metric is lower than specified threshold and initiates early stopping if true. | |
doc_27884 | Returns an instance of the Filter class. If name is specified, it names a logger which, together with its children, will have its events allowed through the filter. If name is the empty string, allows every event.
filter(record)
Is the specified record to be logged? Returns zero for no, nonzero for yes. If deemed appropriate, the record may be modified in-place by this method. | |
doc_27885 | Returns the current unpack data buffer as a string. | |
doc_27886 | Creates a new item and returns the item identifier of the newly created item. parent is the item ID of the parent item, or the empty string to create a new top-level item. index is an integer, or the value “end”, specifying where in the list of parent’s children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning; if index is greater than or equal to the current number of children, it is inserted at the end. If iid is specified, it is used as the item identifier; iid must not already exist in the tree. Otherwise, a new unique identifier is generated. See Item Options for the list of available points. | |
doc_27887 | class sklearn.linear_model.BayesianRidge(*, n_iter=300, tol=0.001, alpha_1=1e-06, alpha_2=1e-06, lambda_1=1e-06, lambda_2=1e-06, alpha_init=None, lambda_init=None, compute_score=False, fit_intercept=True, normalize=False, copy_X=True, verbose=False) [source]
Bayesian ridge regression. Fit a Bayesian ridge model. See the Notes section for details on this implementation and the optimization of the regularization parameters lambda (precision of the weights) and alpha (precision of the noise). Read more in the User Guide. Parameters
n_iterint, default=300
Maximum number of iterations. Should be greater than or equal to 1.
tolfloat, default=1e-3
Stop the algorithm if w has converged.
alpha_1float, default=1e-6
Hyper-parameter : shape parameter for the Gamma distribution prior over the alpha parameter.
alpha_2float, default=1e-6
Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the alpha parameter.
lambda_1float, default=1e-6
Hyper-parameter : shape parameter for the Gamma distribution prior over the lambda parameter.
lambda_2float, default=1e-6
Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the lambda parameter.
alpha_initfloat, default=None
Initial value for alpha (precision of the noise). If not set, alpha_init is 1/Var(y). New in version 0.22.
lambda_initfloat, default=None
Initial value for lambda (precision of the weights). If not set, lambda_init is 1. New in version 0.22.
compute_scorebool, default=False
If True, compute the log marginal likelihood at each iteration of the optimization.
fit_interceptbool, default=True
Whether to calculate the intercept for this model. The intercept is not treated as a probabilistic parameter and thus has no associated variance. If set to False, no intercept will be used in calculations (i.e. data is expected to be centered).
normalizebool, default=False
This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
copy_Xbool, default=True
If True, X will be copied; else, it may be overwritten.
verbosebool, default=False
Verbose mode when fitting the model. Attributes
coef_array-like of shape (n_features,)
Coefficients of the regression model (mean of distribution)
intercept_float
Independent term in decision function. Set to 0.0 if fit_intercept = False.
alpha_float
Estimated precision of the noise.
lambda_float
Estimated precision of the weights.
sigma_array-like of shape (n_features, n_features)
Estimated variance-covariance matrix of the weights
scores_array-like of shape (n_iter_+1,)
If computed_score is True, value of the log marginal likelihood (to be maximized) at each iteration of the optimization. The array starts with the value of the log marginal likelihood obtained for the initial values of alpha and lambda and ends with the value obtained for the estimated alpha and lambda.
n_iter_int
The actual number of iterations to reach the stopping criterion.
X_offset_float
If normalize=True, offset subtracted for centering data to a zero mean.
X_scale_float
If normalize=True, parameter used to scale data to a unit standard deviation. Notes There exist several strategies to perform Bayesian ridge regression. This implementation is based on the algorithm described in Appendix A of (Tipping, 2001) where updates of the regularization parameters are done as suggested in (MacKay, 1992). Note that according to A New View of Automatic Relevance Determination (Wipf and Nagarajan, 2008) these update rules do not guarantee that the marginal likelihood is increasing between two consecutive iterations of the optimization. References D. J. C. MacKay, Bayesian Interpolation, Computation and Neural Systems, Vol. 4, No. 3, 1992. M. E. Tipping, Sparse Bayesian Learning and the Relevance Vector Machine, Journal of Machine Learning Research, Vol. 1, 2001. Examples >>> from sklearn import linear_model
>>> clf = linear_model.BayesianRidge()
>>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
BayesianRidge()
>>> clf.predict([[1, 1]])
array([1.])
Methods
fit(X, y[, sample_weight]) Fit the model
get_params([deep]) Get parameters for this estimator.
predict(X[, return_std]) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit the model Parameters
Xndarray of shape (n_samples, n_features)
Training data
yndarray of shape (n_samples,)
Target values. Will be cast to X’s dtype if necessary
sample_weightndarray of shape (n_samples,), default=None
Individual weights for each sample New in version 0.20: parameter sample_weight support to BayesianRidge. Returns
selfreturns an instance of self.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X, return_std=False) [source]
Predict using the linear model. In addition to the mean of the predictive distribution, also its standard deviation can be returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Samples.
return_stdbool, default=False
Whether to return the standard deviation of posterior prediction. Returns
y_meanarray-like of shape (n_samples,)
Mean of predictive distribution of query points.
y_stdarray-like of shape (n_samples,)
Standard deviation of predictive distribution of query points.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
Examples using sklearn.linear_model.BayesianRidge
Feature agglomeration vs. univariate selection
Curve Fitting with Bayesian Ridge Regression
Bayesian Ridge Regression
Imputing missing values with variants of IterativeImputer | |
doc_27888 | Decodes a DLPack to a tensor. Parameters
dlpack – a PyCapsule object with the dltensor The tensor will share the memory with the object represented in the dlpack. Note that each dlpack can only be consumed once. | |
doc_27889 | Parameters
angle – a number Rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. Do not change the turtle’s heading (direction of movement). >>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.settiltangle(45)
>>> turtle.fd(50)
>>> turtle.settiltangle(-45)
>>> turtle.fd(50)
Deprecated since version 3.1. | |
doc_27890 | socket.PF_PACKET
PACKET_*
Many constants of these forms, documented in the Linux documentation, are also defined in the socket module. Availability: Linux >= 2.2. | |
doc_27891 | Returns a namedtuple() (nchannels, sampwidth,
framerate, nframes, comptype, compname), equivalent to output of the get*() methods. | |
doc_27892 | tf.experimental.numpy.swapaxes(
a, axis1, axis2
)
See the NumPy documentation for numpy.swapaxes. | |
doc_27893 |
Bases: mpl_toolkits.axisartist.axisline_style.AxislineStyle.SimpleArrow Parameters
sizefloat
Size of the arrow as a fraction of the ticklabel size. ArrowAxisClass[source]
alias of mpl_toolkits.axisartist.axisline_style._FancyAxislineStyle.FilledArrow | |
doc_27894 | See Migration guide for more details. tf.compat.v1.config.run_functions_eagerly
tf.config.run_functions_eagerly(
run_eagerly
)
Calling tf.config.run_functions_eagerly(True) will make all invocations of tf.function run eagerly instead of running as a traced graph function. This can be useful for debugging.
def my_func(a):
print("Python side effect")
return a + a
a_fn = tf.function(my_func)
# A side effect the first time the function is traced
a_fn(tf.constant(1))
Python side effect
<tf.Tensor: shape=(), dtype=int32, numpy=2>
# No further side effect, as the traced function is called
a_fn(tf.constant(2))
<tf.Tensor: shape=(), dtype=int32, numpy=4>
# Now, switch to eager running
tf.config.run_functions_eagerly(True)
# Side effect, as the function is called directly
a_fn(tf.constant(2))
Python side effect
<tf.Tensor: shape=(), dtype=int32, numpy=4>
# Turn this back off
tf.config.run_functions_eagerly(False)
Note: This flag has no effect on functions passed into tf.data transformations as arguments. tf.data functions are never executed eagerly and are always executed as a compiled Tensorflow Graph.
Args
run_eagerly Boolean. Whether to run functions eagerly. | |
doc_27895 | Return the single most common data point from discrete or nominal data. The mode (when it exists) is the most typical value and serves as a measure of central location. If there are multiple modes with the same frequency, returns the first one encountered in the data. If the smallest or largest of those is desired instead, use min(multimode(data)) or max(multimode(data)). If the input data is empty, StatisticsError is raised. mode assumes discrete data and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
The mode is unique in that it is the only statistic in this package that also applies to nominal (non-numeric) data: >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
Changed in version 3.8: Now handles multimodal datasets by returning the first mode encountered. Formerly, it raised StatisticsError when more than one mode was found. | |
doc_27896 | boolean that is True if the application is served by a multithreaded WSGI server. | |
doc_27897 |
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values. | |
doc_27898 |
Return a tuple width, height, xdescent, ydescent of the box. | |
doc_27899 | Although the Cursor class of the sqlite3 module implements this attribute, the database engine’s own support for the determination of “rows affected”/”rows selected” is quirky. For executemany() statements, the number of modifications are summed up into rowcount. As required by the Python DB API Spec, the rowcount attribute “is -1 in case no executeXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface”. This includes SELECT statements because we cannot determine the number of rows a query produced until all rows were fetched. With SQLite versions before 3.6.5, rowcount is set to 0 if you make a DELETE FROM table without any condition. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.