_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_3700 | tf.compat.v1.metrics.sparse_precision_at_k(
labels, predictions, k, class_id=None, weights=None, metrics_collections=None,
updates_collections=None, name=None
)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use precision_at_k instead | |
doc_3701 |
Fit MultiTaskElasticNet model with coordinate descent Parameters
Xndarray of shape (n_samples, n_features)
Data.
yndarray of shape (n_samples, n_tasks)
Target. Will be cast to X’s dtype if necessary. Notes Coordinate descent is an algorithm that considers each column of data at a time hence it will automatically convert the X input as a Fortran-contiguous numpy array if necessary. To avoid memory re-allocation it is advised to allocate the initial data in memory directly using that format. | |
doc_3702 |
An ndarray containing the non- fill_value values. Examples
>>> s = SparseArray([0, 0, 1, 0, 2], fill_value=0)
>>> s.sp_values
array([1, 2]) | |
doc_3703 | tf.compat.v1.train.SyncReplicasOptimizer(
opt, replicas_to_aggregate, total_num_replicas=None, variable_averages=None,
variables_to_average=None, use_locking=False, name='sync_replicas'
)
This class is deprecated. For synchronous training, please use Distribution Strategies. In a typical asynchronous training environment, it's common to have some stale gradients. For example, with a N-replica asynchronous training, gradients will be applied to the variables N times independently. Depending on each replica's training speed, some gradients might be calculated from copies of the variable from several steps back (N-1 steps on average). This optimizer avoids stale gradients by collecting gradients from all replicas, averaging them, then applying them to the variables in one shot, after which replicas can fetch the new variables and continue. The following accumulators/queue are created: N gradient accumulators, one per variable to train. Gradients are pushed to them and the chief worker will wait until enough gradients are collected and then average them before applying to variables. The accumulator will drop all stale gradients (more details in the accumulator op). 1 token queue where the optimizer pushes the new global_step value after all variables are updated. The following local variable is created:
sync_rep_local_step, one per replica. Compared against the global_step in each accumulator to check for staleness of the gradients. The optimizer adds nodes to the graph to collect gradients and pause the trainers until variables are updated. For the Parameter Server job: An accumulator is created for each variable, and each replica pushes the gradients into the accumulators instead of directly applying them to the variables. Each accumulator averages once enough gradients (replicas_to_aggregate) have been accumulated. Apply the averaged gradients to the variables. Only after all variables have been updated, increment the global step. Only after step 4, pushes global_step in the token_queue, once for each worker replica. The workers can now fetch the global step, use it to update its local_step variable and start the next batch. Please note that some workers can consume multiple minibatches, while some may not consume even one. This is because each worker fetches minibatches as long as a token exists. If one worker is stuck for some reason and does not consume a token, another worker can use it. For the replicas: Start a step: fetch variables and compute gradients. Once the gradients have been computed, push them into gradient accumulators. Each accumulator will check the staleness and drop the stale. After pushing all the gradients, dequeue an updated value of global_step from the token queue and record that step to its local_step variable. Note that this is effectively a barrier. Start the next batch. Usage # Create any optimizer to update the variables, say a simple SGD:
opt = GradientDescentOptimizer(learning_rate=0.1)
# Wrap the optimizer with sync_replicas_optimizer with 50 replicas: at each
# step the optimizer collects 50 gradients before applying to variables.
# Note that if you want to have 2 backup replicas, you can change
# total_num_replicas=52 and make sure this number matches how many physical
# replicas you started in your job.
opt = tf.compat.v1.train.SyncReplicasOptimizer(opt, replicas_to_aggregate=50,
total_num_replicas=50)
# Some models have startup_delays to help stabilize the model but when using
# sync_replicas training, set it to 0.
# Now you can call `minimize()` or `compute_gradients()` and
# `apply_gradients()` normally
training_op = opt.minimize(total_loss, global_step=self.global_step)
# You can create the hook which handles initialization and queues.
sync_replicas_hook = opt.make_session_run_hook(is_chief)
In the training program, every worker will run the train_op as if not synchronized. with training.MonitoredTrainingSession(
master=workers[worker_id].target, is_chief=is_chief,
hooks=[sync_replicas_hook]) as mon_sess:
while not mon_sess.should_stop():
mon_sess.run(training_op)
To use SyncReplicasOptimizer with an Estimator, you need to send sync_replicas_hook while calling the fit. my_estimator = DNNClassifier(..., optimizer=opt)
my_estimator.fit(..., hooks=[sync_replicas_hook])
Args
opt The actual optimizer that will be used to compute and apply the gradients. Must be one of the Optimizer classes.
replicas_to_aggregate number of replicas to aggregate for each variable update.
total_num_replicas Total number of tasks/workers/replicas, could be different from replicas_to_aggregate. If total_num_replicas > replicas_to_aggregate: it is backup_replicas + replicas_to_aggregate. If total_num_replicas < replicas_to_aggregate: Replicas compute multiple batches per update to variables.
variable_averages Optional ExponentialMovingAverage object, used to maintain moving averages for the variables passed in variables_to_average.
variables_to_average a list of variables that need to be averaged. Only needed if variable_averages is passed in.
use_locking If True use locks for update operation.
name string. Optional name of the returned operation. Methods apply_gradients View source
apply_gradients(
grads_and_vars, global_step=None, name=None
)
Apply gradients to variables. This contains most of the synchronization implementation and also wraps the apply_gradients() from the real optimizer.
Args
grads_and_vars List of (gradient, variable) pairs as returned by compute_gradients().
global_step Optional Variable to increment by one after the variables have been updated.
name Optional name for the returned operation. Default to the name passed to the Optimizer constructor.
Returns
train_op The op to dequeue a token so the replicas can exit this batch and start the next one. This is executed by each replica.
Raises
ValueError If the grads_and_vars is empty.
ValueError If global step is not provided, the staleness cannot be checked. compute_gradients View source
compute_gradients(
*args, **kwargs
)
Compute gradients of "loss" for the variables in "var_list". This simply wraps the compute_gradients() from the real optimizer. The gradients will be aggregated in the apply_gradients() so that user can modify the gradients like clipping with per replica global norm if needed. The global norm with aggregated gradients can be bad as one replica's huge gradients can hurt the gradients from other replicas.
Args
*args Arguments for compute_gradients().
**kwargs Keyword arguments for compute_gradients().
Returns A list of (gradient, variable) pairs.
get_chief_queue_runner View source
get_chief_queue_runner()
Returns the QueueRunner for the chief to execute. This includes the operations to synchronize replicas: aggregate gradients, apply to variables, increment global step, insert tokens to token queue. Note that this can only be called after calling apply_gradients() which actually generates this queuerunner.
Returns A QueueRunner for chief to execute.
Raises
ValueError If this is called before apply_gradients(). get_init_tokens_op View source
get_init_tokens_op(
num_tokens=-1
)
Returns the op to fill the sync_token_queue with the tokens. This is supposed to be executed in the beginning of the chief/sync thread so that even if the total_num_replicas is less than replicas_to_aggregate, the model can still proceed as the replicas can compute multiple steps per variable update. Make sure: num_tokens >= replicas_to_aggregate - total_num_replicas.
Args
num_tokens Number of tokens to add to the queue.
Returns An op for the chief/sync replica to fill the token queue.
Raises
ValueError If this is called before apply_gradients().
ValueError If num_tokens are smaller than replicas_to_aggregate - total_num_replicas. get_name View source
get_name()
get_slot View source
get_slot(
*args, **kwargs
)
Return a slot named "name" created for "var" by the Optimizer. This simply wraps the get_slot() from the actual optimizer.
Args
*args Arguments for get_slot().
**kwargs Keyword arguments for get_slot().
Returns The Variable for the slot if it was created, None otherwise.
get_slot_names View source
get_slot_names(
*args, **kwargs
)
Return a list of the names of slots created by the Optimizer. This simply wraps the get_slot_names() from the actual optimizer.
Args
*args Arguments for get_slot().
**kwargs Keyword arguments for get_slot().
Returns A list of strings.
make_session_run_hook View source
make_session_run_hook(
is_chief, num_tokens=-1
)
Creates a hook to handle SyncReplicasHook ops such as initialization. minimize View source
minimize(
loss, global_step=None, var_list=None, gate_gradients=GATE_OP,
aggregation_method=None, colocate_gradients_with_ops=False, name=None,
grad_loss=None
)
Add operations to minimize loss by updating var_list. This method simply combines calls compute_gradients() and apply_gradients(). If you want to process the gradient before applying them call compute_gradients() and apply_gradients() explicitly instead of using this function.
Args
loss A Tensor containing the value to minimize.
global_step Optional Variable to increment by one after the variables have been updated.
var_list Optional list or tuple of Variable objects to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES.
gate_gradients How to gate the computation of gradients. Can be GATE_NONE, GATE_OP, or GATE_GRAPH.
aggregation_method Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod.
colocate_gradients_with_ops If True, try colocating gradients with the corresponding op.
name Optional name for the returned operation.
grad_loss Optional. A Tensor holding the gradient computed for loss.
Returns An Operation that updates the variables in var_list. If global_step was not None, that operation also increments global_step.
Raises
ValueError If some of the variables are not Variable objects. Eager Compatibility When eager execution is enabled, loss should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of var_list if not None, else with respect to any trainable variables created during the execution of the loss function. gate_gradients, aggregation_method, colocate_gradients_with_ops and grad_loss are ignored when eager execution is enabled. variables View source
variables()
Fetches a list of optimizer variables in the default graph. This wraps variables() from the actual optimizer. It does not include the SyncReplicasOptimizer's local step.
Returns A list of variables.
Class Variables
GATE_GRAPH 2
GATE_NONE 0
GATE_OP 1 | |
doc_3704 | os.execle(path, arg0, arg1, ..., env)
os.execlp(file, arg0, arg1, ...)
os.execlpe(file, arg0, arg1, ..., env)
os.execv(path, args)
os.execve(path, args, env)
os.execvp(file, args)
os.execvpe(file, args, env)
These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions. The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using sys.stdout.flush() or os.fsync() before calling an exec* function. The “l” and “v” variants of the exec* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the execl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced. The variants which include a “p” near the end (execlp(), execlpe(), execvp(), and execvpe()) will use the PATH environment variable to locate the program file. When the environment is being replaced (using one of the exec*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, execl(), execle(), execv(), and execve(), will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path. For execle(), execlpe(), execve(), and execvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (these are used instead of the current process’ environment); the functions execl(), execlp(), execv(), and execvp() all cause the new process to inherit the environment of the current process. For execve() on some platforms, path may also be specified as an open file descriptor. This functionality may not be supported on your platform; you can check whether or not it is available using os.supports_fd. If it is unavailable, using it will raise a NotImplementedError. Raises an auditing event os.exec with arguments path, args, env. Availability: Unix, Windows. New in version 3.3: Added support for specifying path as an open file descriptor for execve(). Changed in version 3.6: Accepts a path-like object. | |
doc_3705 |
Set the (group) id for the artist. Parameters
gidstr | |
doc_3706 | A class to handle opening of HTTPS URLs. context and check_hostname have the same meaning as in http.client.HTTPSConnection. Changed in version 3.2: context and check_hostname were added. | |
doc_3707 |
Shape of the i’th bicluster. Parameters
iint
The index of the cluster. Returns
n_rowsint
Number of rows in the bicluster.
n_colsint
Number of columns in the bicluster. | |
doc_3708 | unlock()
Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. | |
doc_3709 | Line number on which the error was detected. The first line is numbered 1. | |
doc_3710 | Return a stat_result object for this entry. This method follows symbolic links by default; to stat a symbolic link add the follow_symlinks=False argument. On Unix, this method always requires a system call. On Windows, it only requires a system call if follow_symlinks is True and the entry is a reparse point (for example, a symbolic link or directory junction). On Windows, the st_ino, st_dev and st_nlink attributes of the stat_result are always set to zero. Call os.stat() to get these attributes. The result is cached on the os.DirEntry object, with a separate cache for follow_symlinks True and False. Call os.stat() to fetch up-to-date information. | |
doc_3711 | See Mock.reset_mock(). Also sets await_count to 0, await_args to None, and clears the await_args_list. | |
doc_3712 |
Least Squares projection of the data onto the sparse components. To avoid instability issues in case the system is under-determined, regularization can be applied (Ridge regression) via the ridge_alpha parameter. Note that Sparse PCA components orthogonality is not enforced as in PCA hence one cannot use a simple linear projection. Parameters
Xndarray of shape (n_samples, n_features)
Test data to be transformed, must have the same number of features as the data used to train the model. Returns
X_newndarray of shape (n_samples, n_components)
Transformed data. | |
doc_3713 |
Bases: object AxisArtistHelper should define following method with given APIs. Note that the first axes argument will be axes attribute of the caller artist.: # LINE (spinal line?)
def get_line(self, axes):
# path : Path
return path
def get_line_transform(self, axes):
# ...
# trans : transform
return trans
# LABEL
def get_label_pos(self, axes):
# x, y : position
return (x, y), trans
def get_label_offset_transform(self,
axes,
pad_points, fontprops, renderer,
bboxes,
):
# va : vertical alignment
# ha : horizontal alignment
# a : angle
return trans, va, ha, a
# TICK
def get_tick_transform(self, axes):
return trans
def get_tick_iterators(self, axes):
# iter : iterable object that yields (c, angle, l) where
# c, angle, l is position, tick angle, and label
return iter_major, iter_minor
classFixed(loc, nth_coord=None)[source]
Bases: mpl_toolkits.axisartist.axislines.AxisArtistHelper._Base Helper class for a fixed (in the axes coordinate) axis. nth_coord = along which coordinate value varies in 2D, nth_coord = 0 -> x axis, nth_coord = 1 -> y axis get_axislabel_pos_angle(axes)[source]
Return the label reference position in transAxes. get_label_transform() returns a transform of (transAxes+offset)
get_axislabel_transform(axes)[source]
get_line(axes)[source]
get_line_transform(axes)[source]
get_nth_coord()[source]
get_tick_transform(axes)[source]
classFloating(nth_coord, value)[source]
Bases: mpl_toolkits.axisartist.axislines.AxisArtistHelper._Base get_line(axes)[source]
get_nth_coord()[source] | |
doc_3714 |
Bases: matplotlib.ticker.Locator Determine the tick locations for symmetric log axes. Parameters
transformSymmetricalLogTransform, optional
If set, defines the base and linthresh of the symlog transform.
base, linthreshfloat, optional
The base and linthresh of the symlog transform, as documented for SymmetricalLogScale. These parameters are only used if transform is not set.
subssequence of float, default: [1]
The multiples of integer powers of the base where ticks are placed, i.e., ticks are placed at [sub * base**i for i in ... for sub in subs]. Notes Either transform, or both base and linthresh, must be given. set_params(subs=None, numticks=None)[source]
Set parameters within this locator.
tick_values(vmin, vmax)[source]
Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc))
<type 'Locator'>
>>> print(loc())
[1, 2, 3, 4]
view_limits(vmin, vmax)[source]
Try to choose the view limits intelligently. | |
doc_3715 |
Returns whether the kernel is stationary. | |
doc_3716 |
Coarse to fine optical flow estimator. The TV-L1 solver is applied at each level of the image pyramid. TV-L1 is a popular algorithm for optical flow estimation introduced by Zack et al. [1], improved in [2] and detailed in [3]. Parameters
reference_imagendarray, shape (M, N[, P[, …]])
The first gray scale image of the sequence.
moving_imagendarray, shape (M, N[, P[, …]])
The second gray scale image of the sequence.
attachmentfloat, optional
Attachment parameter (\(\lambda\) in [1]). The smaller this parameter is, the smoother the returned result will be.
tightnessfloat, optional
Tightness parameter (\(\tau\) in [1]). It should have a small value in order to maintain attachement and regularization parts in correspondence.
num_warpint, optional
Number of times image1 is warped.
num_iterint, optional
Number of fixed point iteration.
tolfloat, optional
Tolerance used as stopping criterion based on the L² distance between two consecutive values of (u, v).
prefilterbool, optional
Whether to prefilter the estimated optical flow before each image warp. When True, a median filter with window size 3 along each axis is applied. This helps to remove potential outliers.
dtypedtype, optional
Output data type: must be floating point. Single precision provides good results and saves memory usage and computation time compared to double precision. Returns
flowndarray, shape ((image0.ndim, M, N[, P[, …]])
The estimated optical flow components for each axis. Notes Color images are not supported. References
1(1,2,3)
Zach, C., Pock, T., & Bischof, H. (2007, September). A duality based approach for realtime TV-L 1 optical flow. In Joint pattern recognition symposium (pp. 214-223). Springer, Berlin, Heidelberg. DOI:10.1007/978-3-540-74936-3_22
2
Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers, D. (2009). An improved algorithm for TV-L 1 optical flow. In Statistical and geometrical approaches to visual motion analysis (pp. 23-45). Springer, Berlin, Heidelberg. DOI:10.1007/978-3-642-03061-1_2
3
Pérez, J. S., Meinhardt-Llopis, E., & Facciolo, G. (2013). TV-L1 optical flow estimation. Image Processing On Line, 2013, 137-150. DOI:10.5201/ipol.2013.26 Examples >>> from skimage.color import rgb2gray
>>> from skimage.data import stereo_motorcycle
>>> from skimage.registration import optical_flow_tvl1
>>> image0, image1, disp = stereo_motorcycle()
>>> # --- Convert the images to gray level: color is not supported.
>>> image0 = rgb2gray(image0)
>>> image1 = rgb2gray(image1)
>>> flow = optical_flow_tvl1(image1, image0) | |
doc_3717 |
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_3718 |
Pass the input through the encoder layers in turn. Parameters
src – the sequence to the encoder (required).
mask – the mask for the src sequence (optional).
src_key_padding_mask – the mask for the src keys per batch (optional). Shape:
see the docs in Transformer class. | |
doc_3719 |
Construct Python bytes containing the raw data bytes in the array. Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter. New in version 1.9.0. Parameters
order{‘C’, ‘F’, ‘A’}, optional
Controls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’. Returns
sbytes
Python bytes exhibiting a copy of a’s raw data. Examples >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
>>> x.tobytes()
b'\x00\x00\x01\x00\x02\x00\x03\x00'
>>> x.tobytes('C') == x.tobytes()
True
>>> x.tobytes('F')
b'\x00\x00\x02\x00\x01\x00\x03\x00' | |
doc_3720 | A round-robin scheduling policy. | |
doc_3721 | Open the URL url, which can be either a string or a Request object. data must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for details. urllib.request module uses HTTP/1.1 and includes Connection:close header in its HTTP requests. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections. If context is specified, it must be a ssl.SSLContext instance describing the various SSL options. See HTTPSConnection for more details. The optional cafile and capath parameters specify a set of trusted CA certificates for HTTPS requests. cafile should point to a single file containing a bundle of CA certificates, whereas capath should point to a directory of hashed certificate files. More information can be found in ssl.SSLContext.load_verify_locations(). The cadefault parameter is ignored. This function always returns an object which can work as a context manager and has the properties url, headers, and status. See urllib.response.addinfourl for more detail on these properties. For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse object slightly modified. In addition to the three new methods above, the msg attribute contains the same information as the reason attribute — the reason phrase returned by server — instead of the response headers as it is specified in the documentation for HTTPResponse. For FTP, file, and data URLs and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a urllib.response.addinfourl object. Raises URLError on protocol errors. Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). In addition, if proxy settings are detected (for example, when a *_proxy environment variable like http_proxy is set), ProxyHandler is default installed and makes sure the requests are handled through the proxy. The legacy urllib.urlopen function from Python 2.6 and earlier has been discontinued; urllib.request.urlopen() corresponds to the old urllib2.urlopen. Proxy handling, which was done by passing a dictionary parameter to urllib.urlopen, can be obtained by using ProxyHandler objects.
The default opener raises an auditing event urllib.Request with arguments fullurl, data, headers, method taken from the request object. Changed in version 3.2: cafile and capath were added. Changed in version 3.2: HTTPS virtual hosts are now supported if possible (that is, if ssl.HAS_SNI is true). New in version 3.2: data can be an iterable object. Changed in version 3.3: cadefault was added. Changed in version 3.4.3: context was added. Deprecated since version 3.6: cafile, capath and cadefault are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you. | |
doc_3722 | Append items from iterable to the end of the array. If iterable is another array, it must have exactly the same type code; if not, TypeError will be raised. If iterable is not an array, it must be iterable and its elements must be the right type to be appended to the array. | |
doc_3723 |
Locally Linear Embedding Read more in the User Guide. Parameters
n_neighborsint, default=5
number of neighbors to consider for each point.
n_componentsint, default=2
number of coordinates for the manifold
regfloat, default=1e-3
regularization constant, multiplies the trace of the local covariance matrix of the distances.
eigen_solver{‘auto’, ‘arpack’, ‘dense’}, default=’auto’
auto : algorithm will attempt to choose the best method for input data
arpackuse arnoldi iteration in shift-invert mode.
For this method, M may be a dense matrix, sparse matrix, or general linear operator. Warning: ARPACK can be unstable for some problems. It is best to try several random seeds in order to check results.
denseuse standard dense matrix operations for the eigenvalue
decomposition. For this method, M must be an array or matrix type. This method should be avoided for large problems.
tolfloat, default=1e-6
Tolerance for ‘arpack’ method Not used if eigen_solver==’dense’.
max_iterint, default=100
maximum number of iterations for the arpack solver. Not used if eigen_solver==’dense’.
method{‘standard’, ‘hessian’, ‘modified’, ‘ltsa’}, default=’standard’
standarduse the standard locally linear embedding algorithm. see
reference [1]
hessianuse the Hessian eigenmap method. This method requires
n_neighbors > n_components * (1 + (n_components + 1) / 2 see reference [2]
modifieduse the modified locally linear embedding algorithm.
see reference [3]
ltsause local tangent space alignment algorithm
see reference [4]
hessian_tolfloat, default=1e-4
Tolerance for Hessian eigenmapping method. Only used if method == 'hessian'
modified_tolfloat, default=1e-12
Tolerance for modified LLE method. Only used if method == 'modified'
neighbors_algorithm{‘auto’, ‘brute’, ‘kd_tree’, ‘ball_tree’}, default=’auto’
algorithm to use for nearest neighbors search, passed to neighbors.NearestNeighbors instance
random_stateint, RandomState instance, default=None
Determines the random number generator when eigen_solver == ‘arpack’. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>.
n_jobsint or None, default=None
The number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
embedding_array-like, shape [n_samples, n_components]
Stores the embedding vectors
reconstruction_error_float
Reconstruction error associated with embedding_
nbrs_NearestNeighbors object
Stores nearest neighbors instance, including BallTree or KDtree if applicable. References
1
Roweis, S. & Saul, L. Nonlinear dimensionality reduction by locally linear embedding. Science 290:2323 (2000).
2
Donoho, D. & Grimes, C. Hessian eigenmaps: Locally linear embedding techniques for high-dimensional data. Proc Natl Acad Sci U S A. 100:5591 (2003).
3
Zhang, Z. & Wang, J. MLLE: Modified Locally Linear Embedding Using Multiple Weights. http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.70.382
4
Zhang, Z. & Zha, H. Principal manifolds and nonlinear dimensionality reduction via tangent space alignment. Journal of Shanghai Univ. 8:406 (2004) Examples >>> from sklearn.datasets import load_digits
>>> from sklearn.manifold import LocallyLinearEmbedding
>>> X, _ = load_digits(return_X_y=True)
>>> X.shape
(1797, 64)
>>> embedding = LocallyLinearEmbedding(n_components=2)
>>> X_transformed = embedding.fit_transform(X[:100])
>>> X_transformed.shape
(100, 2)
Methods
fit(X[, y]) Compute the embedding vectors for data X
fit_transform(X[, y]) Compute the embedding vectors for data X and transform X.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform new points into embedding space.
fit(X, y=None) [source]
Compute the embedding vectors for data X Parameters
Xarray-like of shape [n_samples, n_features]
training set.
yIgnored
Returns
selfreturns an instance of self.
fit_transform(X, y=None) [source]
Compute the embedding vectors for data X and transform X. Parameters
Xarray-like of shape [n_samples, n_features]
training set.
yIgnored
Returns
X_newarray-like, shape (n_samples, n_components)
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
transform(X) [source]
Transform new points into embedding space. Parameters
Xarray-like of shape (n_samples, n_features)
Returns
X_newarray, shape = [n_samples, n_components]
Notes Because of scaling performed by this method, it is discouraged to use it together with methods that are not scale-invariant (like SVMs) | |
doc_3724 | Quiver(ax, *args[, scale, headwidth, ...]) Specialized PolyCollection for arrows.
QuiverKey(Q, X, Y, U, label, *[, angle, ...]) Labelled arrow for use as a quiver plot scale key.
Barbs(ax, *args[, pivot, length, barbcolor, ...]) Specialized PolyCollection for barbs. | |
doc_3725 | For top-level classes, None. For nested classes, the parent. New in version 3.7. | |
doc_3726 |
Add installable headers to configuration. Add the given sequence of files to the beginning of the headers list. By default, headers will be installed under <python- include>/<self.name.replace(‘.’,’/’)>/ directory. If an item of files is a tuple, then its first argument specifies the actual installation location relative to the <python-include> path. Parameters
filesstr or seq
Argument(s) can be either: 2-sequence (<includedir suffix>,<path to header file(s)>) path(s) to header file(s) where python includedir suffix will default to package name. | |
doc_3727 |
Return the offsets for the collection. | |
doc_3728 |
Calibrate a denoising function and return optimal J-invariant version. The returned function is partially evaluated with optimal parameter values set for denoising the input image. Parameters
imagendarray
Input data to be denoised (converted using img_as_float).
denoise_functionfunction
Denoising function to be calibrated.
denoise_parametersdict of list
Ranges of parameters for denoise_function to be calibrated over.
strideint, optional
Stride used in masking procedure that converts denoise_function to J-invariance.
approximate_lossbool, optional
Whether to approximate the self-supervised loss used to evaluate the denoiser by only computing it on one masked version of the image. If False, the runtime will be a factor of stride**image.ndim longer.
extra_outputbool, optional
If True, return parameters and losses in addition to the calibrated denoising function Returns
best_denoise_functionfunction
The optimal J-invariant version of denoise_function.
If extra_output is True, the following tuple is also returned:
(parameters_tested, losses)tuple (list of dict, list of int)
List of parameters tested for denoise_function, as a dictionary of kwargs Self-supervised loss for each set of parameters in parameters_tested. Notes The calibration procedure uses a self-supervised mean-square-error loss to evaluate the performance of J-invariant versions of denoise_function. The minimizer of the self-supervised loss is also the minimizer of the ground-truth loss (i.e., the true MSE error) [1]. The returned function can be used on the original noisy image, or other images with similar characteristics.
Increasing the stride increases the performance of best_denoise_function
at the expense of increasing its runtime. It has no effect on the runtime of the calibration. References
1
J. Batson & L. Royer. Noise2Self: Blind Denoising by Self-Supervision, International Conference on Machine Learning, p. 524-533 (2019). Examples >>> from skimage import color, data
>>> from skimage.restoration import denoise_wavelet
>>> import numpy as np
>>> img = color.rgb2gray(data.astronaut()[:50, :50])
>>> noisy = img + 0.5 * img.std() * np.random.randn(*img.shape)
>>> parameters = {'sigma': np.arange(0.1, 0.4, 0.02)}
>>> denoising_function = calibrate_denoiser(noisy, denoise_wavelet,
... denoise_parameters=parameters)
>>> denoised_img = denoising_function(img) | |
doc_3729 | See Migration guide for more details. tf.compat.v1.raw_ops.ResourceScatterNdMax
tf.raw_ops.ResourceScatterNdMax(
ref, indices, updates, use_locking=True, name=None
)
Args
ref A Tensor of type resource. A resource handle. Must be from a VarHandleOp.
indices A Tensor. Must be one of the following types: int32, int64. A Tensor. Must be one of the following types: int32, int64. A tensor of indices into ref.
updates A Tensor. A Tensor. Must have the same type as ref. A tensor of values whose element wise max is taken with ref
use_locking An optional bool. Defaults to True. An optional bool. Defaults to True. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention.
name A name for the operation (optional).
Returns The created Operation. | |
doc_3730 | Returns the first_name plus the last_name, with a space in between. | |
doc_3731 |
Gradient Boosting for classification. GB builds an additive model in a forward stage-wise fashion; it allows for the optimization of arbitrary differentiable loss functions. In each stage n_classes_ regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced. Read more in the User Guide. Parameters
loss{‘deviance’, ‘exponential’}, default=’deviance’
The loss function to be optimized. ‘deviance’ refers to deviance (= logistic regression) for classification with probabilistic outputs. For loss ‘exponential’ gradient boosting recovers the AdaBoost algorithm.
learning_ratefloat, default=0.1
Learning rate shrinks the contribution of each tree by learning_rate. There is a trade-off between learning_rate and n_estimators.
n_estimatorsint, default=100
The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance.
subsamplefloat, default=1.0
The fraction of samples to be used for fitting the individual base learners. If smaller than 1.0 this results in Stochastic Gradient Boosting. subsample interacts with the parameter n_estimators. Choosing subsample < 1.0 leads to a reduction of variance and an increase in bias.
criterion{‘friedman_mse’, ‘mse’, ‘mae’}, default=’friedman_mse’
The function to measure the quality of a split. Supported criteria are ‘friedman_mse’ for the mean squared error with improvement score by Friedman, ‘mse’ for mean squared error, and ‘mae’ for the mean absolute error. The default value of ‘friedman_mse’ is generally the best as it can provide a better approximation in some cases. New in version 0.18. Deprecated since version 0.24: criterion='mae' is deprecated and will be removed in version 1.1 (renaming of 0.26). Use criterion='friedman_mse' or 'mse' instead, as trees should use a least-square criterion in Gradient Boosting.
min_samples_splitint or float, default=2
The minimum number of samples required to split an internal node: If int, then consider min_samples_split as the minimum number. If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split. Changed in version 0.18: Added float values for fractions.
min_samples_leafint or float, default=1
The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. If int, then consider min_samples_leaf as the minimum number. If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node. Changed in version 0.18: Added float values for fractions.
min_weight_fraction_leaffloat, default=0.0
The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.
max_depthint, default=3
The maximum depth of the individual regression estimators. The maximum depth limits the number of nodes in the tree. Tune this parameter for best performance; the best value depends on the interaction of the input variables.
min_impurity_decreasefloat, default=0.0
A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following: N_t / N * (impurity - N_t_R / N_t * right_impurity
- N_t_L / N_t * left_impurity)
where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child. N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed. New in version 0.19.
min_impurity_splitfloat, default=None
Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use min_impurity_decrease instead.
initestimator or ‘zero’, default=None
An estimator object that is used to compute the initial predictions. init has to provide fit and predict_proba. If ‘zero’, the initial raw predictions are set to zero. By default, a DummyEstimator predicting the classes priors is used.
random_stateint, RandomState instance or None, default=None
Controls the random seed given to each Tree estimator at each boosting iteration. In addition, it controls the random permutation of the features at each split (see Notes for more details). It also controls the random spliting of the training data to obtain a validation set if n_iter_no_change is not None. Pass an int for reproducible output across multiple function calls. See Glossary.
max_features{‘auto’, ‘sqrt’, ‘log2’}, int or float, default=None
The number of features to consider when looking for the best split: If int, then consider max_features features at each split. If float, then max_features is a fraction and int(max_features * n_features) features are considered at each split. If ‘auto’, then max_features=sqrt(n_features). If ‘sqrt’, then max_features=sqrt(n_features). If ‘log2’, then max_features=log2(n_features). If None, then max_features=n_features. Choosing max_features < n_features leads to a reduction of variance and an increase in bias. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.
verboseint, default=0
Enable verbose output. If 1 then it prints progress and performance once in a while (the more trees the lower the frequency). If greater than 1 then it prints progress and performance for every tree.
max_leaf_nodesint, default=None
Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just erase the previous solution. See the Glossary.
validation_fractionfloat, default=0.1
The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if n_iter_no_change is set to an integer. New in version 0.20.
n_iter_no_changeint, default=None
n_iter_no_change is used to decide if early stopping will be used to terminate training when validation score is not improving. By default it is set to None to disable early stopping. If set to a number, it will set aside validation_fraction size of the training data as validation and terminate training when validation score is not improving in all of the previous n_iter_no_change numbers of iterations. The split is stratified. New in version 0.20.
tolfloat, default=1e-4
Tolerance for the early stopping. When the loss is not improving by at least tol for n_iter_no_change iterations (if set to a number), the training stops. New in version 0.20.
ccp_alphanon-negative float, default=0.0
Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details. New in version 0.22. Attributes
n_estimators_int
The number of estimators as selected by early stopping (if n_iter_no_change is specified). Otherwise it is set to n_estimators. New in version 0.20.
feature_importances_ndarray of shape (n_features,)
The impurity-based feature importances.
oob_improvement_ndarray of shape (n_estimators,)
The improvement in loss (= deviance) on the out-of-bag samples relative to the previous iteration. oob_improvement_[0] is the improvement in loss of the first stage over the init estimator. Only available if subsample < 1.0
train_score_ndarray of shape (n_estimators,)
The i-th score train_score_[i] is the deviance (= loss) of the model at iteration i on the in-bag sample. If subsample == 1 this is the deviance on the training data.
loss_LossFunction
The concrete LossFunction object.
init_estimator
The estimator that provides the initial predictions. Set via the init argument or loss.init_estimator.
estimators_ndarray of DecisionTreeRegressor of shape (n_estimators, loss_.K)
The collection of fitted sub-estimators. loss_.K is 1 for binary classification, otherwise n_classes.
classes_ndarray of shape (n_classes,)
The classes labels.
n_features_int
The number of data features.
n_classes_int
The number of classes.
max_features_int
The inferred value of max_features. See also
HistGradientBoostingClassifier
Histogram-based Gradient Boosting Classification Tree.
sklearn.tree.DecisionTreeClassifier
A decision tree classifier.
RandomForestClassifier
A meta-estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting.
AdaBoostClassifier
A meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases. Notes The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data and max_features=n_features, if the improvement of the criterion is identical for several splits enumerated during the search of the best split. To obtain a deterministic behaviour during fitting, random_state has to be fixed. References J. Friedman, Greedy Function Approximation: A Gradient Boosting Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. Friedman, Stochastic Gradient Boosting, 1999 T. Hastie, R. Tibshirani and J. Friedman. Elements of Statistical Learning Ed. 2, Springer, 2009. Examples The following example shows how to fit a gradient boosting classifier with 100 decision stumps as weak learners. >>> from sklearn.datasets import make_hastie_10_2
>>> from sklearn.ensemble import GradientBoostingClassifier
>>> X, y = make_hastie_10_2(random_state=0)
>>> X_train, X_test = X[:2000], X[2000:]
>>> y_train, y_test = y[:2000], y[2000:]
>>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0,
... max_depth=1, random_state=0).fit(X_train, y_train)
>>> clf.score(X_test, y_test)
0.913...
Methods
apply(X) Apply trees in the ensemble to X, return leaf indices.
decision_function(X) Compute the decision function of X.
fit(X, y[, sample_weight, monitor]) Fit the gradient boosting model.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class for X.
predict_log_proba(X) Predict class log-probabilities for X.
predict_proba(X) Predict class probabilities for X.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
staged_decision_function(X) Compute decision function of X for each iteration.
staged_predict(X) Predict class at each stage for X.
staged_predict_proba(X) Predict class probabilities at each stage for X.
apply(X) [source]
Apply trees in the ensemble to X, return leaf indices. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted to a sparse csr_matrix. Returns
X_leavesarray-like of shape (n_samples, n_estimators, n_classes)
For each datapoint x in X and for each tree in the ensemble, return the index of the leaf x ends up in each estimator. In the case of binary classification n_classes is 1.
decision_function(X) [source]
Compute the decision function of X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
scorendarray of shape (n_samples, n_classes) or (n_samples,)
The decision function of the input samples, which corresponds to the raw values predicted from the trees of the ensemble . The order of the classes corresponds to that in the attribute classes_. Regression and binary classification produce an array of shape (n_samples,).
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros.
fit(X, y, sample_weight=None, monitor=None) [source]
Fit the gradient boosting model. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
yarray-like of shape (n_samples,)
Target values (strings or integers in classification, real numbers in regression) For classification, labels must correspond to classes.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node.
monitorcallable, default=None
The monitor is called after each iteration with the current iteration, a reference to the estimator and the local variables of _fit_stages as keyword arguments callable(i, self,
locals()). If the callable returns True the fitting procedure is stopped. The monitor can be used for various things such as computing held-out estimates, early stopping, model introspect, and snapshoting. Returns
selfobject
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X) [source]
Predict class for X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
yndarray of shape (n_samples,)
The predicted values.
predict_log_proba(X) [source]
Predict class log-probabilities for X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
pndarray of shape (n_samples, n_classes)
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. Raises
AttributeError
If the loss does not support probabilities.
predict_proba(X) [source]
Predict class probabilities for X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. Raises
AttributeError
If the loss does not support probabilities.
score(X, y, sample_weight=None) [source]
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.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
staged_decision_function(X) [source]
Compute decision function of X for each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
scoregenerator of ndarray of shape (n_samples, k)
The decision function of the input samples, which corresponds to the raw values predicted from the trees of the ensemble . The classes corresponds to that in the attribute classes_. Regression and binary classification are special cases with k == 1, otherwise k==n_classes.
staged_predict(X) [source]
Predict class at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
ygenerator of ndarray of shape (n_samples,)
The predicted value of the input samples.
staged_predict_proba(X) [source]
Predict class probabilities at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
ygenerator of ndarray of shape (n_samples,)
The predicted value of the input samples. | |
doc_3732 |
Compute D^2, the percentage of deviance explained. D^2 is a generalization of the coefficient of determination R^2. R^2 uses squared error and D^2 deviance. Note that those two are equal for family='normal'. D^2 is defined as \(D^2 = 1-\frac{D(y_{true},y_{pred})}{D_{null}}\), \(D_{null}\) is the null deviance, i.e. the deviance of a model with intercept alone, which corresponds to \(y_{pred} = \bar{y}\). The mean \(\bar{y}\) is averaged by sample_weight. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,)
True values of target.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
D^2 of self.predict(X) w.r.t. y. | |
doc_3733 | See Migration guide for more details. tf.compat.v1.raw_ops.Requantize
tf.raw_ops.Requantize(
input, input_min, input_max, requested_output_min, requested_output_max,
out_type, name=None
)
Converts the quantized input tensor into a lower-precision output, using the output range specified with requested_output_min and requested_output_max. [input_min, input_max] are scalar floats that specify the range for the float interpretation of the input data. For example, if input_min is -1.0f and input_max is 1.0f, and we are dealing with quint16 quantized data, then a 0 value in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f.
Args
input A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16.
input_min A Tensor of type float32. The float value that the minimum quantized input value represents.
input_max A Tensor of type float32. The float value that the maximum quantized input value represents.
requested_output_min A Tensor of type float32. The float value that the minimum quantized output value represents.
requested_output_max A Tensor of type float32. The float value that the maximum quantized output value represents.
out_type A tf.DType from: tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16. The type of the output. Should be a lower bit depth than Tinput.
name A name for the operation (optional).
Returns A tuple of Tensor objects (output, output_min, output_max). output A Tensor of type out_type.
output_min A Tensor of type float32.
output_max A Tensor of type float32. | |
doc_3734 | tf.compat.v1.SparseTensorValue(
indices, values, dense_shape
)
Attributes
indices
values
dense_shape | |
doc_3735 |
Blocking call to interact with a figure. Wait until the user clicks n times on the figure, and return the coordinates of each click in a list. There are three possible interactions: Add a point. Remove the most recently added point. Stop the interaction and return the points added so far. The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop. Parameters
nint, default: 1
Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.
timeoutfloat, default: 30 seconds
Number of seconds to wait before timing out. If zero or negative will never timeout.
show_clicksbool, default: True
If True, show a red cross at the location of each click.
mouse_addMouseButton or None, default: MouseButton.LEFT
Mouse button used to add points.
mouse_popMouseButton or None, default: MouseButton.RIGHT
Mouse button used to remove the most recently added point.
mouse_stopMouseButton or None, default: MouseButton.MIDDLE
Mouse button used to stop input. Returns
list of tuples
A list of the clicked (x, y) coordinates. Notes The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.
Examples using matplotlib.pyplot.ginput
Interactive functions | |
doc_3736 | class tkinter.scrolledtext.ScrolledText(master=None, **kw)
frame
The frame which surrounds the text and scroll bar widgets.
vbar
The scroll bar widget. | |
doc_3737 |
Reduces array’s dimension by one, by applying ufunc along one axis. Let \(array.shape = (N_0, ..., N_i, ..., N_{M-1})\). Then \(ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]\) = the result of iterating j over \(range(N_i)\), cumulatively applying ufunc to each \(array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]\). For a one-dimensional array, reduce produces results equivalent to: r = op.identity # op = ufunc
for i in range(len(A)):
r = op(r, A[i])
return r
For example, add.reduce() is equivalent to sum(). Parameters
arrayarray_like
The array to act on.
axisNone or int or tuple of ints, optional
Axis or axes along which a reduction is performed. The default (axis = 0) is perform a reduction over the first dimension of the input array. axis may be negative, in which case it counts from the last to the first axis. New in version 1.7.0. If this is None, a reduction is performed over all the axes. If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before. For operations which are either not commutative or not associative, doing a reduction over multiple axes is not well-defined. The ufuncs do not currently raise an exception in this case, but will likely do so in the future.
dtypedata-type code, optional
The type used to represent the intermediate results. Defaults to the data-type of the output array if this is provided, or the data-type of the input array if no output array is provided.
outndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If not provided or None, a freshly-allocated array is returned. For consistency with ufunc.__call__, if given as a keyword, this may be wrapped in a 1-element tuple. Changed in version 1.13.0: Tuples are allowed for keyword argument.
keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array. New in version 1.7.0.
initialscalar, optional
The value with which to start the reduction. If the ufunc has no identity or the dtype is object, this defaults to None - otherwise it defaults to ufunc.identity. If None is given, the first element of the reduction is used, and an error is thrown if the reduction is empty. New in version 1.15.0.
wherearray_like of bool, optional
A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. Note that for ufuncs like minimum that do not have an identity defined, one has to pass in also initial. New in version 1.17.0. Returns
rndarray
The reduced array. If out was supplied, r is a reference to it. Examples >>> np.multiply.reduce([2,3,5])
30
A multi-dimensional array example: >>> X = np.arange(8).reshape((2,2,2))
>>> X
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.add.reduce(X, 0)
array([[ 4, 6],
[ 8, 10]])
>>> np.add.reduce(X) # confirm: default axis value is 0
array([[ 4, 6],
[ 8, 10]])
>>> np.add.reduce(X, 1)
array([[ 2, 4],
[10, 12]])
>>> np.add.reduce(X, 2)
array([[ 1, 5],
[ 9, 13]])
You can use the initial keyword argument to initialize the reduction with a different value, and where to select specific elements to include: >>> np.add.reduce([10], initial=5)
15
>>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)
array([14., 14.])
>>> a = np.array([10., np.nan, 10])
>>> np.add.reduce(a, where=~np.isnan(a))
20.0
Allows reductions of empty arrays where they would normally fail, i.e. for ufuncs without an identity. >>> np.minimum.reduce([], initial=np.inf)
inf
>>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
array([ 1., 10.])
>>> np.minimum.reduce([])
Traceback (most recent call last):
...
ValueError: zero-size array to reduction operation minimum which has no identity | |
doc_3738 | See Migration guide for more details. tf.compat.v1.raw_ops.QueueDequeueManyV2
tf.raw_ops.QueueDequeueManyV2(
handle, n, component_types, timeout_ms=-1, name=None
)
If the queue is closed and there are fewer than n elements, then an OutOfRange error is returned. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. All of the components in the dequeued tuple will have size n in the 0th dimension. This operation has k outputs, where k is the number of components in the tuples stored in the given queue, and output i is the ith component of the dequeued tuple. N.B. If the queue is empty, this operation will block until n elements have been dequeued (or 'timeout_ms' elapses, if specified).
Args
handle A Tensor of type resource. The handle to a queue.
n A Tensor of type int32. The number of tuples to dequeue.
component_types A list of tf.DTypes that has length >= 1. The type of each component in a tuple.
timeout_ms An optional int. Defaults to -1. If the queue has fewer than n elements, this operation will block for up to timeout_ms milliseconds. Note: This option is not supported yet.
name A name for the operation (optional).
Returns A list of Tensor objects of type component_types. | |
doc_3739 |
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_3740 | set -= other | ...
Update the set, removing elements found in others. | |
doc_3741 |
Set the location of tick in data coords with scalar loc. | |
doc_3742 |
Return the tool object with the given name. For convenience, this passes tool objects through. Parameters
namestr or ToolBase
Name of the tool, or the tool itself.
warnbool, default: True
Whether a warning should be emitted it no tool with the given name exists. Returns
ToolBase or None
The tool or None if no tool with the given name exists. | |
doc_3743 |
Modify in place using non-NA values from another DataFrame. Aligns on indices. There is no return value. Parameters
other:DataFrame, or object coercible into a DataFrame
Should have at least one matching index/column label with the original DataFrame. If a Series is passed, its name attribute must be set, and that will be used as the column name to align with the original DataFrame.
join:{‘left’}, default ‘left’
Only left join is implemented, keeping the index and columns of the original object.
overwrite:bool, default True
How to handle non-NA values for overlapping keys: True: overwrite original DataFrame’s values with values from other. False: only update values that are NA in the original DataFrame.
filter_func:callable(1d-array) -> bool 1d-array, optional
Can choose to replace values other than NA. Return True for values that should be updated.
errors:{‘raise’, ‘ignore’}, default ‘ignore’
If ‘raise’, will raise a ValueError if the DataFrame and other both contain non-NA data in the same place. Returns
None:method directly changes calling object
Raises
ValueError
When errors=’raise’ and there’s overlapping non-NA data. When errors is not either ‘ignore’ or ‘raise’ NotImplementedError
If join != ‘left’ See also dict.update
Similar method for dictionaries. DataFrame.merge
For column(s)-on-column(s) operations. Examples
>>> df = pd.DataFrame({'A': [1, 2, 3],
... 'B': [400, 500, 600]})
>>> new_df = pd.DataFrame({'B': [4, 5, 6],
... 'C': [7, 8, 9]})
>>> df.update(new_df)
>>> df
A B
0 1 4
1 2 5
2 3 6
The DataFrame’s length does not increase as a result of the update, only values at matching index/column labels are updated.
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_df = pd.DataFrame({'B': ['d', 'e', 'f', 'g', 'h', 'i']})
>>> df.update(new_df)
>>> df
A B
0 a d
1 b e
2 c f
For Series, its name attribute must be set.
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_column = pd.Series(['d', 'e'], name='B', index=[0, 2])
>>> df.update(new_column)
>>> df
A B
0 a d
1 b y
2 c e
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_df = pd.DataFrame({'B': ['d', 'e']}, index=[1, 2])
>>> df.update(new_df)
>>> df
A B
0 a x
1 b d
2 c e
If other contains NaNs the corresponding values are not updated in the original dataframe.
>>> df = pd.DataFrame({'A': [1, 2, 3],
... 'B': [400, 500, 600]})
>>> new_df = pd.DataFrame({'B': [4, np.nan, 6]})
>>> df.update(new_df)
>>> df
A B
0 1 4.0
1 2 500.0
2 3 6.0 | |
doc_3744 | URL decode a single string with a given encoding. If the charset is set to None no decoding is performed and raw bytes are returned. Parameters
s (Union[str, bytes]) – the string to unquote.
charset (str) – the charset of the query string. If set to None no decoding will take place.
errors (str) – the error handling for the charset decoding.
unsafe (str) – Return type
str | |
doc_3745 | In-place version of square() | |
doc_3746 | See Migration guide for more details. tf.compat.v1.raw_ops.WriteFile
tf.raw_ops.WriteFile(
filename, contents, name=None
)
creates directory if not existing.
Args
filename A Tensor of type string. scalar. The name of the file to which we write the contents.
contents A Tensor of type string. scalar. The content to be written to the output file.
name A name for the operation (optional).
Returns The created Operation. | |
doc_3747 | tf.keras.applications.densenet.DenseNet201 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.DenseNet201, tf.compat.v1.keras.applications.densenet.DenseNet201
tf.keras.applications.DenseNet201(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000
)
Reference:
Densely Connected Convolutional Networks (CVPR 2017) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For DenseNet, call tf.keras.applications.densenet.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
Returns A Keras model instance. | |
doc_3748 |
Return the snap setting. See set_snap for details. | |
doc_3749 |
Generate coordinates of pixels within circle. Parameters
centertuple
Center coordinate of disk.
radiusdouble
Radius of disk.
shapetuple, optional
Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for disks that exceed the image size. If None, the full extent of the disk is used. Must be at least length 2. Only the first two values are used to determine the extent of the input image. Returns
rr, ccndarray of int
Pixel coordinates of disk. May be used to directly index into an array, e.g. img[rr, cc] = 1. Examples >>> from skimage.draw import disk
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = disk((4, 4), 5)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) | |
doc_3750 | See torch.trace() | |
doc_3751 |
Check for availability of Fortran 77 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled successfully). | |
doc_3752 |
Attributes
key string key
value int32 value | |
doc_3753 | Encode the contents of the input file and write the resulting quoted-printable data to the output file. input and output must be binary file objects. quotetabs, a non-optional flag which controls whether to encode embedded spaces and tabs; when true it encodes such embedded whitespace, and when false it leaves them unencoded. Note that spaces and tabs appearing at the end of lines are always encoded, as per RFC 1521. header is a flag which controls if spaces are encoded as underscores as per RFC 1522. | |
doc_3754 |
Return the Transform instance used by this artist offset. | |
doc_3755 |
Array protocol: struct | |
doc_3756 | Do not interrupt sounds currently playing. | |
doc_3757 | Broken pipe: write to pipe with no readers. Default action is to ignore the signal. Availability: Unix. | |
doc_3758 | Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An OSError is raised if the source code cannot be retrieved. Changed in version 3.3: OSError is raised instead of IOError, now an alias of the former. | |
doc_3759 |
Return a function to preprocess the text before tokenization. Returns
preprocessor: callable
A function to preprocess the text before tokenization. | |
doc_3760 | tf.compat.v1.losses.sigmoid_cross_entropy(
multi_class_labels, logits, weights=1.0, label_smoothing=0, scope=None,
loss_collection=tf.GraphKeys.LOSSES, reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
weights acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If weights is a tensor of shape [batch_size], then the loss weights apply to each corresponding sample. If label_smoothing is nonzero, smooth the labels towards 1/2: new_multiclass_labels = multiclass_labels * (1 - label_smoothing)
+ 0.5 * label_smoothing
Args
multi_class_labels [batch_size, num_classes] target integer labels in {0, 1}.
logits Float [batch_size, num_classes] logits outputs of the network.
weights Optional Tensor whose rank is either 0, or the same rank as multi_class_labels, and must be broadcastable to multi_class_labels (i.e., all dimensions must be either 1, or the same as the corresponding losses dimension).
label_smoothing If greater than 0 then smooth the labels.
scope The scope for the operations performed in computing the loss.
loss_collection collection to which the loss will be added.
reduction Type of reduction to apply to loss.
Returns Weighted loss Tensor of the same type as logits. If reduction is NONE, this has the same shape as logits; otherwise, it is scalar.
Raises
ValueError If the shape of logits doesn't match that of multi_class_labels or if the shape of weights is invalid, or if weights is None. Also if multi_class_labels or logits is None. Eager Compatibility The loss_collection argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a tf.keras.Model. | |
doc_3761 | Module: datetime
Provides the time and datetime types with which the ZoneInfo class is designed to be used. Package tzdata
First-party package maintained by the CPython core developers to supply time zone data via PyPI. Using ZoneInfo
ZoneInfo is a concrete implementation of the datetime.tzinfo abstract base class, and is intended to be attached to tzinfo, either via the constructor, the datetime.replace method or datetime.astimezone: >>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta
>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-10-31 12:00:00-07:00
>>> dt.tzname()
'PDT'
Datetimes constructed in this way are compatible with datetime arithmetic and handle daylight saving time transitions with no further intervention: >>> dt_add = dt + timedelta(days=1)
>>> print(dt_add)
2020-11-01 12:00:00-08:00
>>> dt_add.tzname()
'PST'
These time zones also support the fold attribute introduced in PEP 495. During offset transitions which induce ambiguous times (such as a daylight saving time to standard time transition), the offset from before the transition is used when fold=0, and the offset after the transition is used when fold=1, for example: >>> dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-11-01 01:00:00-07:00
>>> print(dt.replace(fold=1))
2020-11-01 01:00:00-08:00
When converting from another time zone, the fold will be set to the correct value: >>> from datetime import timezone
>>> LOS_ANGELES = ZoneInfo("America/Los_Angeles")
>>> dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)
>>> # Before the PDT -> PST transition
>>> print(dt_utc.astimezone(LOS_ANGELES))
2020-11-01 01:00:00-07:00
>>> # After the PDT -> PST transition
>>> print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES))
2020-11-01 01:00:00-08:00
Data sources The zoneinfo module does not directly provide time zone data, and instead pulls time zone information from the system time zone database or the first-party PyPI package tzdata, if available. Some systems, including notably Windows systems, do not have an IANA database available, and so for projects targeting cross-platform compatibility that require time zone data, it is recommended to declare a dependency on tzdata. If neither system data nor tzdata are available, all calls to ZoneInfo will raise ZoneInfoNotFoundError. Configuring the data sources When ZoneInfo(key) is called, the constructor first searches the directories specified in TZPATH for a file matching key, and on failure looks for a match in the tzdata package. This behavior can be configured in three ways: The default TZPATH when not otherwise specified can be configured at compile time.
TZPATH can be configured using an environment variable. At runtime, the search path can be manipulated using the reset_tzpath() function. Compile-time configuration The default TZPATH includes several common deployment locations for the time zone database (except on Windows, where there are no “well-known” locations for time zone data). On POSIX systems, downstream distributors and those building Python from source who know where their system time zone data is deployed may change the default time zone path by specifying the compile-time option TZPATH (or, more likely, the configure flag --with-tzpath), which should be a string delimited by os.pathsep. On all platforms, the configured value is available as the TZPATH key in sysconfig.get_config_var(). Environment configuration When initializing TZPATH (either at import time or whenever reset_tzpath() is called with no arguments), the zoneinfo module will use the environment variable PYTHONTZPATH, if it exists, to set the search path.
PYTHONTZPATH
This is an os.pathsep-separated string containing the time zone search path to use. It must consist of only absolute rather than relative paths. Relative components specified in PYTHONTZPATH will not be used, but otherwise the behavior when a relative path is specified is implementation-defined; CPython will raise InvalidTZPathWarning, but other implementations are free to silently ignore the erroneous component or raise an exception.
To set the system to ignore the system data and use the tzdata package instead, set PYTHONTZPATH="". Runtime configuration The TZ search path can also be configured at runtime using the reset_tzpath() function. This is generally not an advisable operation, though it is reasonable to use it in test functions that require the use of a specific time zone path (or require disabling access to the system time zones). The ZoneInfo class
class zoneinfo.ZoneInfo(key)
A concrete datetime.tzinfo subclass that represents an IANA time zone specified by the string key. Calls to the primary constructor will always return objects that compare identically; put another way, barring cache invalidation via ZoneInfo.clear_cache(), for all values of key, the following assertion will always be true: a = ZoneInfo(key)
b = ZoneInfo(key)
assert a is b
key must be in the form of a relative, normalized POSIX path, with no up-level references. The constructor will raise ValueError if a non-conforming key is passed. If no file matching key is found, the constructor will raise ZoneInfoNotFoundError.
The ZoneInfo class has two alternate constructors:
classmethod ZoneInfo.from_file(fobj, /, key=None)
Constructs a ZoneInfo object from a file-like object returning bytes (e.g. a file opened in binary mode or an io.BytesIO object). Unlike the primary constructor, this always constructs a new object. The key parameter sets the name of the zone for the purposes of __str__() and __repr__(). Objects created via this constructor cannot be pickled (see pickling).
classmethod ZoneInfo.no_cache(key)
An alternate constructor that bypasses the constructor’s cache. It is identical to the primary constructor, but returns a new object on each call. This is most likely to be useful for testing or demonstration purposes, but it can also be used to create a system with a different cache invalidation strategy. Objects created via this constructor will also bypass the cache of a deserializing process when unpickled. Caution Using this constructor may change the semantics of your datetimes in surprising ways, only use it if you know that you need to.
The following class methods are also available:
classmethod ZoneInfo.clear_cache(*, only_keys=None)
A method for invalidating the cache on the ZoneInfo class. If no arguments are passed, all caches are invalidated and the next call to the primary constructor for each key will return a new instance. If an iterable of key names is passed to the only_keys parameter, only the specified keys will be removed from the cache. Keys passed to only_keys but not found in the cache are ignored. Warning Invoking this function may change the semantics of datetimes using ZoneInfo in surprising ways; this modifies process-wide global state and thus may have wide-ranging effects. Only use it if you know that you need to.
The class has one attribute:
ZoneInfo.key
This is a read-only attribute that returns the value of key passed to the constructor, which should be a lookup key in the IANA time zone database (e.g. America/New_York, Europe/Paris or Asia/Tokyo). For zones constructed from file without specifying a key parameter, this will be set to None. Note Although it is a somewhat common practice to expose these to end users, these values are designed to be primary keys for representing the relevant zones and not necessarily user-facing elements. Projects like CLDR (the Unicode Common Locale Data Repository) can be used to get more user-friendly strings from these keys.
String representations The string representation returned when calling str on a ZoneInfo object defaults to using the ZoneInfo.key attribute (see the note on usage in the attribute documentation): >>> zone = ZoneInfo("Pacific/Kwajalein")
>>> str(zone)
'Pacific/Kwajalein'
>>> dt = datetime(2020, 4, 1, 3, 15, tzinfo=zone)
>>> f"{dt.isoformat()} [{dt.tzinfo}]"
'2020-04-01T03:15:00+12:00 [Pacific/Kwajalein]'
For objects constructed from a file without specifying a key parameter, str falls back to calling repr(). ZoneInfo’s repr is implementation-defined and not necessarily stable between versions, but it is guaranteed not to be a valid ZoneInfo key. Pickle serialization Rather than serializing all transition data, ZoneInfo objects are serialized by key, and ZoneInfo objects constructed from files (even those with a value for key specified) cannot be pickled. The behavior of a ZoneInfo file depends on how it was constructed:
ZoneInfo(key): When constructed with the primary constructor, a ZoneInfo object is serialized by key, and when deserialized, the deserializing process uses the primary and thus it is expected that these are expected to be the same object as other references to the same time zone. For example, if europe_berlin_pkl is a string containing a pickle constructed from ZoneInfo("Europe/Berlin"), one would expect the following behavior: >>> a = ZoneInfo("Europe/Berlin")
>>> b = pickle.loads(europe_berlin_pkl)
>>> a is b
True
ZoneInfo.no_cache(key): When constructed from the cache-bypassing constructor, the ZoneInfo object is also serialized by key, but when deserialized, the deserializing process uses the cache bypassing constructor. If europe_berlin_pkl_nc is a string containing a pickle constructed from ZoneInfo.no_cache("Europe/Berlin"), one would expect the following behavior: >>> a = ZoneInfo("Europe/Berlin")
>>> b = pickle.loads(europe_berlin_pkl_nc)
>>> a is b
False
ZoneInfo.from_file(fobj, /, key=None): When constructed from a file, the ZoneInfo object raises an exception on pickling. If an end user wants to pickle a ZoneInfo constructed from a file, it is recommended that they use a wrapper type or a custom serialization function: either serializing by key or storing the contents of the file object and serializing that. This method of serialization requires that the time zone data for the required key be available on both the serializing and deserializing side, similar to the way that references to classes and functions are expected to exist in both the serializing and deserializing environments. It also means that no guarantees are made about the consistency of results when unpickling a ZoneInfo pickled in an environment with a different version of the time zone data. Functions
zoneinfo.available_timezones()
Get a set containing all the valid keys for IANA time zones available anywhere on the time zone path. This is recalculated on every call to the function. This function only includes canonical zone names and does not include “special” zones such as those under the posix/ and right/ directories, or the posixrules zone. Caution This function may open a large number of files, as the best way to determine if a file on the time zone path is a valid time zone is to read the “magic string” at the beginning. Note These values are not designed to be exposed to end-users; for user facing elements, applications should use something like CLDR (the Unicode Common Locale Data Repository) to get more user-friendly strings. See also the cautionary note on ZoneInfo.key.
zoneinfo.reset_tzpath(to=None)
Sets or resets the time zone search path (TZPATH) for the module. When called with no arguments, TZPATH is set to the default value. Calling reset_tzpath will not invalidate the ZoneInfo cache, and so calls to the primary ZoneInfo constructor will only use the new TZPATH in the case of a cache miss. The to parameter must be a sequence of strings or os.PathLike and not a string, all of which must be absolute paths. ValueError will be raised if something other than an absolute path is passed.
Globals
zoneinfo.TZPATH
A read-only sequence representing the time zone search path – when constructing a ZoneInfo from a key, the key is joined to each entry in the TZPATH, and the first file found is used. TZPATH may contain only absolute paths, never relative paths, regardless of how it is configured. The object that zoneinfo.TZPATH points to may change in response to a call to reset_tzpath(), so it is recommended to use zoneinfo.TZPATH rather than importing TZPATH from zoneinfo or assigning a long-lived variable to zoneinfo.TZPATH. For more information on configuring the time zone search path, see Configuring the data sources.
Exceptions and warnings
exception zoneinfo.ZoneInfoNotFoundError
Raised when construction of a ZoneInfo object fails because the specified key could not be found on the system. This is a subclass of KeyError.
exception zoneinfo.InvalidTZPathWarning
Raised when PYTHONTZPATH contains an invalid component that will be filtered out, such as a relative path. | |
doc_3762 |
Fit the model to the data X which should contain a partial segment of the data. Parameters
Xndarray of shape (n_samples, n_features)
Training data. Returns
selfBernoulliRBM
The fitted model. | |
doc_3763 | Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use. The most common use for this option is when you want to associate extra data with a many-to-many relationship. Note If you don’t want multiple associations between the same instances, add a UniqueConstraint including the from and to fields. Django’s automatically generated many-to-many tables include such a constraint. Note Recursive relationships using an intermediary model can’t determine the reverse accessors names, as they would be the same. You need to set a related_name to at least one of them. If you’d prefer Django not to create a backwards relation, set related_name to '+'. If you don’t specify an explicit through model, there is still an implicit through model class you can use to directly access the table created to hold the association. It has three fields to link the models. If the source and target models differ, the following fields are generated:
id: the primary key of the relation.
<containing_model>_id: the id of the model that declares the ManyToManyField.
<other_model>_id: the id of the model that the ManyToManyField points to. If the ManyToManyField points from and to the same model, the following fields are generated:
id: the primary key of the relation.
from_<model>_id: the id of the instance which points at the model (i.e. the source instance).
to_<model>_id: the id of the instance to which the relationship points (i.e. the target model instance). This class can be used to query associated records for a given model instance like a normal model: Model.m2mfield.through.objects.all() | |
doc_3764 | os.spawnle(mode, path, ..., env)
os.spawnlp(mode, file, ...)
os.spawnlpe(mode, file, ..., env)
os.spawnv(mode, path, args)
os.spawnve(mode, path, args, env)
os.spawnvp(mode, file, args)
os.spawnvpe(mode, file, args, env)
Execute the program path in a new process. (Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the Replacing Older Functions with the subprocess Module section.) If mode is P_NOWAIT, this function returns the process id of the new process; if mode is P_WAIT, returns the process’s exit code if it exits normally, or -signal, where signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the waitpid() function. Note on VxWorks, this function doesn’t return -signal when the new process is killed. Instead it raises OSError exception. The “l” and “v” variants of the spawn* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run. The variants which include a second “p” near the end (spawnlp(), spawnlpe(), spawnvp(), and spawnvpe()) will use the PATH environment variable to locate the program file. When the environment is being replaced (using one of the spawn*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, spawnl(), spawnle(), spawnv(), and spawnve(), will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path. For spawnle(), spawnlpe(), spawnve(), and spawnvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functions spawnl(), spawnlp(), spawnv(), and spawnvp() all cause the new process to inherit the environment of the current process. Note that keys and values in the env dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of 127. As an example, the following calls to spawnlp() and spawnvpe() are equivalent: import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
L = ['cp', 'index.html', '/dev/null']
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
Raises an auditing event os.spawn with arguments mode, path, args, env. Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and spawnvpe() are not available on Windows. spawnle() and spawnve() are not thread-safe on Windows; we advise you to use the subprocess module instead. Changed in version 3.6: Accepts a path-like object. | |
doc_3765 |
Center kernel matrix. Parameters
Kndarray of shape (n_samples1, n_samples2)
Kernel matrix.
copybool, default=True
Set to False to perform inplace computation. Returns
K_newndarray of shape (n_samples1, n_samples2) | |
doc_3766 | operator.__lshift__(a, b)
Return a shifted left by b. | |
doc_3767 | A field which accepts JSON encoded data for an HStoreField. It casts all values (except nulls) to strings. It is represented by an HTML <textarea>. User friendly forms HStoreField is not particularly user friendly in most cases, however it is a useful way to format data from a client-side widget for submission to the server. Note On occasions it may be useful to require or restrict the keys which are valid for a given field. This can be done using the KeysValidator. | |
doc_3768 |
[Deprecated] Render a tex expression to a PNG file. Parameters
filename
A writable filename or fileobject.
texstrstr
A valid mathtext string, e.g., r'IQ: $sigma_i=15$'.
colorcolor
The text color.
dpifloat
The dots-per-inch setting used to render the text.
fontsizeint
The font size in points. Returns
int
Offset of the baseline from the bottom of the image, in pixels. Notes Deprecated since version 3.4. | |
doc_3769 |
Return the ceiling of the input, element-wise. The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \(\lceil x \rceil\). Parameters
xarray_like
Input data.
outndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs
For other keyword-only arguments, see the ufunc docs. Returns
yndarray or scalar
The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar. See also
floor, trunc, rint, fix
Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.ceil(a)
array([-1., -1., -0., 1., 2., 2., 2.]) | |
doc_3770 |
current(newindex=None)
If newindex is specified, sets the combobox value to the element position newindex. Otherwise, returns the index of the current value or -1 if the current value is not in the values list.
get()
Returns the current value of the combobox.
set(value)
Sets the value of the combobox to value. | |
doc_3771 | By default you will not get any tracebacks in user-defined functions, aggregates, converters, authorizer callbacks etc. If you want to debug them, you can call this function with flag set to True. Afterwards, you will get tracebacks from callbacks on sys.stderr. Use False to disable the feature again. | |
doc_3772 |
Construct a Pipeline from the given estimators. This is a shorthand for the Pipeline constructor; it does not require, and does not permit, naming the estimators. Instead, their names will be set to the lowercase of their types automatically. Parameters
*stepslist of estimators.
memorystr or object with the joblib.Memory interface, default=None
Used to cache the fitted transformers of the pipeline. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. Use the attribute named_steps or steps to inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming.
verbosebool, default=False
If True, the time elapsed while fitting each step will be printed as it is completed. Returns
pPipeline
See also
Pipeline
Class for creating a pipeline of transforms with a final estimator. Examples >>> from sklearn.naive_bayes import GaussianNB
>>> from sklearn.preprocessing import StandardScaler
>>> make_pipeline(StandardScaler(), GaussianNB(priors=None))
Pipeline(steps=[('standardscaler', StandardScaler()),
('gaussiannb', GaussianNB())]) | |
doc_3773 | See Migration guide for more details. tf.compat.v1.raw_ops.MatrixDiagV2
tf.raw_ops.MatrixDiagV2(
diagonal, k, num_rows, num_cols, padding_value, name=None
)
Returns a tensor with the contents in diagonal as k[0]-th to k[1]-th diagonals of a matrix, with everything else padded with padding. num_rows and num_cols specify the dimension of the innermost matrix of the output. If both are not specified, the op assumes the innermost matrix is square and infers its size from k and the innermost dimension of diagonal. If only one of them is specified, the op assumes the unspecified value is the smallest possible based on other criteria. Let diagonal have r dimensions [I, J, ..., L, M, N]. The output tensor has rank r+1 with shape [I, J, ..., L, M, num_rows, num_cols] when only one diagonal is given (k is an integer or k[0] == k[1]). Otherwise, it has rank r with shape [I, J, ..., L, num_rows, num_cols]. The second innermost dimension of diagonal has double meaning. When k is scalar or k[0] == k[1], M is part of the batch size [I, J, ..., M], and the output tensor is: output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper
padding_value ; otherwise
Otherwise, M is treated as the number of diagonals for the matrix in the same batch (M = k[1]-k[0]+1), and the output tensor is: output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]
padding_value ; otherwise
where d = n - m, diag_index = k[1] - d, and index_in_diag = n - max(d, 0). For example: # The main diagonal.
diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)
[5, 6, 7, 8]])
tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]],
[[5, 0, 0, 0],
[0, 6, 0, 0],
[0, 0, 7, 0],
[0, 0, 0, 8]]]
# A superdiagonal (per batch).
diagonal = np.array([[1, 2, 3], # Input shape: (2, 3)
[4, 5, 6]])
tf.matrix_diag(diagonal, k = 1)
==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)
[0, 0, 2, 0],
[0, 0, 0, 3],
[0, 0, 0, 0]],
[[0, 4, 0, 0],
[0, 0, 5, 0],
[0, 0, 0, 6],
[0, 0, 0, 0]]]
# A band of diagonals.
diagonals = np.array([[[1, 2, 3], # Input shape: (2, 2, 3)
[4, 5, 0]],
[[6, 7, 9],
[9, 1, 0]]])
tf.matrix_diag(diagonals, k = (-1, 0))
==> [[[1, 0, 0], # Output shape: (2, 3, 3)
[4, 2, 0],
[0, 5, 3]],
[[6, 0, 0],
[9, 7, 0],
[0, 1, 9]]]
# Rectangular matrix.
diagonal = np.array([1, 2]) # Input shape: (2)
tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)
==> [[0, 0, 0, 0], # Output shape: (3, 4)
[1, 0, 0, 0],
[0, 2, 0, 0]]
# Rectangular matrix with inferred num_cols and padding_value = 9.
tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9)
==> [[9, 9], # Output shape: (3, 2)
[1, 9],
[9, 2]]
Args
diagonal A Tensor. Rank r, where r >= 1
k A Tensor of type int32. Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main diagonal, and negative value means subdiagonals. k can be a single integer (for a single diagonal) or a pair of integers specifying the low and high ends of a matrix band. k[0] must not be larger than k[1].
num_rows A Tensor of type int32. The number of rows of the output matrix. If it is not provided, the op assumes the output matrix is a square matrix and infers the matrix size from k and the innermost dimension of diagonal.
num_cols A Tensor of type int32. The number of columns of the output matrix. If it is not provided, the op assumes the output matrix is a square matrix and infers the matrix size from k and the innermost dimension of diagonal.
padding_value A Tensor. Must have the same type as diagonal. The number to fill the area outside the specified diagonal band with. Default is 0.
name A name for the operation (optional).
Returns A Tensor. Has the same type as diagonal. | |
doc_3774 |
Put a value into a specified place in a field defined by a data-type. Place val into a’s field defined by dtype and beginning offset bytes into the field. Parameters
valobject
Value to be placed in field.
dtypedtype object
Data-type of the field in which to place val.
offsetint, optional
The number of bytes into the field at which to place val. Returns
None
See also getfield
Examples >>> x = np.eye(3)
>>> x.getfield(np.float64)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> x.setfield(3, np.int32)
>>> x.getfield(np.int32)
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]], dtype=int32)
>>> x
array([[1.0e+000, 1.5e-323, 1.5e-323],
[1.5e-323, 1.0e+000, 1.5e-323],
[1.5e-323, 1.5e-323, 1.0e+000]])
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]) | |
doc_3775 | Read everything that can be without blocking in I/O (eager). Raise EOFError if connection closed and no cooked data available. Return b'' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence. | |
doc_3776 |
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default. | |
doc_3777 | See Migration guide for more details. tf.compat.v1.distribute.cluster_resolver.TPUClusterResolver
tf.distribute.cluster_resolver.TPUClusterResolver(
tpu=None, zone=None, project=None, job_name='worker',
coordinator_name=None, coordinator_address=None,
credentials='default', service=None, discovery_url=None
)
This is an implementation of cluster resolvers for the Google Cloud TPU service. TPUClusterResolver supports the following distinct environments: Google Compute Engine Google Kubernetes Engine Google internal It can be passed into tf.distribute.TPUStrategy to support TF2 training on Cloud TPUs.
Args
tpu A string corresponding to the TPU to use. It can be the TPU name or TPU worker gRPC address. If not set, it will try automatically resolve the TPU address on Cloud TPUs. If set to "local", it will assume that the TPU is directly connected to the VM instead of over the network.
zone Zone where the TPUs are located. If omitted or empty, we will assume that the zone of the TPU is the same as the zone of the GCE VM, which we will try to discover from the GCE metadata service.
project Name of the GCP project containing Cloud TPUs. If omitted or empty, we will try to discover the project name of the GCE VM from the GCE metadata service.
job_name Name of the TensorFlow job the TPUs belong to.
coordinator_name The name to use for the coordinator. Set to None if the coordinator should not be included in the computed ClusterSpec.
coordinator_address The address of the coordinator (typically an ip:port pair). If set to None, a TF server will be started. If coordinator_name is None, a TF server will not be started even if coordinator_address is None.
credentials GCE Credentials. If None, then we use default credentials from the oauth2client
service The GCE API object returned by the googleapiclient.discovery function. If you specify a custom service object, then the credentials parameter will be ignored.
discovery_url A URL template that points to the location of the discovery service. It should have two parameters {api} and {apiVersion} that when filled in produce an absolute URL to the discovery document for that service. The environment variable 'TPU_API_DISCOVERY_URL' will override this.
Raises
ImportError If the googleapiclient is not installed.
ValueError If no TPUs are specified.
RuntimeError If an empty TPU name is specified and this is running in a Google Cloud environment.
Attributes
environment Returns the current environment which TensorFlow is running in.
task_id Returns the task id this ClusterResolver indicates. In TensorFlow distributed environment, each job may have an applicable task id, which is the index of the instance within its task type. This is useful when user needs to run specific code according to task index. For example, cluster_spec = tf.train.ClusterSpec({
"ps": ["localhost:2222", "localhost:2223"],
"worker": ["localhost:2224", "localhost:2225", "localhost:2226"]
})
# SimpleClusterResolver is used here for illustration; other cluster
# resolvers may be used for other source of task type/id.
simple_resolver = SimpleClusterResolver(cluster_spec, task_type="worker",
task_id=0)
...
if cluster_resolver.task_type == 'worker' and cluster_resolver.task_id == 0:
# Perform something that's only applicable on 'worker' type, id 0. This
# block will run on this particular instance since we've specified this
# task to be a 'worker', id 0 in above cluster resolver.
else:
# Perform something that's only applicable on other ids. This block will
# not run on this particular instance.
Returns None if such information is not available or is not applicable in the current distributed environment, such as training with tf.distribute.cluster_resolver.TPUClusterResolver. For more information, please see tf.distribute.cluster_resolver.ClusterResolver's class docstring.
task_type Returns the task type this ClusterResolver indicates. In TensorFlow distributed environment, each job may have an applicable task type. Valid task types in TensorFlow include 'chief': a worker that is designated with more responsibility, 'worker': a regular worker for training/evaluation, 'ps': a parameter server, or 'evaluator': an evaluator that evaluates the checkpoints for metrics. See Multi-worker configuration for more information about 'chief' and 'worker' task type, which are most commonly used. Having access to such information is useful when user needs to run specific code according to task types. For example, cluster_spec = tf.train.ClusterSpec({
"ps": ["localhost:2222", "localhost:2223"],
"worker": ["localhost:2224", "localhost:2225", "localhost:2226"]
})
# SimpleClusterResolver is used here for illustration; other cluster
# resolvers may be used for other source of task type/id.
simple_resolver = SimpleClusterResolver(cluster_spec, task_type="worker",
task_id=1)
...
if cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. This block
# will run on this particular instance since we've specified this task to
# be a worker in above cluster resolver.
elif cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. This
# block will not run on this particular instance.
Returns None if such information is not available or is not applicable in the current distributed environment, such as training with tf.distribute.experimental.TPUStrategy. For more information, please see tf.distribute.cluster_resolver.ClusterResolver's class doc.
Methods cluster_spec View source
cluster_spec()
Returns a ClusterSpec object based on the latest TPU information. We retrieve the information from the GCE APIs every time this method is called.
Returns A ClusterSpec containing host information returned from Cloud TPUs, or None.
Raises
RuntimeError If the provided TPU is not healthy. connect View source
@staticmethod
connect(
tpu=None, zone=None, project=None
)
Initializes TPU and returns a TPUClusterResolver. This API will connect to remote TPU cluster and initialize the TPU hardwares. Example usage:
resolver = tf.distribute.cluster_resolver.TPUClusterResolver.connect(
tpu='')
It can be viewed as convenient wrapper of the following code:
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initialize_tpu_system(resolver)
Args
tpu A string corresponding to the TPU to use. It can be the TPU name or TPU worker gRPC address. If not set, it will try automatically resolve the TPU address on Cloud TPUs.
zone Zone where the TPUs are located. If omitted or empty, we will assume that the zone of the TPU is the same as the zone of the GCE VM, which we will try to discover from the GCE metadata service.
project Name of the GCP project containing Cloud TPUs. If omitted or empty, we will try to discover the project name of the GCE VM from the GCE metadata service.
Returns An instance of TPUClusterResolver object.
Raises
NotFoundError If no TPU devices found in eager mode. get_job_name View source
get_job_name()
get_master View source
get_master()
get_tpu_system_metadata View source
get_tpu_system_metadata()
Returns the metadata of the TPU system. Users can call this method to get some facts of the TPU system, like total number of cores, number of TPU workers and the devices. E.g.
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tpu_system_medata = resolver.get_tpu_system_metadata()
num_hosts = tpu_system_medata.num_hosts
Returns A tf.tpu.experimental.TPUSystemMetadata object.
master View source
master(
task_type=None, task_id=None, rpc_layer=None
)
Get the Master string to be used for the session. In the normal case, this returns the grpc path (grpc://1.2.3.4:8470) of first instance in the ClusterSpec returned by the cluster_spec function. If a non-TPU name is used when constructing a TPUClusterResolver, that will be returned instead (e.g. If the tpus argument's value when constructing this TPUClusterResolver was 'grpc://10.240.1.2:8470', 'grpc://10.240.1.2:8470' will be returned).
Args
task_type (Optional, string) The type of the TensorFlow task of the master.
task_id (Optional, integer) The index of the TensorFlow task of the master.
rpc_layer (Optional, string) The RPC protocol TensorFlow should use to communicate with TPUs.
Returns string, the connection string to use when creating a session.
Raises
ValueError If none of the TPUs specified exists. num_accelerators View source
num_accelerators(
task_type=None, task_id=None, config_proto=None
)
Returns the number of TPU cores per worker. Connects to the master and list all the devices present in the master, and counts them up. Also verifies that the device counts per host in the cluster is the same before returning the number of TPU cores per host.
Args
task_type Unused.
task_id Unused.
config_proto Used to create a connection to a TPU master in order to retrieve the system metadata.
Raises
RuntimeError If we cannot talk to a TPU worker after retrying or if the number of TPU devices per host is different. __enter__ View source
__enter__()
__exit__ View source
__exit__(
type, value, traceback
) | |
doc_3778 | See Migration guide for more details. tf.compat.v1.math.segment_sum, tf.compat.v1.segment_sum
tf.math.segment_sum(
data, segment_ids, name=None
)
Read the section on segmentation for an explanation of segments. Computes a tensor such that \(output_i = \sum_j data_j\) where sum is over j such that segment_ids[j] == i. If the sum is empty for a given segment ID i, output[i] = 0. For example: c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])
tf.segment_sum(c, tf.constant([0, 0, 1]))
# ==> [[5, 5, 5, 5],
# [5, 6, 7, 8]]
Args
data A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64.
segment_ids A Tensor. Must be one of the following types: int32, int64. A 1-D tensor whose size is equal to the size of data's first dimension. Values should be sorted and can be repeated.
name A name for the operation (optional).
Returns A Tensor. Has the same type as data. | |
doc_3779 | Like make_middleware but for decorating functions. Example usage: @manager.middleware
def application(environ, start_response):
...
The difference to make_middleware is that the function passed will have all the arguments copied from the inner application (name, docstring, module). Parameters
func (WSGIApplication) – Return type
WSGIApplication | |
doc_3780 |
Return the aspect ratio of the axes scaling. This is either "auto" or a float giving the ratio of y/x-scale. | |
doc_3781 |
Unpacks the data and pivots from a LU factorization of a tensor. Returns a tuple of tensors as (the pivots, the L tensor, the U tensor). Parameters
LU_data (Tensor) – the packed LU factorization data
LU_pivots (Tensor) – the packed LU factorization pivots
unpack_data (bool) – flag indicating if the data should be unpacked
unpack_pivots (bool) – flag indicating if the pivots should be unpacked Examples: >>> A = torch.randn(2, 3, 3)
>>> A_LU, pivots = A.lu()
>>> P, A_L, A_U = torch.lu_unpack(A_LU, pivots)
>>>
>>> # can recover A from factorization
>>> A_ = torch.bmm(P, torch.bmm(A_L, A_U))
>>> # LU factorization of a rectangular matrix:
>>> A = torch.randn(2, 3, 2)
>>> A_LU, pivots = A.lu()
>>> P, A_L, A_U = torch.lu_unpack(A_LU, pivots)
>>> P
tensor([[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]],
[[0., 0., 1.],
[0., 1., 0.],
[1., 0., 0.]]])
>>> A_L
tensor([[[ 1.0000, 0.0000],
[ 0.4763, 1.0000],
[ 0.3683, 0.1135]],
[[ 1.0000, 0.0000],
[ 0.2957, 1.0000],
[-0.9668, -0.3335]]])
>>> A_U
tensor([[[ 2.1962, 1.0881],
[ 0.0000, -0.8681]],
[[-1.0947, 0.3736],
[ 0.0000, 0.5718]]])
>>> A_ = torch.bmm(P, torch.bmm(A_L, A_U))
>>> torch.norm(A_ - A)
tensor(2.9802e-08) | |
doc_3782 |
Return Subtraction of series and other, element-wise (binary operator sub). Equivalent to series - other, but with support to substitute a fill_value for missing data in either one of the inputs. Parameters
other:Series or scalar value
fill_value:None or float value, default None (NaN)
Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name
Broadcast across a level, matching Index values on the passed MultiIndex level. Returns
Series
The result of the operation. See also Series.rsub
Reverse of the Subtraction operator, see Python documentation for more details. Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a 1.0
b 1.0
c 1.0
d NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a 1.0
b NaN
d 1.0
e NaN
dtype: float64
>>> a.subtract(b, fill_value=0)
a 0.0
b 1.0
c 1.0
d -1.0
e NaN
dtype: float64 | |
doc_3783 | Return a pair (response, date). date is a datetime object containing the current date and time of the server. | |
doc_3784 | Modifies an already registered fd. This has the same effect as register(fd, eventmask). Attempting to modify a file descriptor that was never registered causes an OSError exception with errno ENOENT to be raised. | |
doc_3785 |
Returns the number of splitting iterations in the cross-validator Parameters
Xobject
Always ignored, exists for compatibility.
yobject
Always ignored, exists for compatibility.
groupsobject
Always ignored, exists for compatibility. Returns
n_splitsint
Returns the number of splitting iterations in the cross-validator. | |
doc_3786 |
Return the recommended gain value for the given nonlinearity function. The values are as follows:
nonlinearity gain
Linear / Identity 11
Conv{1,2,3}D 11
Sigmoid 11
Tanh 53\frac{5}{3}
ReLU 2\sqrt{2}
Leaky Relu 21+negative_slope2\sqrt{\frac{2}{1 + \text{negative\_slope}^2}}
SELU 34\frac{3}{4} Parameters
nonlinearity – the non-linear function (nn.functional name)
param – optional parameter for the non-linear function Examples >>> gain = nn.init.calculate_gain('leaky_relu', 0.2) # leaky_relu with negative_slope=0.2 | |
doc_3787 | Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.) | |
doc_3788 |
Human retina. This image of a retina is useful for demonstrations requiring circular images. Returns
retina(1411, 1411, 3) uint8 ndarray
Retina image in RGB. Notes This image was downloaded from wikimedia. This file is made available under the Creative Commons CC0 1.0 Universal Public Domain Dedication. References
1
Häggström, Mikael (2014). “Medical gallery of Mikael Häggström 2014”. WikiJournal of Medicine 1 (2). DOI:10.15347/wjm/2014.008. ISSN 2002-4436. Public Domain | |
doc_3789 | Release the underlying lock. This method calls the corresponding method on the underlying lock; there is no return value. | |
doc_3790 |
Plot visualization Extra keyword arguments will be passed to matplotlib’s plot. Parameters
axmatplotlib axes, default=None
Axes object to plot on. If None, a new figure and axes is created.
namestr, default=None
Name of ROC Curve for labeling. If None, use the name of the estimator. Returns
displayRocCurveDisplay
Object that stores computed values. | |
doc_3791 |
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data | |
doc_3792 | See Migration guide for more details. tf.compat.v1.raw_ops.UnicodeDecodeWithOffsets
tf.raw_ops.UnicodeDecodeWithOffsets(
input, input_encoding, errors='replace', replacement_char=65533,
replace_control_characters=False, Tsplits=tf.dtypes.int64, name=None
)
The character codepoints for all strings are returned using a single vector char_values, with strings expanded to characters in row-major order. Similarly, the character start byte offsets are returned using a single vector char_to_byte_starts, with strings expanded in row-major order. The row_splits tensor indicates where the codepoints and start offsets for each input string begin and end within the char_values and char_to_byte_starts tensors. In particular, the values for the ith string (in row-major order) are stored in the slice [row_splits[i]:row_splits[i+1]]. Thus:
char_values[row_splits[i]+j] is the Unicode codepoint for the jth character in the ith string (in row-major order).
char_to_bytes_starts[row_splits[i]+j] is the start byte offset for the jth character in the ith string (in row-major order).
row_splits[i+1] - row_splits[i] is the number of characters in the ith string (in row-major order).
Args
input A Tensor of type string. The text to be decoded. Can have any shape. Note that the output is flattened to a vector of char values.
input_encoding A string. Text encoding of the input strings. This is any of the encodings supported by ICU ucnv algorithmic converters. Examples: "UTF-16", "US ASCII", "UTF-8".
errors An optional string from: "strict", "replace", "ignore". Defaults to "replace". Error handling policy when there is invalid formatting found in the input. The value of 'strict' will cause the operation to produce a InvalidArgument error on any invalid input formatting. A value of 'replace' (the default) will cause the operation to replace any invalid formatting in the input with the replacement_char codepoint. A value of 'ignore' will cause the operation to skip any invalid formatting in the input and produce no corresponding output character.
replacement_char An optional int. Defaults to 65533. The replacement character codepoint to be used in place of any invalid formatting in the input when errors='replace'. Any valid unicode codepoint may be used. The default value is the default unicode replacement character is 0xFFFD or U+65533.)
replace_control_characters An optional bool. Defaults to False. Whether to replace the C0 control characters (00-1F) with the replacement_char. Default is false.
Tsplits An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int64.
name A name for the operation (optional).
Returns A tuple of Tensor objects (row_splits, char_values, char_to_byte_starts). row_splits A Tensor of type Tsplits.
char_values A Tensor of type int32.
char_to_byte_starts A Tensor of type int64. | |
doc_3793 | Internal attributes. | |
doc_3794 | Return the system identifier for the current event. | |
doc_3795 | Returns a new tensor with the tangent of the elements of input. outi=tan(inputi)\text{out}_{i} = \tan(\text{input}_{i})
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([-1.2027, -1.7687, 0.4412, -1.3856])
>>> torch.tan(a)
tensor([-2.5930, 4.9859, 0.4722, -5.3366]) | |
doc_3796 | tf.compat.v1.test.get_temp_dir()
There is no need to delete the directory after the test.
Returns The temporary directory. | |
doc_3797 | Autocast Op Reference Op Eligibility
Op-Specific Behavior Ops that can autocast to float16 Ops that can autocast to float32 Ops that promote to the widest input type Prefer binary_cross_entropy_with_logits over binary_cross_entropy Autocasting
class torch.cuda.amp.autocast(enabled=True) [source]
Instances of autocast serve as context managers or decorators that allow regions of your script to run in mixed precision. In these regions, CUDA ops run in an op-specific dtype chosen by autocast to improve performance while maintaining accuracy. See the Autocast Op Reference for details. When entering an autocast-enabled region, Tensors may be any type. You should not call .half() on your model(s) or inputs when using autocasting. autocast should wrap only the forward pass(es) of your network, including the loss computation(s). Backward passes under autocast are not recommended. Backward ops run in the same type that autocast used for corresponding forward ops. Example: # Creates model and optimizer in default precision
model = Net().cuda()
optimizer = optim.SGD(model.parameters(), ...)
for input, target in data:
optimizer.zero_grad()
# Enables autocasting for the forward pass (model + loss)
with autocast():
output = model(input)
loss = loss_fn(output, target)
# Exits the context manager before backward()
loss.backward()
optimizer.step()
See the Automatic Mixed Precision examples for usage (along with gradient scaling) in more complex scenarios (e.g., gradient penalty, multiple models/losses, custom autograd functions). autocast can also be used as a decorator, e.g., on the forward method of your model: class AutocastModel(nn.Module):
...
@autocast()
def forward(self, input):
...
Floating-point Tensors produced in an autocast-enabled region may be float16. After returning to an autocast-disabled region, using them with floating-point Tensors of different dtypes may cause type mismatch errors. If so, cast the Tensor(s) produced in the autocast region back to float32 (or other dtype if desired). If a Tensor from the autocast region is already float32, the cast is a no-op, and incurs no additional overhead. Example: # Creates some tensors in default dtype (here assumed to be float32)
a_float32 = torch.rand((8, 8), device="cuda")
b_float32 = torch.rand((8, 8), device="cuda")
c_float32 = torch.rand((8, 8), device="cuda")
d_float32 = torch.rand((8, 8), device="cuda")
with autocast():
# torch.mm is on autocast's list of ops that should run in float16.
# Inputs are float32, but the op runs in float16 and produces float16 output.
# No manual casts are required.
e_float16 = torch.mm(a_float32, b_float32)
# Also handles mixed input types
f_float16 = torch.mm(d_float32, e_float16)
# After exiting autocast, calls f_float16.float() to use with d_float32
g_float32 = torch.mm(d_float32, f_float16.float())
Type mismatch errors in an autocast-enabled region are a bug; if this is what you observe, please file an issue. autocast(enabled=False) subregions can be nested in autocast-enabled regions. Locally disabling autocast can be useful, for example, if you want to force a subregion to run in a particular dtype. Disabling autocast gives you explicit control over the execution type. In the subregion, inputs from the surrounding region should be cast to dtype before use: # Creates some tensors in default dtype (here assumed to be float32)
a_float32 = torch.rand((8, 8), device="cuda")
b_float32 = torch.rand((8, 8), device="cuda")
c_float32 = torch.rand((8, 8), device="cuda")
d_float32 = torch.rand((8, 8), device="cuda")
with autocast():
e_float16 = torch.mm(a_float32, b_float32)
with autocast(enabled=False):
# Calls e_float16.float() to ensure float32 execution
# (necessary because e_float16 was created in an autocasted region)
f_float32 = torch.mm(c_float32, e_float16.float())
# No manual casts are required when re-entering the autocast-enabled region.
# torch.mm again runs in float16 and produces float16 output, regardless of input types.
g_float16 = torch.mm(d_float32, f_float32)
The autocast state is thread-local. If you want it enabled in a new thread, the context manager or decorator must be invoked in that thread. This affects torch.nn.DataParallel and torch.nn.parallel.DistributedDataParallel when used with more than one GPU per process (see Working with Multiple GPUs). Parameters
enabled (bool, optional, default=True) – Whether autocasting should be enabled in the region.
torch.cuda.amp.custom_fwd(fwd=None, **kwargs) [source]
Helper decorator for forward methods of custom autograd functions (subclasses of torch.autograd.Function). See the example page for more detail. Parameters
cast_inputs (torch.dtype or None, optional, default=None) – If not None, when forward runs in an autocast-enabled region, casts incoming floating-point CUDA Tensors to the target dtype (non-floating-point Tensors are not affected), then executes forward with autocast disabled. If None, forward’s internal ops execute with the current autocast state. Note If the decorated forward is called outside an autocast-enabled region, custom_fwd is a no-op and cast_inputs has no effect.
torch.cuda.amp.custom_bwd(bwd) [source]
Helper decorator for backward methods of custom autograd functions (subclasses of torch.autograd.Function). Ensures that backward executes with the same autocast state as forward. See the example page for more detail.
Gradient Scaling If the forward pass for a particular op has float16 inputs, the backward pass for that op will produce float16 gradients. Gradient values with small magnitudes may not be representable in float16. These values will flush to zero (“underflow”), so the update for the corresponding parameters will be lost. To prevent underflow, “gradient scaling” multiplies the network’s loss(es) by a scale factor and invokes a backward pass on the scaled loss(es). Gradients flowing backward through the network are then scaled by the same factor. In other words, gradient values have a larger magnitude, so they don’t flush to zero. Each parameter’s gradient (.grad attribute) should be unscaled before the optimizer updates the parameters, so the scale factor does not interfere with the learning rate.
class torch.cuda.amp.GradScaler(init_scale=65536.0, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000, enabled=True) [source]
get_backoff_factor() [source]
Returns a Python float containing the scale backoff factor.
get_growth_factor() [source]
Returns a Python float containing the scale growth factor.
get_growth_interval() [source]
Returns a Python int containing the growth interval.
get_scale() [source]
Returns a Python float containing the current scale, or 1.0 if scaling is disabled. Warning get_scale() incurs a CPU-GPU sync.
is_enabled() [source]
Returns a bool indicating whether this instance is enabled.
load_state_dict(state_dict) [source]
Loads the scaler state. If this instance is disabled, load_state_dict() is a no-op. Parameters
state_dict (dict) – scaler state. Should be an object returned from a call to state_dict().
scale(outputs) [source]
Multiplies (‘scales’) a tensor or list of tensors by the scale factor. Returns scaled outputs. If this instance of GradScaler is not enabled, outputs are returned unmodified. Parameters
outputs (Tensor or iterable of Tensors) – Outputs to scale.
set_backoff_factor(new_factor) [source]
Parameters
new_scale (float) – Value to use as the new scale backoff factor.
set_growth_factor(new_factor) [source]
Parameters
new_scale (float) – Value to use as the new scale growth factor.
set_growth_interval(new_interval) [source]
Parameters
new_interval (int) – Value to use as the new growth interval.
state_dict() [source]
Returns the state of the scaler as a dict. It contains five entries:
"scale" - a Python float containing the current scale
"growth_factor" - a Python float containing the current growth factor
"backoff_factor" - a Python float containing the current backoff factor
"growth_interval" - a Python int containing the current growth interval
"_growth_tracker" - a Python int containing the number of recent consecutive unskipped steps. If this instance is not enabled, returns an empty dict. Note If you wish to checkpoint the scaler’s state after a particular iteration, state_dict() should be called after update().
step(optimizer, *args, **kwargs) [source]
step() carries out the following two operations: Internally invokes unscale_(optimizer) (unless unscale_() was explicitly called for optimizer earlier in the iteration). As part of the unscale_(), gradients are checked for infs/NaNs. If no inf/NaN gradients are found, invokes optimizer.step() using the unscaled gradients. Otherwise, optimizer.step() is skipped to avoid corrupting the params. *args and **kwargs are forwarded to optimizer.step(). Returns the return value of optimizer.step(*args, **kwargs). Parameters
optimizer (torch.optim.Optimizer) – Optimizer that applies the gradients.
args – Any arguments.
kwargs – Any keyword arguments. Warning Closure use is not currently supported.
unscale_(optimizer) [source]
Divides (“unscales”) the optimizer’s gradient tensors by the scale factor. unscale_() is optional, serving cases where you need to modify or inspect gradients between the backward pass(es) and step(). If unscale_() is not called explicitly, gradients will be unscaled automatically during step(). Simple example, using unscale_() to enable clipping of unscaled gradients: ...
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
scaler.step(optimizer)
scaler.update()
Parameters
optimizer (torch.optim.Optimizer) – Optimizer that owns the gradients to be unscaled. Note unscale_() does not incur a CPU-GPU sync. Warning unscale_() should only be called once per optimizer per step() call, and only after all gradients for that optimizer’s assigned parameters have been accumulated. Calling unscale_() twice for a given optimizer between each step() triggers a RuntimeError. Warning unscale_() may unscale sparse gradients out of place, replacing the .grad attribute.
update(new_scale=None) [source]
Updates the scale factor. If any optimizer steps were skipped the scale is multiplied by backoff_factor to reduce it. If growth_interval unskipped iterations occurred consecutively, the scale is multiplied by growth_factor to increase it. Passing new_scale sets the scale directly. Parameters
new_scale (float or torch.cuda.FloatTensor, optional, default=None) – New scale factor. Warning update() should only be called at the end of the iteration, after scaler.step(optimizer) has been invoked for all optimizers used this iteration.
Autocast Op Reference Op Eligibility Only CUDA ops are eligible for autocasting. Ops that run in float64 or non-floating-point dtypes are not eligible, and will run in these types whether or not autocast is enabled. Only out-of-place ops and Tensor methods are eligible. In-place variants and calls that explicitly supply an out=... Tensor are allowed in autocast-enabled regions, but won’t go through autocasting. For example, in an autocast-enabled region a.addmm(b, c) can autocast, but a.addmm_(b, c) and a.addmm(b, c, out=d) cannot. For best performance and stability, prefer out-of-place ops in autocast-enabled regions. Ops called with an explicit dtype=... argument are not eligible, and will produce output that respects the dtype argument. Op-Specific Behavior The following lists describe the behavior of eligible ops in autocast-enabled regions. These ops always go through autocasting whether they are invoked as part of a torch.nn.Module, as a function, or as a torch.Tensor method. If functions are exposed in multiple namespaces, they go through autocasting regardless of the namespace. Ops not listed below do not go through autocasting. They run in the type defined by their inputs. However, autocasting may still change the type in which unlisted ops run if they’re downstream from autocasted ops. If an op is unlisted, we assume it’s numerically stable in float16. If you believe an unlisted op is numerically unstable in float16, please file an issue. Ops that can autocast to float16
__matmul__, addbmm, addmm, addmv, addr, baddbmm, bmm, chain_matmul, conv1d, conv2d, conv3d, conv_transpose1d, conv_transpose2d, conv_transpose3d, GRUCell, linear, LSTMCell, matmul, mm, mv, prelu, RNNCell Ops that can autocast to float32
__pow__, __rdiv__, __rpow__, __rtruediv__, acos, asin, binary_cross_entropy_with_logits, cosh, cosine_embedding_loss, cdist, cosine_similarity, cross_entropy, cumprod, cumsum, dist, erfinv, exp, expm1, gelu, group_norm, hinge_embedding_loss, kl_div, l1_loss, layer_norm, log, log_softmax, log10, log1p, log2, margin_ranking_loss, mse_loss, multilabel_margin_loss, multi_margin_loss, nll_loss, norm, normalize, pdist, poisson_nll_loss, pow, prod, reciprocal, rsqrt, sinh, smooth_l1_loss, soft_margin_loss, softmax, softmin, softplus, sum, renorm, tan, triplet_margin_loss Ops that promote to the widest input type These ops don’t require a particular dtype for stability, but take multiple inputs and require that the inputs’ dtypes match. If all of the inputs are float16, the op runs in float16. If any of the inputs is float32, autocast casts all inputs to float32 and runs the op in float32. addcdiv, addcmul, atan2, bilinear, cat, cross, dot, equal, index_put, stack, tensordot Some ops not listed here (e.g., binary ops like add) natively promote inputs without autocasting’s intervention. If inputs are a mixture of float16 and float32, these ops run in float32 and produce float32 output, regardless of whether autocast is enabled. Prefer binary_cross_entropy_with_logits over binary_cross_entropy
The backward passes of torch.nn.functional.binary_cross_entropy() (and torch.nn.BCELoss, which wraps it) can produce gradients that aren’t representable in float16. In autocast-enabled regions, the forward input may be float16, which means the backward gradient must be representable in float16 (autocasting float16 forward inputs to float32 doesn’t help, because that cast must be reversed in backward). Therefore, binary_cross_entropy and BCELoss raise an error in autocast-enabled regions. Many models use a sigmoid layer right before the binary cross entropy layer. In this case, combine the two layers using torch.nn.functional.binary_cross_entropy_with_logits() or torch.nn.BCEWithLogitsLoss. binary_cross_entropy_with_logits and BCEWithLogits are safe to autocast. | |
doc_3798 | Reads the robots.txt URL and feeds it to the parser. | |
doc_3799 |
Alias for set_edgecolor. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.