_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_24600
Create a SubplotBase suitable for a colorbar. The axes is placed in the figure of the parent axes, by resizing and repositioning parent. This function is similar to make_axes. Primary differences are make_axes_gridspec should only be used with a SubplotBase parent. make_axes creates an Axes; make_axes_gridspec creates a SubplotBase. make_axes updates the position of the parent. make_axes_gridspec replaces the grid_spec attribute of the parent with a new one. While this function is meant to be compatible with make_axes, there could be some minor differences. Parameters parentAxes The Axes to use as parent for placing the colorbar. locationNone or {'left', 'right', 'top', 'bottom'} The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset. orientationNone or {'vertical', 'horizontal'} The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception. fractionfloat, default: 0.15 Fraction of original axes to use for colorbar. shrinkfloat, default: 1.0 Fraction by which to multiply the size of the colorbar. aspectfloat, default: 20 Ratio of long to short dimensions. Returns caxSubplotBase The child axes. kwdict The reduced keyword dictionary to be passed when creating the colorbar instance. Other Parameters padfloat, default: 0.05 if vertical, 0.15 if horizontal Fraction of original axes between colorbar and new image axes. anchor(float, float), optional The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal. panchor(float, float), or False, optional The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.
doc_24601
Adds the element subelement to the end of this element’s internal list of subelements. Raises TypeError if subelement is not an Element.
doc_24602
See Migration guide for more details. tf.compat.v1.raw_ops.TakeManySparseFromTensorsMap tf.raw_ops.TakeManySparseFromTensorsMap( sparse_handles, dtype, container='', shared_name='', name=None ) The input sparse_handles must be an int64 matrix of shape [N, 1] where N is the minibatch size and the rows correspond to the output handles of AddSparseToTensorsMap or AddManySparseToTensorsMap. The ranks of the original SparseTensor objects that went into the given input ops must all match. When the final SparseTensor is created, it has rank one higher than the ranks of the incoming SparseTensor objects (they have been concatenated along a new row dimension on the left). The output SparseTensor object's shape values for all dimensions but the first are the max across the input SparseTensor objects' shape values for the corresponding dimensions. Its first shape value is N, the minibatch size. The input SparseTensor objects' indices are assumed ordered in standard lexicographic order. If this is not the case, after this step run SparseReorder to restore index ordering. For example, if the handles represent an input, which is a [2, 3] matrix representing two original SparseTensor objects: index = [ 0] [10] [20] values = [1, 2, 3] shape = [50] and index = [ 2] [10] values = [4, 5] shape = [30] then the final SparseTensor will be: index = [0 0] [0 10] [0 20] [1 2] [1 10] values = [1, 2, 3, 4, 5] shape = [2 50] Args sparse_handles A Tensor of type int64. 1-D, The N serialized SparseTensor objects. Shape: [N]. dtype A tf.DType. The dtype of the SparseTensor objects stored in the SparseTensorsMap. container An optional string. Defaults to "". The container name for the SparseTensorsMap read by this op. shared_name An optional string. Defaults to "". The shared name for the SparseTensorsMap read by this op. It should not be blank; rather the shared_name or unique Operation name of the Op that created the original SparseTensorsMap should be used. name A name for the operation (optional). Returns A tuple of Tensor objects (sparse_indices, sparse_values, sparse_shape). sparse_indices A Tensor of type int64. sparse_values A Tensor of type dtype. sparse_shape A Tensor of type int64.
doc_24603
This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported.
doc_24604
Start monitoring the fd file descriptor for write availability and invoke callback with the specified arguments once fd is available for writing. Use functools.partial() to pass keyword arguments to callback.
doc_24605
Nearest centroid classifier. Each class is represented by its centroid, with test samples classified to the class with the nearest centroid. Read more in the User Guide. Parameters metricstr or callable The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by metrics.pairwise.pairwise_distances for its metric parameter. The centroids for the samples corresponding to each class is the point from which the sum of the distances (according to the metric) of all samples that belong to that particular class are minimized. If the “manhattan” metric is provided, this centroid is the median and for all other metrics, the centroid is now set to be the mean. Changed in version 0.19: metric='precomputed' was deprecated and now raises an error shrink_thresholdfloat, default=None Threshold for shrinking centroids to remove features. Attributes centroids_array-like of shape (n_classes, n_features) Centroid of each class. classes_array of shape (n_classes,) The unique classes labels. See also KNeighborsClassifier Nearest neighbors classifier. Notes When used for text classification with tf-idf vectors, this classifier is also known as the Rocchio classifier. References Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of multiple cancer types by shrunken centroids of gene expression. Proceedings of the National Academy of Sciences of the United States of America, 99(10), 6567-6572. The National Academy of Sciences. Examples >>> from sklearn.neighbors import NearestCentroid >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> clf = NearestCentroid() >>> clf.fit(X, y) NearestCentroid() >>> print(clf.predict([[-0.8, -1]])) [1] Methods fit(X, y) Fit the NearestCentroid model according to the given training data. get_params([deep]) Get parameters for this estimator. predict(X) Perform classification on an array of test vectors 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. fit(X, y) [source] Fit the NearestCentroid model according to the given training data. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. Note that centroid shrinking cannot be used with sparse matrices. yarray-like of shape (n_samples,) Target values (integers) 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] Perform classification on an array of test vectors X. The predicted class C for each sample in X is returned. Parameters Xarray-like of shape (n_samples, n_features) Returns Cndarray of shape (n_samples,) Notes If the metric constructor parameter is “precomputed”, X is assumed to be the distance matrix between the data to be predicted and self.centroids_. 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.
doc_24606
Set up axis ticks and labels to treat data along the zaxis as dates. Parameters tzstr or datetime.tzinfo, default: rcParams["timezone"] (default: 'UTC') The timezone used to create date labels. Notes This function is merely provided for completeness, but 3D axes do not support dates for ticks, and so this may not work as expected.
doc_24607
DataFrame.notnull is an alias for DataFrame.notna. Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). NA values, such as None or numpy.NaN, get mapped to False values. Returns DataFrame Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value. See also DataFrame.notnull Alias of notna. DataFrame.isna Boolean inverse of notna. DataFrame.dropna Omit axes labels with missing values. notna Top-level notna. Examples Show which entries in a DataFrame are not NA. >>> df = pd.DataFrame(dict(age=[5, 6, np.NaN], ... born=[pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... name=['Alfred', 'Batman', ''], ... toy=[None, 'Batmobile', 'Joker'])) >>> df age born name toy 0 5.0 NaT Alfred None 1 6.0 1939-05-27 Batman Batmobile 2 NaN 1940-04-25 Joker >>> df.notna() age born name toy 0 True False True False 1 True True True True 2 False True True True Show which entries in a Series are not NA. >>> ser = pd.Series([5, 6, np.NaN]) >>> ser 0 5.0 1 6.0 2 NaN dtype: float64 >>> ser.notna() 0 True 1 True 2 False dtype: bool
doc_24608
Call self as a function.
doc_24609
Return the clip path.
doc_24610
The ordinal day of the year.
doc_24611
Bases: DeprecationWarning A class for issuing deprecation warnings for Matplotlib users.
doc_24612
Return Datetime Array/Index as object ndarray of datetime.datetime objects. Returns datetimes:ndarray[object]
doc_24613
Alias for set_edgecolor.
doc_24614
class str(object=b'', encoding='utf-8', errors='strict') Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows. If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object). If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode(). See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects. Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python). For example: >>> str(b'Zoot!') "b'Zoot!'" For more information on the str class and its methods, see Text Sequence Type — str and the String Methods section below. To output formatted strings, see the Formatted string literals and Format String Syntax sections. In addition, see the Text Processing Services section.
doc_24615
Applies element-wise, LeakyReLU(x)=max⁡(0,x)+negative_slope∗min⁡(0,x)\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x) See LeakyReLU for more details.
doc_24616
Applies a 2D adaptive max pooling over an input signal composed of several input planes. The output is of size H x W, for any input size. The number of output features is equal to the number of input planes. Parameters output_size – the target output size of the image of the form H x W. Can be a tuple (H, W) or a single H for a square image H x H. H and W can be either a int, or None which means the size will be the same as that of the input. return_indices – if True, will return the indices along with the outputs. Useful to pass to nn.MaxUnpool2d. Default: False Examples >>> # target output size of 5x7 >>> m = nn.AdaptiveMaxPool2d((5,7)) >>> input = torch.randn(1, 64, 8, 9) >>> output = m(input) >>> # target output size of 7x7 (square) >>> m = nn.AdaptiveMaxPool2d(7) >>> input = torch.randn(1, 64, 10, 9) >>> output = m(input) >>> # target output size of 10x7 >>> m = nn.AdaptiveMaxPool2d((None, 7)) >>> input = torch.randn(1, 64, 10, 9) >>> output = m(input)
doc_24617
Return a copy of the array collapsed into one dimension. Parameters order{‘C’, ‘F’, ‘A’, ‘K’}, optional ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’. Returns yndarray A copy of the input array, flattened to one dimension. See also ravel Return a flattened array. flat A 1-D flat iterator over the array. Examples >>> a = np.array([[1,2], [3,4]]) >>> a.flatten() array([1, 2, 3, 4]) >>> a.flatten('F') array([1, 3, 2, 4])
doc_24618
Remove the handles artist from the figure.
doc_24619
The error raised for bad ZIP files. New in version 3.2.
doc_24620
This context is used by the Context constructor as a prototype for new contexts. Changing a field (such a precision) has the effect of changing the default for new contexts created by the Context constructor. This context is most useful in multi-threaded environments. Changing one of the fields before threads are started has the effect of setting system-wide defaults. Changing the fields after threads have started is not recommended as it would require thread synchronization to prevent race conditions. In single threaded environments, it is preferable to not use this context at all. Instead, simply create contexts explicitly as described below. The default values are prec=28, rounding=ROUND_HALF_EVEN, and enabled traps for Overflow, InvalidOperation, and DivisionByZero.
doc_24621
For scalar a, returns the data type with the smallest size and smallest scalar kind which can hold its value. For non-scalar array a, returns the vector’s dtype unmodified. Floating point values are not demoted to integers, and complex values are not demoted to floats. Parameters ascalar or array_like The value whose minimal data type is to be found. Returns outdtype The minimal data type. See also result_type, promote_types, dtype, can_cast Notes New in version 1.6.0. Examples >>> np.min_scalar_type(10) dtype('uint8') >>> np.min_scalar_type(-260) dtype('int16') >>> np.min_scalar_type(3.1) dtype('float16') >>> np.min_scalar_type(1e50) dtype('float64') >>> np.min_scalar_type(np.arange(4,dtype='f8')) dtype('float64')
doc_24622
Close the view, through MsiViewClose().
doc_24623
Collision detection between two sprites, using circles scaled to a ratio. collide_circle_ratio(ratio) -> collided_callable A callable class that checks for collisions between two sprites, using a scaled version of the sprites radius. Is created with a floating point ratio, the instance is then intended to be passed as a collided callback function to the *collide functions. A ratio is a floating point number - 1.0 is the same size, 2.0 is twice as big, and 0.5 is half the size. The created callable tests for collision between two sprites, by testing to see if two circles centered on the sprites overlap, after scaling the circles radius by the stored ratio. If the sprites have a "radius" attribute, that is used to create the circle, otherwise a circle is created that is big enough to completely enclose the sprites rect as given by the "rect" attribute. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "radius" attribute. New in pygame 1.8.1.
doc_24624
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters snapbool or None Possible values: True: Snap vertices to the nearest pixel center. False: Do not modify vertex positions. None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
doc_24625
Alias for set_antialiased.
doc_24626
Return time tuple, compatible with time.localtime().
doc_24627
symtable.symtable(code, filename, compile_type) Return the toplevel SymbolTable for the Python source code. filename is the name of the file containing the code. compile_type is like the mode argument to compile(). Examining Symbol Tables class symtable.SymbolTable A namespace table for a block. The constructor is not public. get_type() Return the type of the symbol table. Possible values are 'class', 'module', and 'function'. get_id() Return the table’s identifier. get_name() Return the table’s name. This is the name of the class if the table is for a class, the name of the function if the table is for a function, or 'top' if the table is global (get_type() returns 'module'). get_lineno() Return the number of the first line in the block this table represents. is_optimized() Return True if the locals in this table can be optimized. is_nested() Return True if the block is a nested class or function. has_children() Return True if the block has nested namespaces within it. These can be obtained with get_children(). get_identifiers() Return a list of names of symbols in this table. lookup(name) Lookup name in the table and return a Symbol instance. get_symbols() Return a list of Symbol instances for names in the table. get_children() Return a list of the nested symbol tables. class symtable.Function A namespace for a function or method. This class inherits SymbolTable. get_parameters() Return a tuple containing names of parameters to this function. get_locals() Return a tuple containing names of locals in this function. get_globals() Return a tuple containing names of globals in this function. get_nonlocals() Return a tuple containing names of nonlocals in this function. get_frees() Return a tuple containing names of free variables in this function. class symtable.Class A namespace of a class. This class inherits SymbolTable. get_methods() Return a tuple containing the names of methods declared in the class. class symtable.Symbol An entry in a SymbolTable corresponding to an identifier in the source. The constructor is not public. get_name() Return the symbol’s name. is_referenced() Return True if the symbol is used in its block. is_imported() Return True if the symbol is created from an import statement. is_parameter() Return True if the symbol is a parameter. is_global() Return True if the symbol is global. is_nonlocal() Return True if the symbol is nonlocal. is_declared_global() Return True if the symbol is declared global with a global statement. is_local() Return True if the symbol is local to its block. is_annotated() Return True if the symbol is annotated. New in version 3.6. is_free() Return True if the symbol is referenced in its block, but not assigned to. is_assigned() Return True if the symbol is assigned to in its block. is_namespace() Return True if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. For example: >>> table = symtable.symtable("def some_func(): pass", "string", "exec") >>> table.lookup("some_func").is_namespace() True Note that a single name can be bound to multiple objects. If the result is True, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace. get_namespaces() Return a list of namespaces bound to this name. get_namespace() Return the namespace bound to this name. If more than one namespace is bound, ValueError is raised.
doc_24628
tf.experimental.numpy.arccosh( x ) Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.arccosh.
doc_24629
With PureWindowsPath, return True if the path is considered reserved under Windows, False otherwise. With PurePosixPath, False is always returned. >>> PureWindowsPath('nul').is_reserved() True >>> PurePosixPath('nul').is_reserved() False File system calls on reserved paths can fail mysteriously or have unintended effects.
doc_24630
Bases: object Create a MathTextParser for the given backend output. get_depth(texstr, dpi=120, fontsize=14)[source] [Deprecated] Get the depth of a mathtext string. Parameters texstrstr A valid mathtext string, e.g., r'IQ: $sigma_i=15$'. dpifloat The dots-per-inch setting used to render the text. Returns int Offset of the baseline from the bottom of the image, in pixels. Notes Deprecated since version 3.4. parse(s, dpi=72, prop=None, *, _force_standard_ps_fonts=False)[source] Parse the given math expression s at the given dpi. If prop is provided, it is a FontProperties object specifying the "default" font to use in the math expression, used for all non-math text. The results are cached, so multiple calls to parse with the same expression should be fast. to_mask(texstr, dpi=120, fontsize=14)[source] [Deprecated] Convert a mathtext string to a grayscale array and depth. Parameters texstrstr A valid mathtext string, e.g., r'IQ: $sigma_i=15$'. dpifloat The dots-per-inch setting used to render the text. fontsizeint The font size in points Returns array2D uint8 alpha Mask array of rasterized tex. depthint Offset of the baseline from the bottom of the image, in pixels. Notes Deprecated since version 3.4. to_png(filename, texstr, color='black', dpi=120, fontsize=14)[source] [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. to_rgba(texstr, color='black', dpi=120, fontsize=14)[source] [Deprecated] Convert a mathtext string to an RGBA array and depth. Parameters 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 array(M, N, 4) array RGBA color values of rasterized tex, colorized with color. depthint Offset of the baseline from the bottom of the image, in pixels. Notes Deprecated since version 3.4.
doc_24631
Base class for raw binary streams. It inherits IOBase. There is no public constructor. Raw binary streams typically provide low-level access to an underlying OS device or API, and do not try to encapsulate it in high-level primitives (this functionality is done at a higher-level in buffered binary streams and text streams, described later in this page). RawIOBase provides these methods in addition to those from IOBase: read(size=-1) Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Otherwise, only one system call is ever made. Fewer than size bytes may be returned if the operating system call returns fewer than size bytes. If 0 bytes are returned, and size was not 0, this indicates end of file. If the object is in non-blocking mode and no bytes are available, None is returned. The default implementation defers to readall() and readinto(). readall() Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary. readinto(b) Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. For example, b might be a bytearray. If the object is in non-blocking mode and no bytes are available, None is returned. write(b) Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. This can be less than the length of b in bytes, depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode. None is returned if the raw stream is set not to block and no single byte could be readily written to it. The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.
doc_24632
Get the transformation used for drawing x-axis labels, ticks and gridlines. The x-direction is in data coordinates and the y-direction is in axis coordinates. Note This transformation is primarily used by the Axis class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations. Examples using matplotlib.axes.Axes.get_xaxis_transform Filling the area between lines hlines and vlines Boxplots Scale invariant angle label Centered spines with arrows Transformations Tutorial
doc_24633
sklearn.metrics.pairwise.nan_euclidean_distances(X, Y=None, *, squared=False, missing_values=nan, copy=True) [source] Calculate the euclidean distances in the presence of missing values. Compute the euclidean distance between each pair of samples in X and Y, where Y=X is assumed if Y=None. When calculating the distance between a pair of samples, this formulation ignores feature coordinates with a missing value in either sample and scales up the weight of the remaining coordinates: dist(x,y) = sqrt(weight * sq. distance from present coordinates) where, weight = Total # of coordinates / # of present coordinates For example, the distance between [3, na, na, 6] and [1, na, 4, 5] is: \[\sqrt{\frac{4}{2}((3-1)^2 + (6-5)^2)}\] If all the coordinates are missing or if there are no common present coordinates then NaN is returned for that pair. Read more in the User Guide. New in version 0.22. Parameters Xarray-like of shape=(n_samples_X, n_features) Yarray-like of shape=(n_samples_Y, n_features), default=None squaredbool, default=False Return squared Euclidean distances. missing_valuesnp.nan or int, default=np.nan Representation of missing value. copybool, default=True Make and use a deep copy of X and Y (if Y exists). Returns distancesndarray of shape (n_samples_X, n_samples_Y) See also paired_distances Distances between pairs of elements of X and Y. References John K. Dixon, “Pattern Recognition with Partly Missing Data”, IEEE Transactions on Systems, Man, and Cybernetics, Volume: 9, Issue: 10, pp. 617 - 621, Oct. 1979. http://ieeexplore.ieee.org/abstract/document/4310090/ Examples >>> from sklearn.metrics.pairwise import nan_euclidean_distances >>> nan = float("NaN") >>> X = [[0, 1], [1, nan]] >>> nan_euclidean_distances(X, X) # distance between rows of X array([[0. , 1.41421356], [1.41421356, 0. ]]) >>> # get distance to origin >>> nan_euclidean_distances(X, [[0, 0]]) array([[1. ], [1.41421356]])
doc_24634
See Migration guide for more details. tf.compat.v1.raw_ops.FresnelCos tf.raw_ops.FresnelCos( x, name=None ) Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64. name A name for the operation (optional). Returns A Tensor. Has the same type as x.
doc_24635
tf.experimental.numpy.sinc( x ) See the NumPy documentation for numpy.sinc.
doc_24636
Clear all cookies and reload cookies from a saved file. revert() can raise the same exceptions as load(). If there is a failure, the object’s state will not be altered.
doc_24637
Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client ip address and current date and time are prefixed to every message logged.
doc_24638
Note The parameter reuse_address is no longer supported, as using SO_REUSEADDR poses a significant security concern for UDP. Explicitly passing reuse_address=True will raise an exception. When multiple processes with differing UIDs assign sockets to an identical UDP socket address with SO_REUSEADDR, incoming packets can become randomly distributed among the sockets. For supported platforms, reuse_port can be used as a replacement for similar functionality. With reuse_port, SO_REUSEPORT is used instead, which specifically prevents processes with differing UIDs from assigning sockets to the same socket address. Create a datagram connection. The socket family can be either AF_INET, AF_INET6, or AF_UNIX, depending on host (or the family argument, if provided). The socket type will be SOCK_DGRAM. protocol_factory must be a callable returning a protocol implementation. A tuple of (transport, protocol) is returned on success. Other arguments: local_addr, if given, is a (local_host, local_port) tuple used to bind the socket to locally. The local_host and local_port are looked up using getaddrinfo(). remote_addr, if given, is a (remote_host, remote_port) tuple used to connect the socket to a remote address. The remote_host and remote_port are looked up using getaddrinfo(). family, proto, flags are the optional address family, protocol and flags to be passed through to getaddrinfo() for host resolution. If given, these should all be integers from the corresponding socket module constants. reuse_port tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows and some Unixes. If the SO_REUSEPORT constant is not defined then this capability is unsupported. allow_broadcast tells the kernel to allow this endpoint to send messages to the broadcast address. sock can optionally be specified in order to use a preexisting, already connected, socket.socket object to be used by the transport. If specified, local_addr and remote_addr should be omitted (must be None). See UDP echo client protocol and UDP echo server protocol examples. Changed in version 3.4.4: The family, proto, flags, reuse_address, reuse_port, *allow_broadcast, and sock parameters were added. Changed in version 3.8.1: The reuse_address parameter is no longer supported due to security concerns. Changed in version 3.8: Added support for Windows.
doc_24639
Convert coefficient matrix to dense array format. Converts the coef_ member (back) to a numpy.ndarray. This is the default format of coef_ and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op. Returns self Fitted estimator.
doc_24640
See Migration guide for more details. tf.compat.v1.register_tensor_conversion_function tf.register_tensor_conversion_function( base_type, conversion_func, priority=100 ) The conversion function must have the following signature: def conversion_func(value, dtype=None, name=None, as_ref=False): # ... It must return a Tensor with the given dtype if specified. If the conversion function creates a new Tensor, it should use the given name if specified. All exceptions will be propagated to the caller. The conversion function may return NotImplemented for some inputs. In this case, the conversion process will continue to try subsequent conversion functions. If as_ref is true, the function must return a Tensor reference, such as a Variable. Note: The conversion functions will execute in order of priority, followed by order of registration. To ensure that a conversion function F runs before another conversion function G, ensure that F is registered with a smaller priority than G. Args base_type The base type or tuple of base types for all objects that conversion_func accepts. conversion_func A function that converts instances of base_type to Tensor. priority Optional integer that indicates the priority for applying this conversion function. Conversion functions with smaller priority values run earlier than conversion functions with larger priority values. Defaults to 100. Raises TypeError If the arguments do not have the appropriate type.
doc_24641
Generate package __config__.py file containing system_info information used during building the package. This file is installed to the package installation directory.
doc_24642
Integrate a Chebyshev series. Returns the Chebyshev series coefficients c integrated m times from lbnd along axis. At each iteration the resulting series is multiplied by scl and an integration constant, k, is added. The scaling factor is for use in a linear change of variable. (“Buyer beware”: note that, depending on what one is doing, one may want scl to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument c is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series T_0 + 2*T_1 + 3*T_2 while [[1,2],[1,2]] represents 1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y) if axis=0 is x and axis=1 is y. Parameters carray_like Array of Chebyshev series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. mint, optional Order of integration, must be positive. (Default: 1) k{[], list, scalar}, optional Integration constant(s). The value of the first integral at zero is the first value in the list, the value of the second integral at zero is the second value, etc. If k == [] (the default), all constants are set to zero. If m == 1, a single scalar can be given instead of a list. lbndscalar, optional The lower bound of the integral. (Default: 0) sclscalar, optional Following each integration the result is multiplied by scl before the integration constant is added. (Default: 1) axisint, optional Axis over which the integral is taken. (Default: 0). New in version 1.7.0. Returns Sndarray C-series coefficients of the integral. Raises ValueError If m < 1, len(k) > m, np.ndim(lbnd) != 0, or np.ndim(scl) != 0. See also chebder Notes Note that the result of each integration is multiplied by scl. Why is this important to note? Say one is making a linear change of variable \(u = ax + b\) in an integral relative to x. Then \(dx = du/a\), so one will need to set scl equal to \(1/a\)- perhaps not what one would have first thought. Also note that, in general, the result of integrating a C-series needs to be “reprojected” onto the C-series basis set. Thus, typically, the result of this function is “unintuitive,” albeit correct; see Examples section below. Examples >>> from numpy.polynomial import chebyshev as C >>> c = (1,2,3) >>> C.chebint(c) array([ 0.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,3) array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, # may vary 0.00625 ]) >>> C.chebint(c, k=3) array([ 3.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,lbnd=-2) array([ 8.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,scl=-2) array([-1., 1., -1., -1.])
doc_24643
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters rendererRendererBase subclass. Notes This method is overridden in the Artist subclasses.
doc_24644
Return the Figure instance the artist belongs to.
doc_24645
This allows better BC support for load_state_dict(). In state_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See _load_from_state_dict on how to use this information in loading. If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
doc_24646
Minimum Covariance Determinant (MCD): robust estimator of covariance. The Minimum Covariance Determinant covariance estimator is to be applied on Gaussian-distributed data, but could still be relevant on data drawn from a unimodal, symmetric distribution. It is not meant to be used with multi-modal data (the algorithm used to fit a MinCovDet object is likely to fail in such a case). One should consider projection pursuit methods to deal with multi-modal datasets. Read more in the User Guide. Parameters store_precisionbool, default=True Specify if the estimated precision is stored. assume_centeredbool, default=False If True, the support of the robust location and the covariance estimates is computed, and a covariance estimate is recomputed from it, without centering the data. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, the robust location and covariance are directly computed with the FastMCD algorithm without additional treatment. support_fractionfloat, default=None The proportion of points to be included in the support of the raw MCD estimate. Default is None, which implies that the minimum value of support_fraction will be used within the algorithm: (n_sample + n_features + 1) / 2. The parameter must be in the range (0, 1). random_stateint, RandomState instance or None, default=None Determines the pseudo random number generator for shuffling the data. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Attributes raw_location_ndarray of shape (n_features,) The raw robust estimated location before correction and re-weighting. raw_covariance_ndarray of shape (n_features, n_features) The raw robust estimated covariance before correction and re-weighting. raw_support_ndarray of shape (n_samples,) A mask of the observations that have been used to compute the raw robust estimates of location and shape, before correction and re-weighting. location_ndarray of shape (n_features,) Estimated robust location. covariance_ndarray of shape (n_features, n_features) Estimated robust covariance matrix. precision_ndarray of shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) support_ndarray of shape (n_samples,) A mask of the observations that have been used to compute the robust estimates of location and shape. dist_ndarray of shape (n_samples,) Mahalanobis distances of the training set (on which fit is called) observations. References Rouseeuw1984 P. J. Rousseeuw. Least median of squares regression. J. Am Stat Ass, 79:871, 1984. Rousseeuw A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS ButlerDavies R. W. Butler, P. L. Davies and M. Jhun, Asymptotics For The Minimum Covariance Determinant Estimator, The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400 Examples >>> import numpy as np >>> from sklearn.covariance import MinCovDet >>> from sklearn.datasets import make_gaussian_quantiles >>> real_cov = np.array([[.8, .3], ... [.3, .4]]) >>> rng = np.random.RandomState(0) >>> X = rng.multivariate_normal(mean=[0, 0], ... cov=real_cov, ... size=500) >>> cov = MinCovDet(random_state=0).fit(X) >>> cov.covariance_ array([[0.7411..., 0.2535...], [0.2535..., 0.3053...]]) >>> cov.location_ array([0.0813... , 0.0427...]) Methods correct_covariance(data) Apply a correction to raw Minimum Covariance Determinant estimates. error_norm(comp_cov[, norm, scaling, squared]) Computes the Mean Squared Error between two covariance estimators. fit(X[, y]) Fits a Minimum Covariance Determinant with the FastMCD algorithm. get_params([deep]) Get parameters for this estimator. get_precision() Getter for the precision matrix. mahalanobis(X) Computes the squared Mahalanobis distances of given observations. reweight_covariance(data) Re-weight raw Minimum Covariance Determinant estimates. score(X_test[, y]) Computes the log-likelihood of a Gaussian data set with self.covariance_ as an estimator of its covariance matrix. set_params(**params) Set the parameters of this estimator. correct_covariance(data) [source] Apply a correction to raw Minimum Covariance Determinant estimates. Correction using the empirical correction factor suggested by Rousseeuw and Van Driessen in [RVD]. Parameters dataarray-like of shape (n_samples, n_features) The data matrix, with p features and n samples. The data set must be the one which was used to compute the raw estimates. Returns covariance_correctedndarray of shape (n_features, n_features) Corrected robust covariance estimate. References RVD A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS error_norm(comp_cov, norm='frobenius', scaling=True, squared=True) [source] Computes the Mean Squared Error between two covariance estimators. (In the sense of the Frobenius norm). Parameters comp_covarray-like of shape (n_features, n_features) The covariance to compare with. norm{“frobenius”, “spectral”}, default=”frobenius” The type of norm used to compute the error. Available error types: - ‘frobenius’ (default): sqrt(tr(A^t.A)) - ‘spectral’: sqrt(max(eigenvalues(A^t.A)) where A is the error (comp_cov - self.covariance_). scalingbool, default=True If True (default), the squared error norm is divided by n_features. If False, the squared error norm is not rescaled. squaredbool, default=True Whether to compute the squared error norm or the error norm. If True (default), the squared error norm is returned. If False, the error norm is returned. Returns resultfloat The Mean Squared Error (in the sense of the Frobenius norm) between self and comp_cov covariance estimators. fit(X, y=None) [source] Fits a Minimum Covariance Determinant with the FastMCD algorithm. Parameters Xarray-like of shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y: Ignored Not used, present for API consistency by convention. 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. get_precision() [source] Getter for the precision matrix. Returns precision_array-like of shape (n_features, n_features) The precision matrix associated to the current covariance object. mahalanobis(X) [source] Computes the squared Mahalanobis distances of given observations. Parameters Xarray-like of shape (n_samples, n_features) The observations, the Mahalanobis distances of the which we compute. Observations are assumed to be drawn from the same distribution than the data used in fit. Returns distndarray of shape (n_samples,) Squared Mahalanobis distances of the observations. reweight_covariance(data) [source] Re-weight raw Minimum Covariance Determinant estimates. Re-weight observations using Rousseeuw’s method (equivalent to deleting outlying observations from the data set before computing location and covariance estimates) described in [RVDriessen]. Parameters dataarray-like of shape (n_samples, n_features) The data matrix, with p features and n samples. The data set must be the one which was used to compute the raw estimates. Returns location_reweightedndarray of shape (n_features,) Re-weighted robust location estimate. covariance_reweightedndarray of shape (n_features, n_features) Re-weighted robust covariance estimate. support_reweightedndarray of shape (n_samples,), dtype=bool A mask of the observations that have been used to compute the re-weighted robust location and covariance estimates. References RVDriessen A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS score(X_test, y=None) [source] Computes the log-likelihood of a Gaussian data set with self.covariance_ as an estimator of its covariance matrix. Parameters X_testarray-like of shape (n_samples, n_features) Test data of which we compute the likelihood, where n_samples is the number of samples and n_features is the number of features. X_test is assumed to be drawn from the same distribution than the data used in fit (including centering). yIgnored Not used, present for API consistency by convention. Returns resfloat The likelihood of the data set with self.covariance_ as an estimator of its covariance matrix. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_24647
Return a backend-specific tuple to return to the backend after all processing is done.
doc_24648
Return the number of ways to choose k items from n items without repetition and with order. Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n. If k is not specified or is None, then k defaults to n and the function returns n!. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. New in version 3.8.
doc_24649
Return the size of the buffer used in ufuncs. Returns getbufsizeint Size of ufunc buffer in bytes.
doc_24650
Efficiently infer the type of a passed val, or list-like array of values. Return a string describing the type. Parameters value:scalar, list, ndarray, or pandas type skipna:bool, default True Ignore NaN values when inferring the type. Returns str Describing the common type of the input data. Results can include: string bytes floating integer mixed-integer mixed-integer-float decimal complex categorical boolean datetime64 datetime date timedelta64 timedelta time period mixed unknown-array Raises TypeError If ndarray-like but cannot infer the dtype Notes ‘mixed’ is the catchall for anything that is not otherwise specialized ‘mixed-integer-float’ are floats and integers ‘mixed-integer’ are integers mixed with non-integers ‘unknown-array’ is the catchall for something that is an array (has a dtype attribute), but has a dtype unknown to pandas (e.g. external extension array) Examples >>> import datetime >>> infer_dtype(['foo', 'bar']) 'string' >>> infer_dtype(['a', np.nan, 'b'], skipna=True) 'string' >>> infer_dtype(['a', np.nan, 'b'], skipna=False) 'mixed' >>> infer_dtype([b'foo', b'bar']) 'bytes' >>> infer_dtype([1, 2, 3]) 'integer' >>> infer_dtype([1, 2, 3.5]) 'mixed-integer-float' >>> infer_dtype([1.0, 2.0, 3.5]) 'floating' >>> infer_dtype(['a', 1]) 'mixed-integer' >>> infer_dtype([Decimal(1), Decimal(2.0)]) 'decimal' >>> infer_dtype([True, False]) 'boolean' >>> infer_dtype([True, False, np.nan]) 'boolean' >>> infer_dtype([pd.Timestamp('20130101')]) 'datetime' >>> infer_dtype([datetime.date(2013, 1, 1)]) 'date' >>> infer_dtype([np.datetime64('2013-01-01')]) 'datetime64' >>> infer_dtype([datetime.timedelta(0, 1, 1)]) 'timedelta' >>> infer_dtype(pd.Series(list('aabc')).astype('category')) 'categorical'
doc_24651
A hardware setting.
doc_24652
See Migration guide for more details. tf.compat.v1.debugging.assert_rank tf.compat.v1.assert_rank( x, rank, data=None, summarize=None, message=None, name=None ) Example of adding a dependency to an operation: with tf.control_dependencies([tf.compat.v1.assert_rank(x, 2)]): output = tf.reduce_sum(x) Args x Numeric Tensor. rank Scalar integer Tensor. data The tensors to print out if the condition is False. Defaults to error message and the shape of x. summarize Print this many entries of each tensor. message A string to prefix to the default message. name A name for this operation (optional). Defaults to "assert_rank". Returns Op raising InvalidArgumentError unless x has specified rank. If static checks determine x has correct rank, a no_op is returned. Raises ValueError If static checks determine x has wrong rank.
doc_24653
Call self as a function.
doc_24654
Vertical bar plot. A bar plot is a plot that presents categorical data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, and the other axis represents a measured value. Parameters x:label or position, optional Allows plotting of one column versus another. If not specified, the index of the DataFrame is used. y:label or position, optional Allows plotting of one column versus another. If not specified, all numerical columns are used. color:str, array-like, or dict, optional The color for each of the DataFrame’s columns. Possible values are: A single color string referred to by name, RGB or RGBA code, for instance ‘red’ or ‘#a98d19’. A sequence of color strings referred to by name, RGB or RGBA code, which will be used for each column recursively. For instance [‘green’,’yellow’] each column’s bar will be filled in green or yellow, alternatively. If there is only a single column to be plotted, then only the first color from the color list will be used. A dict of the form {column name:color}, so that each column will be colored accordingly. For example, if your columns are called a and b, then passing {‘a’: ‘green’, ‘b’: ‘red’} will color bars for column a in green and bars for column b in red. New in version 1.1.0. **kwargs Additional keyword arguments are documented in DataFrame.plot(). Returns matplotlib.axes.Axes or np.ndarray of them An ndarray is returned with one matplotlib.axes.Axes per column when subplots=True. See also DataFrame.plot.barh Horizontal bar plot. DataFrame.plot Make plots of a DataFrame. matplotlib.pyplot.bar Make a bar plot with matplotlib. Examples Basic plot. >>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]}) >>> ax = df.plot.bar(x='lab', y='val', rot=0) Plot a whole dataframe to a bar plot. Each column is assigned a distinct color, and each row is nested in a group along the horizontal axis. >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] >>> index = ['snail', 'pig', 'elephant', ... 'rabbit', 'giraffe', 'coyote', 'horse'] >>> df = pd.DataFrame({'speed': speed, ... 'lifespan': lifespan}, index=index) >>> ax = df.plot.bar(rot=0) Plot stacked bar charts for the DataFrame >>> ax = df.plot.bar(stacked=True) Instead of nesting, the figure can be split by column with subplots=True. In this case, a numpy.ndarray of matplotlib.axes.Axes are returned. >>> axes = df.plot.bar(rot=0, subplots=True) >>> axes[1].legend(loc=2) If you don’t like the default colours, you can specify how you’d like each column to be colored. >>> axes = df.plot.bar( ... rot=0, subplots=True, color={"speed": "red", "lifespan": "green"} ... ) >>> axes[1].legend(loc=2) Plot a single column. >>> ax = df.plot.bar(y='speed', rot=0) Plot only selected categories for the DataFrame. >>> ax = df.plot.bar(x='lifespan', rot=0)
doc_24655
Alias for set_facecolor.
doc_24656
Draw samples from a binomial distribution. Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval [0,1]. (n may be input as a float, but it is truncated to an integer in use) Note New code should use the binomial method of a default_rng() instance instead; please see the Quick Start. Parameters nint or array_like of ints Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers. pfloat or array_like of floats Parameter of the distribution, >= 0 and <=1. sizeint or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if n and p are both scalars. Otherwise, np.broadcast(n, p).size samples are drawn. Returns outndarray or scalar Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials. See also scipy.stats.binom probability density function, distribution or cumulative density function, etc. Generator.binomial which should be used for new code. Notes The probability density for the binomial distribution is \[P(N) = \binom{n}{N}p^N(1-p)^{n-N},\] where \(n\) is the number of trials, \(p\) is the probability of success, and \(N\) is the number of successes. When estimating the standard error of a proportion in a population by using a random sample, the normal distribution works well unless the product p*n <=5, where p = population proportion estimate, and n = number of samples, in which case the binomial distribution is used instead. For example, a sample of 15 people shows 4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so the binomial distribution should be used in this case. References 1 Dalgaard, Peter, “Introductory Statistics with R”, Springer-Verlag, 2002. 2 Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002. 3 Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972. 4 Weisstein, Eric W. “Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html 5 Wikipedia, “Binomial distribution”, https://en.wikipedia.org/wiki/Binomial_distribution Examples Draw samples from the distribution: >>> n, p = 10, .5 # number of trials, probability of each trial >>> s = np.random.binomial(n, p, 1000) # result of flipping a coin 10 times, tested 1000 times. A real world example. A company drills 9 wild-cat oil exploration wells, each with an estimated probability of success of 0.1. All nine wells fail. What is the probability of that happening? Let’s do 20,000 trials of the model, and count the number that generate zero positive results. >>> sum(np.random.binomial(9, 0.1, 20000) == 0)/20000. # answer = 0.38885, or 38%.
doc_24657
class sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep) The scheduler class defines a generic interface to scheduling events. It needs two functions to actually deal with the “outside world” — timefunc should be callable without arguments, and return a number (the “time”, in any units whatsoever). The delayfunc function should be callable with one argument, compatible with the output of timefunc, and should delay that many time units. delayfunc will also be called with the argument 0 after each event is run to allow other threads an opportunity to run in multi-threaded applications. Changed in version 3.3: timefunc and delayfunc parameters are optional. Changed in version 3.3: scheduler class can be safely used in multi-threaded environments. Example: >>> import sched, time >>> s = sched.scheduler(time.time, time.sleep) >>> def print_time(a='default'): ... print("From print_time", time.time(), a) ... >>> def print_some_times(): ... print(time.time()) ... s.enter(10, 1, print_time) ... s.enter(5, 2, print_time, argument=('positional',)) ... s.enter(5, 1, print_time, kwargs={'a': 'keyword'}) ... s.run() ... print(time.time()) ... >>> print_some_times() 930343690.257 From print_time 930343695.274 positional From print_time 930343695.275 keyword From print_time 930343700.273 default 930343700.276 Scheduler Objects scheduler instances have the following methods and attributes: scheduler.enterabs(time, priority, action, argument=(), kwargs={}) Schedule a new event. The time argument should be a numeric type compatible with the return value of the timefunc function passed to the constructor. Events scheduled for the same time will be executed in the order of their priority. A lower number represents a higher priority. Executing the event means executing action(*argument, **kwargs). argument is a sequence holding the positional arguments for action. kwargs is a dictionary holding the keyword arguments for action. Return value is an event which may be used for later cancellation of the event (see cancel()). Changed in version 3.3: argument parameter is optional. Changed in version 3.3: kwargs parameter was added. scheduler.enter(delay, priority, action, argument=(), kwargs={}) Schedule an event for delay more time units. Other than the relative time, the other arguments, the effect and the return value are the same as those for enterabs(). Changed in version 3.3: argument parameter is optional. Changed in version 3.3: kwargs parameter was added. scheduler.cancel(event) Remove the event from the queue. If event is not an event currently in the queue, this method will raise a ValueError. scheduler.empty() Return True if the event queue is empty. scheduler.run(blocking=True) Run all scheduled events. This method will wait (using the delayfunc() function passed to the constructor) for the next event, then execute it and so on until there are no more scheduled events. If blocking is false executes the scheduled events due to expire soonest (if any) and then return the deadline of the next scheduled call in the scheduler (if any). Either action or delayfunc can raise an exception. In either case, the scheduler will maintain a consistent state and propagate the exception. If an exception is raised by action, the event will not be attempted in future calls to run(). If a sequence of events takes longer to run than the time available before the next event, the scheduler will simply fall behind. No events will be dropped; the calling code is responsible for canceling events which are no longer pertinent. Changed in version 3.3: blocking parameter was added. scheduler.queue Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a named tuple with the following fields: time, priority, action, argument, kwargs.
doc_24658
Return the local number (population) of pixels. The number of pixels is defined as the number of pixels which are included in the structuring element and the mask. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters image2-D array (uint8, uint16) Input image. selem2-D array The neighborhood expressed as a 2-D array of 1’s and 0’s. out2-D array (same dtype as input) If None, a new array is allocated. maskndarray Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). shift_x, shift_yint Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). p0, p1float in [0, …, 1] Define the [p0, p1] percentile interval to be considered for computing the value. Returns out2-D array (same dtype as input image) Output image.
doc_24659
This attribute controls the maximum length of diffs output by assert methods that report diffs on failure. It defaults to 80*8 characters. Assert methods affected by this attribute are assertSequenceEqual() (including all the sequence comparison methods that delegate to it), assertDictEqual() and assertMultiLineEqual(). Setting maxDiff to None means that there is no maximum length of diffs. New in version 3.2.
doc_24660
Select image on display using index into image collection.
doc_24661
Get or set the PRNG state Returns statedict Dictionary containing the information required to describe the state of the PRNG
doc_24662
The save_related method is given the HttpRequest, the parent ModelForm instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed. Here you can do any pre- or post-save operations for objects related to the parent. Note that at this point the parent object and its form have already been saved.
doc_24663
Return the sketch parameters for the artist. Returns tuple or None A 3-tuple with the following elements: scale: The amplitude of the wiggle perpendicular to the source line. length: The length of the wiggle along the line. randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
doc_24664
Return the clipbox.
doc_24665
Create and return a SubplotSpec instance. Parameters loc(int, int) The position of the subplot in the grid as (row_index, column_index). rowspan, colspanint, default: 1 The number of rows and columns the subplot should span in the grid.
doc_24666
Assigns values from one structured array to another by field name. Normally in numpy >= 1.14, assignment of one structured array to another copies fields “by position”, meaning that the first field from the src is copied to the first field of the dst, and so on, regardless of field name. This function instead copies “by field name”, such that fields in the dst are assigned from the identically named field in the src. This applies recursively for nested structures. This is how structure assignment worked in numpy >= 1.6 to <= 1.13. Parameters dstndarray srcndarray The source and destination arrays during assignment. zero_unassignedbool, optional If True, fields in the dst for which there was no matching field in the src are filled with the value 0 (zero). This was the behavior of numpy <= 1.13. If False, those fields are not modified.
doc_24667
The name of the class.
doc_24668
Return the xheight as float.
doc_24669
tf.compat.v1.global_variables( scope=None ) Global variables are variables that are shared across machines in a distributed environment. The Variable() constructor or get_variable() automatically adds new variables to the graph collection GraphKeys.GLOBAL_VARIABLES. This convenience function returns the contents of that collection. An alternative to global variables are local variables. See tf.compat.v1.local_variables Args scope (Optional.) A string. If supplied, the resulting list is filtered to include only items whose name attribute matches scope using re.match. Items without a name attribute are never returned if a scope is supplied. The choice of re.match means that a scope without special tokens filters by prefix. Returns A list of Variable objects.
doc_24670
The full name of a template to use. Defaults to registration/password_change_done.html if not supplied.
doc_24671
Reverse the samples in a fragment and returns the modified fragment.
doc_24672
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_24673
tf.initializers.Initializer Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.initializers.Initializer Initializers should implement a __call__ method with the following signature: def __call__(self, shape, dtype=None, **kwargs): # returns a tensor of shape `shape` and dtype `dtype` # containing values drawn from a distribution of your choice. Optionally, you an also implement the method get_config and the class method from_config in order to support serialization -- just like with any Keras object. Here's a simple example: a random normal initializer. import tensorflow as tf class ExampleRandomNormal(tf.keras.initializers.Initializer): def __init__(self, mean, stddev): self.mean = mean self.stddev = stddev def __call__(self, shape, dtype=None, **kwargs): return tf.random.normal( shape, mean=self.mean, stddev=self.stddev, dtype=dtype) def get_config(self): # To support serialization return {"mean": self.mean, "stddev": self.stddev} Note that we don't have to implement from_config in the example above since the constructor arguments of the class the keys in the config returned by get_config are the same. In this case, the default from_config works fine. Methods from_config View source @classmethod from_config( config ) Instantiates an initializer from a configuration dictionary. Example: initializer = RandomUniform(-1, 1) config = initializer.get_config() initializer = RandomUniform.from_config(config) Args config A Python dictionary, the output of get_config. Returns A tf.keras.initializers.Initializer instance. get_config View source get_config() Returns the configuration of the initializer as a JSON-serializable dict. Returns A JSON-serializable Python dict. __call__ View source __call__( shape, dtype=None, **kwargs ) Returns a tensor object initialized as specified by the initializer. Args shape Shape of the tensor. dtype Optional dtype of the tensor. **kwargs Additional keyword arguments.
doc_24674
See Migration guide for more details. tf.compat.v1.raw_ops.UnsortedSegmentMax tf.raw_ops.UnsortedSegmentMax( data, segment_ids, num_segments, name=None ) Read the section on segmentation for an explanation of segments. This operator is similar to the unsorted segment sum operator found (here). Instead of computing the sum over segments, it computes the maximum such that: \(output_i = \max_{j...} data[j...]\) where max is over tuples j... such that segment_ids[j...] == i. If the maximum is empty for a given segment ID i, it outputs the smallest possible value for the specific numeric type, output[i] = numeric_limits<T>::lowest(). If the given segment ID i is negative, then the corresponding value is dropped, and will not be included in the result. For example: c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) tf.unsorted_segment_max(c, tf.constant([0, 1, 0]), num_segments=2) # ==> [[ 4, 3, 3, 4], # [5, 6, 7, 8]] Args data A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. segment_ids A Tensor. Must be one of the following types: int32, int64. A tensor whose shape is a prefix of data.shape. num_segments A Tensor. Must be one of the following types: int32, int64. name A name for the operation (optional). Returns A Tensor. Has the same type as data.
doc_24675
crops a line inside a rectangle clipline(x1, y1, x2, y2) -> ((cx1, cy1), (cx2, cy2)) clipline(x1, y1, x2, y2) -> () clipline((x1, y1), (x2, y2)) -> ((cx1, cy1), (cx2, cy2)) clipline((x1, y1), (x2, y2)) -> () clipline((x1, y1, x2, y2)) -> ((cx1, cy1), (cx2, cy2)) clipline((x1, y1, x2, y2)) -> () clipline(((x1, y1), (x2, y2))) -> ((cx1, cy1), (cx2, cy2)) clipline(((x1, y1), (x2, y2))) -> () Returns the coordinates of a line that is cropped to be completely inside the rectangle. If the line does not overlap the rectangle, then an empty tuple is returned. The line to crop can be any of the following formats (floats can be used in place of ints, but they will be truncated): four ints 2 lists/tuples/Vector2s of 2 ints a list/tuple of four ints a list/tuple of 2 lists/tuples/Vector2s of 2 ints Returns: a tuple with the coordinates of the given line cropped to be completely inside the rectangle is returned, if the given line does not overlap the rectangle, an empty tuple is returned Return type: tuple(tuple(int, int), tuple(int, int)) or () Raises: TypeError -- if the line coordinates are not given as one of the above described line formats Note This method can be used for collision detection between a rect and a line. See example code below. Note The rect.bottom and rect.right attributes of a pygame.Rect always lie one pixel outside of its actual border. # Example using clipline(). clipped_line = rect.clipline(line) if clipped_line: # If clipped_line is not an empty tuple then the line # collides/overlaps with the rect. The returned value contains # the endpoints of the clipped line. start, end = clipped_line x1, y1 = start x2, y2 = end else: print("No clipping. The line is fully outside the rect.") New in pygame 2.0.0.
doc_24676
The dtype of the Interval bounds.
doc_24677
Computes the (weighted) graph of Neighbors for points in X Neighborhoods are restricted the points at a distance lower than radius. Parameters Xarray-like of shape (n_samples, n_features), default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. radiusfloat, default=None Radius of neighborhoods. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. sort_resultsbool, default=False If True, in each row of the result, the non-zero entries will be sorted by increasing distances. If False, the non-zero entries may not be sorted. Only used with mode=’distance’. New in version 0.22. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix if of format CSR. See also kneighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(radius=1.5) >>> neigh.fit(X) NearestNeighbors(radius=1.5) >>> A = neigh.radius_neighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 0.], [1., 0., 1.]])
doc_24678
See Migration guide for more details. tf.compat.v1.raw_ops.RaggedCross tf.raw_ops.RaggedCross( ragged_values, ragged_row_splits, sparse_indices, sparse_values, sparse_shape, dense_inputs, input_order, hashed_output, num_buckets, hash_key, out_values_type, out_row_splits_type, name=None ) RaggedTensor. See tf.ragged.cross for more details. Args: ragged_values: A list of Tensor objects with types from: int64, string. The values tensor for each RaggedTensor input. ragged_row_splits: A list of Tensor objects with types from: int32, int64. The row_splits tensor for each RaggedTensor input. sparse_indices: A list of Tensor objects with type int64. The indices tensor for each SparseTensor input. sparse_values: A list of Tensor objects with types from: int64, string. The values tensor for each SparseTensor input. sparse_shape: A list with the same length as sparse_indices of Tensor objects with type int64. The dense_shape tensor for each SparseTensor input. dense_inputs: A list of Tensor objects with types from: int64, string. The tf.Tensor inputs. input_order: A string. String specifying the tensor type for each input. The ith character in this string specifies the type of the ith input, and is one of: 'R' (ragged), 'D' (dense), or 'S' (sparse). This attr is used to ensure that the crossed values are combined in the order of the inputs from the call to tf.ragged.cross. hashed_output: A bool. num_buckets: An int that is >= 0. hash_key: An int. out_values_type: A tf.DType from: tf.int64, tf.string. out_row_splits_type: A tf.DType from: tf.int32, tf.int64. name: A name for the operation (optional). Returns: A tuple of Tensor objects (output_values, output_row_splits). output_values: A `Tensor` of type `out_values_type`. output_row_splits: A `Tensor` of type `out_row_splits_type`.
doc_24679
Apply function ‘func’ as a reduction across fields of a structured array. This is similar to apply_along_axis, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from numpy.result_type applied to the field’s dtypes. Parameters funcfunction Function to apply on the “field” dimension. This function must support an axis argument, like np.mean, np.sum, etc. arrndarray Structured array for which to apply func. Returns outndarray Result of the recution operation Examples >>> from numpy.lib import recfunctions as rfn >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> rfn.apply_along_fields(np.mean, b) array([ 2.66666667, 5.33333333, 8.66666667, 11. ]) >>> rfn.apply_along_fields(np.mean, b[['x', 'z']]) array([ 3. , 5.5, 9. , 11. ])
doc_24680
Sets the array system to be used for sound arrays use_arraytype (arraytype) -> None DEPRECATED: Uses the requested array type for the module functions. The only supported arraytype is 'numpy'. Other values will raise ValueError.
doc_24681
Compute the anomalies (deviations from the arithmetic mean) along the given axis. Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed along the given axis. Parameters axisint, optional Axis over which the anomalies are taken. The default is to use the mean of the flattened array as reference. dtypedtype, optional Type to use in computing the variance. For arrays of integer type the default is float32; for arrays of float types it is the same as the array type. See also mean Compute the mean of the array. Examples >>> a = np.ma.array([1,2,3]) >>> a.anom() masked_array(data=[-1., 0., 1.], mask=False, fill_value=1e+20)
doc_24682
a place where extensions can store application specific state. For example this is where an extension could store database engines and similar things. The key must match the name of the extension module. For example in case of a “Flask-Foo” extension in flask_foo, the key would be 'foo'. Changelog New in version 0.7.
doc_24683
See Migration guide for more details. tf.compat.v1.AggregationMethod Computing partial derivatives can require aggregating gradient contributions. This class lists the various methods that can be used to combine gradients in the graph. The following aggregation methods are part of the stable API for aggregating gradients: ADD_N: All of the gradient terms are summed as part of one operation using the "AddN" op (see tf.add_n). This method has the property that all gradients must be ready and buffered separately in memory before any aggregation is performed. DEFAULT: The system-chosen default aggregation method. The following aggregation methods are experimental and may not be supported in future releases: EXPERIMENTAL_TREE: Gradient terms are summed in pairs using using the "AddN" op. This method of summing gradients may reduce performance, but it can improve memory utilization because the gradients can be released earlier. Class Variables ADD_N 0 DEFAULT 0 EXPERIMENTAL_ACCUMULATE_N 2 EXPERIMENTAL_TREE 1
doc_24684
tf.nn.all_candidate_sampler Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.all_candidate_sampler, tf.compat.v1.random.all_candidate_sampler tf.random.all_candidate_sampler( true_classes, num_true, num_sampled, unique, seed=None, name=None ) Deterministically generates and returns the set of all possible classes. For testing purposes. There is no need to use this, since you might as well use full softmax or full logistic regression. Args true_classes A Tensor of type int64 and shape [batch_size, num_true]. The target classes. num_true An int. The number of target classes per training example. num_sampled An int. The number of possible classes. unique A bool. Ignored. unique. seed An int. An operation-specific seed. Default is 0. name A name for the operation (optional). Returns sampled_candidates A tensor of type int64 and shape [num_sampled]. This operation deterministically returns the entire range [0, num_sampled]. true_expected_count A tensor of type float. Same shape as true_classes. The expected counts under the sampling distribution of each of true_classes. All returned values are 1.0. sampled_expected_count A tensor of type float. Same shape as sampled_candidates. The expected counts under the sampling distribution of each of sampled_candidates. All returned values are 1.0.
doc_24685
Helper for pickle.
doc_24686
See Migration guide for more details. tf.compat.v1.raw_ops.QuantizedConv2DWithBiasAndRelu tf.raw_ops.QuantizedConv2DWithBiasAndRelu( input, filter, bias, min_input, max_input, min_filter, max_filter, strides, padding, out_type=tf.dtypes.qint32, dilations=[1, 1, 1, 1], padding_list=[], name=None ) Args input A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. filter A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. bias A Tensor of type float32. min_input A Tensor of type float32. max_input A Tensor of type float32. min_filter A Tensor of type float32. max_filter A Tensor of type float32. strides A list of ints. padding A string from: "SAME", "VALID". out_type An optional tf.DType from: tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16. Defaults to tf.qint32. dilations An optional list of ints. Defaults to [1, 1, 1, 1]. padding_list An optional list of ints. Defaults to []. name A name for the operation (optional). Returns A tuple of Tensor objects (output, min_output, max_output). output A Tensor of type out_type. min_output A Tensor of type float32. max_output A Tensor of type float32.
doc_24687
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters t (torch.Tensor) – tensor to prune (of same dimensions as default_mask). importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place. default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns pruned version of tensor t.
doc_24688
Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule. Parameters args (Any) – kwargs (Any) – Return type Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
doc_24689
Draw a filled black rectangle from (x1, y1) to (x2, y2).
doc_24690
Convert arrays to MultiIndex. Parameters arrays:list / sequence of array-likes Each array-like gives one level’s value for each data point. len(arrays) is the number of levels. sortorder:int or None Level of sortedness (must be lexicographically sorted by that level). names:list / sequence of str, optional Names for the levels in the index. Returns MultiIndex See also MultiIndex.from_tuples Convert list of tuples to MultiIndex. MultiIndex.from_product Make a MultiIndex from cartesian product of iterables. MultiIndex.from_frame Make a MultiIndex from a DataFrame. Examples >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) MultiIndex([(1, 'red'), (1, 'blue'), (2, 'red'), (2, 'blue')], names=['number', 'color'])
doc_24691
Start collecting profiling data. Only in cProfile.
doc_24692
True if this transform is separable in the x- and y- dimensions.
doc_24693
Return an array and missing value suitable for factorization. Returns values:ndarray An array suitable for factorization. This should maintain order and be a supported dtype (Float64, Int64, UInt64, String, Object). By default, the extension array is cast to object dtype. na_value:object The value in values to consider missing. This will be treated as NA in the factorization routines, so it will be coded as na_sentinel and not included in uniques. By default, np.nan is used. Notes The values returned by this method are also used in pandas.util.hash_pandas_object().
doc_24694
pause the program for an amount of time wait(milliseconds) -> time Will pause for a given number of milliseconds. This function sleeps the process to share the processor with other programs. A program that waits for even a few milliseconds will consume very little processor time. It is slightly less accurate than the pygame.time.delay() function. This returns the actual number of milliseconds used.
doc_24695
Set the CapStyle for the collection (for all its elements). Parameters csCapStyle or {'butt', 'projecting', 'round'}
doc_24696
Convert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError. >>> fmean([3.5, 4.0, 5.25]) 4.25 New in version 3.8.
doc_24697
Bases: matplotlib.patches.ConnectionStyle._Base Creates a simple quadratic Bezier curve between two points. The curve is created so that the middle control point (C1) is located at the same distance from the start (C0) and end points(C2) and the distance of the C1 to the line connecting C0-C2 is rad times the distance of C0-C2. rad curvature of the curve. connect(posA, posB)[source]
doc_24698
Return the month name of the Timestamp with specified locale. Parameters locale:str, default None (English locale) Locale determining the language in which to return the month name. Returns str Examples >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') >>> ts.month_name() 'March' Analogous for pd.NaT: >>> pd.NaT.month_name() nan
doc_24699
Method called immediately after the test method has been called and the result recorded. This is called before tearDown(). This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception, other than AssertionError or SkipTest, raised by this method will be considered an additional error rather than a test failure (thus increasing the total number of reported errors). This method will only be called if the asyncSetUp() succeeds, regardless of the outcome of the test method. The default implementation does nothing.