_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_28000
enum.IntFlag collection of OP_* constants.
doc_28001
create a new surface that references its parent subsurface(Rect) -> Surface Returns a new Surface that shares its pixels with its new parent. The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other. Surface information like clipping area and color keys are unique to each Surface. The new Surface will inherit the palette, color key, and alpha settings from its parent. It is possible to have any number of subsurfaces and subsubsurfaces on the parent. It is also possible to subsurface the display Surface if the display mode is not hardware accelerated. See get_offset() and get_parent() to learn more about the state of a subsurface. A subsurface will have the same class as the parent surface.
doc_28002
Module: email.mime.application A subclass of MIMENonMultipart, the MIMEApplication class is used to represent MIME message objects of major type application. _data is a string containing the raw byte data. Optional _subtype specifies the MIME subtype and defaults to octet-stream. Optional _encoder is a callable (i.e. function) which will perform the actual encoding of the data for transport. This callable takes one argument, which is the MIMEApplication instance. It should use get_payload() and set_payload() to change the payload to encoded form. It should also add any Content-Transfer-Encoding or other headers to the message object as necessary. The default encoding is base64. See the email.encoders module for a list of the built-in encoders. Optional policy argument defaults to compat32. _params are passed straight through to the base class constructor. Changed in version 3.6: Added policy keyword-only parameter.
doc_28003
Abstract base class for unions in native byte order.
doc_28004
Check for the existence of the compiler executables whose names are listed in cmd_names or all the compiler executables when cmd_names is empty and return the first missing executable or None when none is found missing.
doc_28005
Remove and return oldAttr from the attribute list, if present. If oldAttr is not present, NotFoundErr is raised.
doc_28006
os.MFD_ALLOW_SEALING os.MFD_HUGETLB os.MFD_HUGE_SHIFT os.MFD_HUGE_MASK os.MFD_HUGE_64KB os.MFD_HUGE_512KB os.MFD_HUGE_1MB os.MFD_HUGE_2MB os.MFD_HUGE_8MB os.MFD_HUGE_16MB os.MFD_HUGE_32MB os.MFD_HUGE_256MB os.MFD_HUGE_512MB os.MFD_HUGE_1GB os.MFD_HUGE_2GB os.MFD_HUGE_16GB These flags can be passed to memfd_create(). Availability: Linux 3.17 or newer with glibc 2.27 or newer. The MFD_HUGE* flags are only available since Linux 4.14. New in version 3.8.
doc_28007
Adds a child module to the current module. The module can be accessed as an attribute using the given name. Parameters name (string) – name of the child module. The child module can be accessed from this module using the given name module (Module) – child module to be added to the module.
doc_28008
Parse the headers from a file pointer fp representing a HTTP request/response. The file has to be a BufferedIOBase reader (i.e. not text) and must provide a valid RFC 2822 style header. This function returns an instance of http.client.HTTPMessage that holds the header fields, but no payload (the same as HTTPResponse.msg and http.server.BaseHTTPRequestHandler.headers). After returning, the file pointer fp is ready to read the HTTP body. Note parse_headers() does not parse the start-line of a HTTP message; it only parses the Name: value lines. The file has to be ready to read these field lines, so the first line should already be consumed before calling the function.
doc_28009
The type of objects defined in extension modules with PyGetSetDef, such as FrameType.f_locals or array.array.typecode. This type is used as descriptor for object attributes; it has the same purpose as the property type, but for classes defined in extension modules.
doc_28010
Create a new decompressor object. This object may be used to decompress data incrementally. For one-shot compression, use the decompress() function instead. Note This class does not transparently handle inputs containing multiple compressed streams, unlike decompress() and BZ2File. If you need to decompress a multi-stream input with BZ2Decompressor, you must use a new decompressor for each stream. decompress(data, max_length=-1) Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to decompress(). The returned data should be concatenated with the output of any previous calls to decompress(). If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the needs_input attribute will be set to False. In this case, the next call to decompress() may provide data as b'' to obtain more of the output. If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the needs_input attribute will be set to True. Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the unused_data attribute. Changed in version 3.5: Added the max_length parameter. eof True if the end-of-stream marker has been reached. New in version 3.3. unused_data Data found after the end of the compressed stream. If this attribute is accessed before the end of the stream has been reached, its value will be b''. needs_input False if the decompress() method can provide more decompressed data before requiring new uncompressed input. New in version 3.5.
doc_28011
Fit the gradient boosting model. Parameters Xarray-like of shape (n_samples, n_features) The input samples. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,) default=None Weights of training data. New in version 0.23. Returns selfobject
doc_28012
Return the Attr node for the attribute named by attrname.
doc_28013
See Migration guide for more details. tf.compat.v1.raw_ops.TextLineDataset tf.raw_ops.TextLineDataset( filenames, compression_type, buffer_size, name=None ) Args filenames A Tensor of type string. A scalar or a vector containing the name(s) of the file(s) to be read. compression_type A Tensor of type string. A scalar containing either (i) the empty string (no compression), (ii) "ZLIB", or (iii) "GZIP". buffer_size A Tensor of type int64. A scalar containing the number of bytes to buffer. name A name for the operation (optional). Returns A Tensor of type variant.
doc_28014
Do some necessary and/or useful substitutions for texts to be included in LaTeX documents. This distinguishes text-mode and math-mode by replacing the math separator $ with \(\displaystyle %s\). Escaped math separators (\$) are ignored. The following characters are escaped in text segments: _^$%
doc_28015
Set the delivery date of the message to date, a floating-point number representing seconds since the epoch.
doc_28016
skimage.restoration.ball_kernel(radius, ndim) Create a ball kernel for restoration.rolling_ball. skimage.restoration.calibrate_denoiser(…) Calibrate a denoising function and return optimal J-invariant version. skimage.restoration.cycle_spin(x, func, …) Cycle spinning (repeatedly apply func to shifted versions of x). skimage.restoration.denoise_bilateral(image) Denoise image using bilateral filter. skimage.restoration.denoise_nl_means(image) Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images. skimage.restoration.denoise_tv_bregman(…) Perform total-variation denoising using split-Bregman optimization. skimage.restoration.denoise_tv_chambolle(image) Perform total-variation denoising on n-dimensional images. skimage.restoration.denoise_wavelet(image[, …]) Perform wavelet denoising on an image. skimage.restoration.ellipsoid_kernel(shape, …) Create an ellipoid kernel for restoration.rolling_ball. skimage.restoration.estimate_sigma(image[, …]) Robust wavelet-based estimator of the (Gaussian) noise standard deviation. skimage.restoration.inpaint_biharmonic(…) Inpaint masked points in image with biharmonic equations. skimage.restoration.richardson_lucy(image, psf) Richardson-Lucy deconvolution. skimage.restoration.rolling_ball(image, *[, …]) Estimate background intensity by rolling/translating a kernel. skimage.restoration.unsupervised_wiener(…) Unsupervised Wiener-Hunt deconvolution. skimage.restoration.unwrap_phase(image[, …]) Recover the original from a wrapped phase image. skimage.restoration.wiener(image, psf, balance) Wiener-Hunt deconvolution ball_kernel skimage.restoration.ball_kernel(radius, ndim) [source] Create a ball kernel for restoration.rolling_ball. Parameters radiusint Radius of the ball. ndimint Number of dimensions of the ball. ndim should match the dimensionality of the image the kernel will be applied to. Returns kernelndarray The kernel containing the surface intensity of the top half of the ellipsoid. See also rolling_ball calibrate_denoiser skimage.restoration.calibrate_denoiser(image, denoise_function, denoise_parameters, *, stride=4, approximate_loss=True, extra_output=False) [source] 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) cycle_spin skimage.restoration.cycle_spin(x, func, max_shifts, shift_steps=1, num_workers=None, multichannel=False, func_kw={}) [source] Cycle spinning (repeatedly apply func to shifted versions of x). Parameters xarray-like Data for input to func. funcfunction A function to apply to circularly shifted versions of x. Should take x as its first argument. Any additional arguments can be supplied via func_kw. max_shiftsint or tuple If an integer, shifts in range(0, max_shifts+1) will be used along each axis of x. If a tuple, range(0, max_shifts[i]+1) will be along axis i. shift_stepsint or tuple, optional The step size for the shifts applied along axis, i, are:: range((0, max_shifts[i]+1, shift_steps[i])). If an integer is provided, the same step size is used for all axes. num_workersint or None, optional The number of parallel threads to use during cycle spinning. If set to None, the full set of available cores are used. multichannelbool, optional Whether to treat the final axis as channels (no cycle shifts are performed over the channels axis). func_kwdict, optional Additional keyword arguments to supply to func. Returns avg_ynp.ndarray The output of func(x, **func_kw) averaged over all combinations of the specified axis shifts. Notes Cycle spinning was proposed as a way to approach shift-invariance via performing several circular shifts of a shift-variant transform [1]. For a n-level discrete wavelet transforms, one may wish to perform all shifts up to max_shifts = 2**n - 1. In practice, much of the benefit can often be realized with only a small number of shifts per axis. For transforms such as the blockwise discrete cosine transform, one may wish to evaluate shifts up to the block size used by the transform. References 1 R.R. Coifman and D.L. Donoho. “Translation-Invariant De-Noising”. Wavelets and Statistics, Lecture Notes in Statistics, vol.103. Springer, New York, 1995, pp.125-150. DOI:10.1007/978-1-4612-2544-7_9 Examples >>> import skimage.data >>> from skimage import img_as_float >>> from skimage.restoration import denoise_wavelet, cycle_spin >>> img = img_as_float(skimage.data.camera()) >>> sigma = 0.1 >>> img = img + sigma * np.random.standard_normal(img.shape) >>> denoised = cycle_spin(img, func=denoise_wavelet, ... max_shifts=3) denoise_bilateral skimage.restoration.denoise_bilateral(image, win_size=None, sigma_color=None, sigma_spatial=1, bins=10000, mode='constant', cval=0, multichannel=False) [source] Denoise image using bilateral filter. Parameters imagendarray, shape (M, N[, 3]) Input image, 2D grayscale or RGB. win_sizeint Window size for filtering. If win_size is not specified, it is calculated as max(5, 2 * ceil(3 * sigma_spatial) + 1). sigma_colorfloat Standard deviation for grayvalue/color distance (radiometric similarity). A larger value results in averaging of pixels with larger radiometric differences. Note, that the image will be converted using the img_as_float function and thus the standard deviation is in respect to the range [0, 1]. If the value is None the standard deviation of the image will be used. sigma_spatialfloat Standard deviation for range distance. A larger value results in averaging of pixels with larger spatial differences. binsint Number of discrete values for Gaussian weights of color filtering. A larger value results in improved accuracy. mode{‘constant’, ‘edge’, ‘symmetric’, ‘reflect’, ‘wrap’} How to handle values outside the image borders. See numpy.pad for detail. cvalstring Used in conjunction with mode ‘constant’, the value outside the image boundaries. multichannelbool Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. Returns denoisedndarray Denoised image. Notes This is an edge-preserving, denoising filter. It averages pixels based on their spatial closeness and radiometric similarity [1]. Spatial closeness is measured by the Gaussian function of the Euclidean distance between two pixels and a certain standard deviation (sigma_spatial). Radiometric similarity is measured by the Gaussian function of the Euclidean distance between two color values and a certain standard deviation (sigma_color). References 1 C. Tomasi and R. Manduchi. “Bilateral Filtering for Gray and Color Images.” IEEE International Conference on Computer Vision (1998) 839-846. DOI:10.1109/ICCV.1998.710815 Examples >>> from skimage import data, img_as_float >>> astro = img_as_float(data.astronaut()) >>> astro = astro[220:300, 220:320] >>> noisy = astro + 0.6 * astro.std() * np.random.random(astro.shape) >>> noisy = np.clip(noisy, 0, 1) >>> denoised = denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15, ... multichannel=True) Examples using skimage.restoration.denoise_bilateral Rank filters denoise_nl_means skimage.restoration.denoise_nl_means(image, patch_size=7, patch_distance=11, h=0.1, multichannel=False, fast_mode=True, sigma=0.0, *, preserve_range=None) [source] Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images. Parameters image2D or 3D ndarray Input image to be denoised, which can be 2D or 3D, and grayscale or RGB (for 2D images only, see multichannel parameter). patch_sizeint, optional Size of patches used for denoising. patch_distanceint, optional Maximal distance in pixels where to search patches used for denoising. hfloat, optional Cut-off distance (in gray levels). The higher h, the more permissive one is in accepting patches. A higher h results in a smoother image, at the expense of blurring features. For a Gaussian noise of standard deviation sigma, a rule of thumb is to choose the value of h to be sigma of slightly less. multichannelbool, optional Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. fast_modebool, optional If True (default value), a fast version of the non-local means algorithm is used. If False, the original version of non-local means is used. See the Notes section for more details about the algorithms. sigmafloat, optional The standard deviation of the (Gaussian) noise. If provided, a more robust computation of patch weights is computed that takes the expected noise variance into account (see Notes below). preserve_rangebool, optional Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html Returns resultndarray Denoised image, of same shape as image. Notes The non-local means algorithm is well suited for denoising images with specific textures. The principle of the algorithm is to average the value of a given pixel with values of other pixels in a limited neighbourhood, provided that the patches centered on the other pixels are similar enough to the patch centered on the pixel of interest. In the original version of the algorithm [1], corresponding to fast=False, the computational complexity is: image.size * patch_size ** image.ndim * patch_distance ** image.ndim Hence, changing the size of patches or their maximal distance has a strong effect on computing times, especially for 3-D images. However, the default behavior corresponds to fast_mode=True, for which another version of non-local means [2] is used, corresponding to a complexity of: image.size * patch_distance ** image.ndim The computing time depends only weakly on the patch size, thanks to the computation of the integral of patches distances for a given shift, that reduces the number of operations [1]. Therefore, this algorithm executes faster than the classic algorithm (fast_mode=False), at the expense of using twice as much memory. This implementation has been proven to be more efficient compared to other alternatives, see e.g. [3]. Compared to the classic algorithm, all pixels of a patch contribute to the distance to another patch with the same weight, no matter their distance to the center of the patch. This coarser computation of the distance can result in a slightly poorer denoising performance. Moreover, for small images (images with a linear size that is only a few times the patch size), the classic algorithm can be faster due to boundary effects. The image is padded using the reflect mode of skimage.util.pad before denoising. If the noise standard deviation, sigma, is provided a more robust computation of patch weights is used. Subtracting the known noise variance from the computed patch distances improves the estimates of patch similarity, giving a moderate improvement to denoising performance [4]. It was also mentioned as an option for the fast variant of the algorithm in [3]. When sigma is provided, a smaller h should typically be used to avoid oversmoothing. The optimal value for h depends on the image content and noise level, but a reasonable starting point is h = 0.8 * sigma when fast_mode is True, or h = 0.6 * sigma when fast_mode is False. References 1(1,2) A. Buades, B. Coll, & J-M. Morel. A non-local algorithm for image denoising. In CVPR 2005, Vol. 2, pp. 60-65, IEEE. DOI:10.1109/CVPR.2005.38 2 J. Darbon, A. Cunha, T.F. Chan, S. Osher, and G.J. Jensen, Fast nonlocal filtering applied to electron cryomicroscopy, in 5th IEEE International Symposium on Biomedical Imaging: From Nano to Macro, 2008, pp. 1331-1334. DOI:10.1109/ISBI.2008.4541250 3(1,2) Jacques Froment. Parameter-Free Fast Pixelwise Non-Local Means Denoising. Image Processing On Line, 2014, vol. 4, pp. 300-326. DOI:10.5201/ipol.2014.120 4 A. Buades, B. Coll, & J-M. Morel. Non-Local Means Denoising. Image Processing On Line, 2011, vol. 1, pp. 208-212. DOI:10.5201/ipol.2011.bcm_nlm Examples >>> a = np.zeros((40, 40)) >>> a[10:-10, 10:-10] = 1. >>> a += 0.3 * np.random.randn(*a.shape) >>> denoised_a = denoise_nl_means(a, 7, 5, 0.1) denoise_tv_bregman skimage.restoration.denoise_tv_bregman(image, weight, max_iter=100, eps=0.001, isotropic=True, *, multichannel=False) [source] Perform total-variation denoising using split-Bregman optimization. Total-variation denoising (also know as total-variation regularization) tries to find an image with less total-variation under the constraint of being similar to the input image, which is controlled by the regularization parameter ([1], [2], [3], [4]). Parameters imagendarray Input data to be denoised (converted using img_as_float`). weightfloat Denoising weight. The smaller the weight, the more denoising (at the expense of less similarity to the input). The regularization parameter lambda is chosen as 2 * weight. epsfloat, optional Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when: SUM((u(n) - u(n-1))**2) < eps max_iterint, optional Maximal number of iterations used for the optimization. isotropicboolean, optional Switch between isotropic and anisotropic TV denoising. multichannelbool, optional Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension. Returns undarray Denoised image. References 1 https://en.wikipedia.org/wiki/Total_variation_denoising 2 Tom Goldstein and Stanley Osher, “The Split Bregman Method For L1 Regularized Problems”, ftp://ftp.math.ucla.edu/pub/camreport/cam08-29.pdf 3 Pascal Getreuer, “Rudin–Osher–Fatemi Total Variation Denoising using Split Bregman” in Image Processing On Line on 2012–05–19, https://www.ipol.im/pub/art/2012/g-tvd/article_lr.pdf 4 https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf denoise_tv_chambolle skimage.restoration.denoise_tv_chambolle(image, weight=0.1, eps=0.0002, n_iter_max=200, multichannel=False) [source] Perform total-variation denoising on n-dimensional images. Parameters imagendarray of ints, uints or floats Input data to be denoised. image can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image. weightfloat, optional Denoising weight. The greater weight, the more denoising (at the expense of fidelity to input). epsfloat, optional Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when: (E_(n-1) - E_n) < eps * E_0 n_iter_maxint, optional Maximal number of iterations used for the optimization. multichannelbool, optional Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension. Returns outndarray Denoised image. Notes Make sure to set the multichannel parameter appropriately for color images. The principle of total variation denoising is explained in https://en.wikipedia.org/wiki/Total_variation_denoising The principle of total variation denoising is to minimize the total variation of the image, which can be roughly described as the integral of the norm of the image gradient. Total variation denoising tends to produce “cartoon-like” images, that is, piecewise-constant images. This code is an implementation of the algorithm of Rudin, Fatemi and Osher that was proposed by Chambolle in [1]. References 1 A. Chambolle, An algorithm for total variation minimization and applications, Journal of Mathematical Imaging and Vision, Springer, 2004, 20, 89-97. Examples 2D example on astronaut image: >>> from skimage import color, data >>> img = color.rgb2gray(data.astronaut())[:50, :50] >>> img += 0.5 * img.std() * np.random.randn(*img.shape) >>> denoised_img = denoise_tv_chambolle(img, weight=60) 3D example on synthetic data: >>> x, y, z = np.ogrid[0:20, 0:20, 0:20] >>> mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2 >>> mask = mask.astype(float) >>> mask += 0.2*np.random.randn(*mask.shape) >>> res = denoise_tv_chambolle(mask, weight=100) denoise_wavelet skimage.restoration.denoise_wavelet(image, sigma=None, wavelet='db1', mode='soft', wavelet_levels=None, multichannel=False, convert2ycbcr=False, method='BayesShrink', rescale_sigma=True) [source] Perform wavelet denoising on an image. Parameters imagendarray ([M[, N[, …P]][, C]) of ints, uints or floats Input data to be denoised. image can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image. sigmafloat or list, optional The noise standard deviation used when computing the wavelet detail coefficient threshold(s). When None (default), the noise standard deviation is estimated via the method in [2]. waveletstring, optional The type of wavelet to perform and can be any of the options pywt.wavelist outputs. The default is ‘db1’. For example, wavelet can be any of {'db2', 'haar', 'sym9'} and many more. mode{‘soft’, ‘hard’}, optional An optional argument to choose the type of denoising performed. It noted that choosing soft thresholding given additive noise finds the best approximation of the original image. wavelet_levelsint or None, optional The number of wavelet decomposition levels to use. The default is three less than the maximum number of possible decomposition levels. multichannelbool, optional Apply wavelet denoising separately for each channel (where channels correspond to the final axis of the array). convert2ycbcrbool, optional If True and multichannel True, do the wavelet denoising in the YCbCr colorspace instead of the RGB color space. This typically results in better performance for RGB images. method{‘BayesShrink’, ‘VisuShrink’}, optional Thresholding method to be used. The currently supported methods are “BayesShrink” [1] and “VisuShrink” [2]. Defaults to “BayesShrink”. rescale_sigmabool, optional If False, no rescaling of the user-provided sigma will be performed. The default of True rescales sigma appropriately if the image is rescaled internally. New in version 0.16: rescale_sigma was introduced in 0.16 Returns outndarray Denoised image. Notes The wavelet domain is a sparse representation of the image, and can be thought of similarly to the frequency domain of the Fourier transform. Sparse representations have most values zero or near-zero and truly random noise is (usually) represented by many small values in the wavelet domain. Setting all values below some threshold to 0 reduces the noise in the image, but larger thresholds also decrease the detail present in the image. If the input is 3D, this function performs wavelet denoising on each color plane separately. Changed in version 0.16: For floating point inputs, the original input range is maintained and there is no clipping applied to the output. Other input types will be converted to a floating point value in the range [-1, 1] or [0, 1] depending on the input image range. Unless rescale_sigma = False, any internal rescaling applied to the image will also be applied to sigma to maintain the same relative amplitude. Many wavelet coefficient thresholding approaches have been proposed. By default, denoise_wavelet applies BayesShrink, which is an adaptive thresholding method that computes separate thresholds for each wavelet sub-band as described in [1]. If method == "VisuShrink", a single “universal threshold” is applied to all wavelet detail coefficients as described in [2]. This threshold is designed to remove all Gaussian noise at a given sigma with high probability, but tends to produce images that appear overly smooth. Although any of the wavelets from PyWavelets can be selected, the thresholding methods assume an orthogonal wavelet transform and may not choose the threshold appropriately for biorthogonal wavelets. Orthogonal wavelets are desirable because white noise in the input remains white noise in the subbands. Biorthogonal wavelets lead to colored noise in the subbands. Additionally, the orthogonal wavelets in PyWavelets are orthonormal so that noise variance in the subbands remains identical to the noise variance of the input. Example orthogonal wavelets are the Daubechies (e.g. ‘db2’) or symmlet (e.g. ‘sym2’) families. References 1(1,2) Chang, S. Grace, Bin Yu, and Martin Vetterli. “Adaptive wavelet thresholding for image denoising and compression.” Image Processing, IEEE Transactions on 9.9 (2000): 1532-1546. DOI:10.1109/83.862633 2(1,2,3) D. L. Donoho and I. M. Johnstone. “Ideal spatial adaptation by wavelet shrinkage.” Biometrika 81.3 (1994): 425-455. DOI:10.1093/biomet/81.3.425 Examples >>> from skimage import color, data >>> img = img_as_float(data.astronaut()) >>> img = color.rgb2gray(img) >>> img += 0.1 * np.random.randn(*img.shape) >>> img = np.clip(img, 0, 1) >>> denoised_img = denoise_wavelet(img, sigma=0.1, rescale_sigma=True) ellipsoid_kernel skimage.restoration.ellipsoid_kernel(shape, intensity) [source] Create an ellipoid kernel for restoration.rolling_ball. Parameters shapearraylike Length of the principal axis of the ellipsoid (excluding the intensity axis). The kernel needs to have the same dimensionality as the image it will be applied to. intensityint Length of the intensity axis of the ellipsoid. Returns kernelndarray The kernel containing the surface intensity of the top half of the ellipsoid. See also rolling_ball Examples using skimage.restoration.ellipsoid_kernel Use rolling-ball algorithm for estimating background intensity estimate_sigma skimage.restoration.estimate_sigma(image, average_sigmas=False, multichannel=False) [source] Robust wavelet-based estimator of the (Gaussian) noise standard deviation. Parameters imagendarray Image for which to estimate the noise standard deviation. average_sigmasbool, optional If true, average the channel estimates of sigma. Otherwise return a list of sigmas corresponding to each channel. multichannelbool Estimate sigma separately for each channel. Returns sigmafloat or list Estimated noise standard deviation(s). If multichannel is True and average_sigmas is False, a separate noise estimate for each channel is returned. Otherwise, the average of the individual channel estimates is returned. Notes This function assumes the noise follows a Gaussian distribution. The estimation algorithm is based on the median absolute deviation of the wavelet detail coefficients as described in section 4.2 of [1]. References 1 D. L. Donoho and I. M. Johnstone. “Ideal spatial adaptation by wavelet shrinkage.” Biometrika 81.3 (1994): 425-455. DOI:10.1093/biomet/81.3.425 Examples >>> import skimage.data >>> from skimage import img_as_float >>> img = img_as_float(skimage.data.camera()) >>> sigma = 0.1 >>> img = img + sigma * np.random.standard_normal(img.shape) >>> sigma_hat = estimate_sigma(img, multichannel=False) inpaint_biharmonic skimage.restoration.inpaint_biharmonic(image, mask, multichannel=False) [source] Inpaint masked points in image with biharmonic equations. Parameters image(M[, N[, …, P]][, C]) ndarray Input image. mask(M[, N[, …, P]]) ndarray Array of pixels to be inpainted. Have to be the same shape as one of the ‘image’ channels. Unknown pixels have to be represented with 1, known pixels - with 0. multichannelboolean, optional If True, the last image dimension is considered as a color channel, otherwise as spatial. Returns out(M[, N[, …, P]][, C]) ndarray Input image with masked pixels inpainted. References 1 N.S.Hoang, S.B.Damelin, “On surface completion and image inpainting by biharmonic functions: numerical aspects”, arXiv:1707.06567 2 C. K. Chui and H. N. Mhaskar, MRA Contextual-Recovery Extension of Smooth Functions on Manifolds, Appl. and Comp. Harmonic Anal., 28 (2010), 104-113, DOI:10.1016/j.acha.2009.04.004 Examples >>> img = np.tile(np.square(np.linspace(0, 1, 5)), (5, 1)) >>> mask = np.zeros_like(img) >>> mask[2, 2:] = 1 >>> mask[1, 3:] = 1 >>> mask[0, 4:] = 1 >>> out = inpaint_biharmonic(img, mask) richardson_lucy skimage.restoration.richardson_lucy(image, psf, iterations=50, clip=True, filter_epsilon=None) [source] Richardson-Lucy deconvolution. Parameters imagendarray Input degraded image (can be N dimensional). psfndarray The point spread function. iterationsint, optional Number of iterations. This parameter plays the role of regularisation. clipboolean, optional True by default. If true, pixel value of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. filter_epsilon: float, optional Value below which intermediate results become 0 to avoid division by small numbers. Returns im_deconvndarray The deconvolved image. References 1 https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution Examples >>> from skimage import img_as_float, data, restoration >>> camera = img_as_float(data.camera()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> camera = convolve2d(camera, psf, 'same') >>> camera += 0.1 * camera.std() * np.random.standard_normal(camera.shape) >>> deconvolved = restoration.richardson_lucy(camera, psf, 5) rolling_ball skimage.restoration.rolling_ball(image, *, radius=100, kernel=None, nansafe=False, num_threads=None) [source] Estimate background intensity by rolling/translating a kernel. This rolling ball algorithm estimates background intensity for a ndimage in case of uneven exposure. It is a generalization of the frequently used rolling ball algorithm [1]. Parameters imagendarray The image to be filtered. radiusint, optional Radius of a ball shaped kernel to be rolled/translated in the image. Used if kernel = None. kernelndarray, optional The kernel to be rolled/translated in the image. It must have the same number of dimensions as image. Kernel is filled with the intensity of the kernel at that position. nansafe: bool, optional If False (default) assumes that none of the values in image are np.nan, and uses a faster implementation. num_threads: int, optional The maximum number of threads to use. If None use the OpenMP default value; typically equal to the maximum number of virtual cores. Note: This is an upper limit to the number of threads. The exact number is determined by the system’s OpenMP library. Returns backgroundndarray The estimated background of the image. Notes For the pixel that has its background intensity estimated (without loss of generality at center) the rolling ball method centers kernel under it and raises the kernel until the surface touches the image umbra at some pos=(y,x). The background intensity is then estimated using the image intensity at that position (image[pos]) plus the difference of kernel[center] - kernel[pos]. This algorithm assumes that dark pixels correspond to the background. If you have a bright background, invert the image before passing it to the function, e.g., using utils.invert. See the gallery example for details. This algorithm is sensitive to noise (in particular salt-and-pepper noise). If this is a problem in your image, you can apply mild gaussian smoothing before passing the image to this function. References 1 Sternberg, Stanley R. “Biomedical image processing.” Computer 1 (1983): 22-34. DOI:10.1109/MC.1983.1654163 Examples >>> import numpy as np >>> from skimage import data >>> from skimage.restoration import rolling_ball >>> image = data.coins() >>> background = rolling_ball(data.coins()) >>> filtered_image = image - background >>> import numpy as np >>> from skimage import data >>> from skimage.restoration import rolling_ball, ellipsoid_kernel >>> image = data.coins() >>> kernel = ellipsoid_kernel((101, 101), 75) >>> background = rolling_ball(data.coins(), kernel=kernel) >>> filtered_image = image - background Examples using skimage.restoration.rolling_ball Use rolling-ball algorithm for estimating background intensity unsupervised_wiener skimage.restoration.unsupervised_wiener(image, psf, reg=None, user_params=None, is_real=True, clip=True) [source] Unsupervised Wiener-Hunt deconvolution. Return the deconvolution with a Wiener-Hunt approach, where the hyperparameters are automatically estimated. The algorithm is a stochastic iterative process (Gibbs sampler) described in the reference below. See also wiener function. Parameters image(M, N) ndarray The input degraded image. psfndarray The impulse response (input image’s space) or the transfer function (Fourier space). Both are accepted. The transfer function is automatically recognized as being complex (np.iscomplexobj(psf)). regndarray, optional The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf. user_paramsdict, optional Dictionary of parameters for the Gibbs sampler. See below. clipboolean, optional True by default. If true, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns x_postmean(M, N) ndarray The deconvolved image (the posterior mean). chainsdict The keys noise and prior contain the chain list of noise and prior precision respectively. Other Parameters The keys of ``user_params`` are: thresholdfloat The stopping criterion: the norm of the difference between to successive approximated solution (empirical mean of object samples, see Notes section). 1e-4 by default. burninint The number of sample to ignore to start computation of the mean. 15 by default. min_iterint The minimum number of iterations. 30 by default. max_iterint The maximum number of iterations if threshold is not satisfied. 200 by default. callbackcallable (None by default) A user provided callable to which is passed, if the function exists, the current image sample for whatever purpose. The user can store the sample, or compute other moments than the mean. It has no influence on the algorithm execution and is only for inspection. Notes The estimated image is design as the posterior mean of a probability law (from a Bayesian analysis). The mean is defined as a sum over all the possible images weighted by their respective probability. Given the size of the problem, the exact sum is not tractable. This algorithm use of MCMC to draw image under the posterior law. The practical idea is to only draw highly probable images since they have the biggest contribution to the mean. At the opposite, the less probable images are drawn less often since their contribution is low. Finally the empirical mean of these samples give us an estimation of the mean, and an exact computation with an infinite sample set. References 1 François Orieux, Jean-François Giovannelli, and Thomas Rodet, “Bayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution”, J. Opt. Soc. Am. A 27, 1593-1607 (2010) https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593 http://research.orieux.fr/files/papers/OGR-JOSA10.pdf Examples >>> from skimage import color, data, restoration >>> img = color.rgb2gray(data.astronaut()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> img = convolve2d(img, psf, 'same') >>> img += 0.1 * img.std() * np.random.standard_normal(img.shape) >>> deconvolved_img = restoration.unsupervised_wiener(img, psf) unwrap_phase skimage.restoration.unwrap_phase(image, wrap_around=False, seed=None) [source] Recover the original from a wrapped phase image. From an image wrapped to lie in the interval [-pi, pi), recover the original, unwrapped image. Parameters image1D, 2D or 3D ndarray of floats, optionally a masked array The values should be in the range [-pi, pi). If a masked array is provided, the masked entries will not be changed, and their values will not be used to guide the unwrapping of neighboring, unmasked values. Masked 1D arrays are not allowed, and will raise a ValueError. wrap_aroundbool or sequence of bool, optional When an element of the sequence is True, the unwrapping process will regard the edges along the corresponding axis of the image to be connected and use this connectivity to guide the phase unwrapping process. If only a single boolean is given, it will apply to all axes. Wrap around is not supported for 1D arrays. seedint, optional Unwrapping 2D or 3D images uses random initialization. This sets the seed of the PRNG to achieve deterministic behavior. Returns image_unwrappedarray_like, double Unwrapped image of the same shape as the input. If the input image was a masked array, the mask will be preserved. Raises ValueError If called with a masked 1D array or called with a 1D array and wrap_around=True. References 1 Miguel Arevallilo Herraez, David R. Burton, Michael J. Lalor, and Munther A. Gdeisat, “Fast two-dimensional phase-unwrapping algorithm based on sorting by reliability following a noncontinuous path”, Journal Applied Optics, Vol. 41, No. 35 (2002) 7437, 2 Abdul-Rahman, H., Gdeisat, M., Burton, D., & Lalor, M., “Fast three-dimensional phase-unwrapping algorithm based on sorting by reliability following a non-continuous path. In W. Osten, C. Gorecki, & E. L. Novak (Eds.), Optical Metrology (2005) 32–40, International Society for Optics and Photonics. Examples >>> c0, c1 = np.ogrid[-1:1:128j, -1:1:128j] >>> image = 12 * np.pi * np.exp(-(c0**2 + c1**2)) >>> image_wrapped = np.angle(np.exp(1j * image)) >>> image_unwrapped = unwrap_phase(image_wrapped) >>> np.std(image_unwrapped - image) < 1e-6 # A constant offset is normal True Examples using skimage.restoration.unwrap_phase Phase Unwrapping wiener skimage.restoration.wiener(image, psf, balance, reg=None, is_real=True, clip=True) [source] Wiener-Hunt deconvolution Return the deconvolution with a Wiener-Hunt approach (i.e. with Fourier diagonalisation). Parameters image(M, N) ndarray Input degraded image psfndarray Point Spread Function. This is assumed to be the impulse response (input image space) if the data-type is real, or the transfer function (Fourier space) if the data-type is complex. There is no constraints on the shape of the impulse response. The transfer function must be of shape (M, N) if is_real is True, (M, N // 2 + 1) otherwise (see np.fft.rfftn). balancefloat The regularisation parameter value that tunes the balance between the data adequacy that improve frequency restoration and the prior adequacy that reduce frequency restoration (to avoid noise artifacts). regndarray, optional The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf. Shape constraint is the same as for the psf parameter. is_realboolean, optional True by default. Specify if psf and reg are provided with hermitian hypothesis, that is only half of the frequency plane is provided (due to the redundancy of Fourier transform of real signal). It’s apply only if psf and/or reg are provided as transfer function. For the hermitian property see uft module or np.fft.rfftn. clipboolean, optional True by default. If True, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns im_deconv(M, N) ndarray The deconvolved image. Notes This function applies the Wiener filter to a noisy and degraded image by an impulse response (or PSF). If the data model is \[y = Hx + n\] where \(n\) is noise, \(H\) the PSF and \(x\) the unknown original image, the Wiener filter is \[\hat x = F^\dagger (|\Lambda_H|^2 + \lambda |\Lambda_D|^2) \Lambda_H^\dagger F y\] where \(F\) and \(F^\dagger\) are the Fourier and inverse Fourier transforms respectively, \(\Lambda_H\) the transfer function (or the Fourier transform of the PSF, see [Hunt] below) and \(\Lambda_D\) the filter to penalize the restored image frequencies (Laplacian by default, that is penalization of high frequency). The parameter \(\lambda\) tunes the balance between the data (that tends to increase high frequency, even those coming from noise), and the regularization. These methods are then specific to a prior model. Consequently, the application or the true image nature must corresponds to the prior model. By default, the prior model (Laplacian) introduce image smoothness or pixel correlation. It can also be interpreted as high-frequency penalization to compensate the instability of the solution with respect to the data (sometimes called noise amplification or “explosive” solution). Finally, the use of Fourier space implies a circulant property of \(H\), see [Hunt]. References 1 François Orieux, Jean-François Giovannelli, and Thomas Rodet, “Bayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution”, J. Opt. Soc. Am. A 27, 1593-1607 (2010) https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593 http://research.orieux.fr/files/papers/OGR-JOSA10.pdf 2 B. R. Hunt “A matrix theory proof of the discrete convolution theorem”, IEEE Trans. on Audio and Electroacoustics, vol. au-19, no. 4, pp. 285-288, dec. 1971 Examples >>> from skimage import color, data, restoration >>> img = color.rgb2gray(data.astronaut()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> img = convolve2d(img, psf, 'same') >>> img += 0.1 * img.std() * np.random.standard_normal(img.shape) >>> deconvolved_img = restoration.wiener(img, psf, 1100)
doc_28017
Reserve an ID for an indirect object. The name is used for debugging in case we forget to print out the object with writeObject.
doc_28018
Adds object to the context.
doc_28019
Create a cell and add it to the table. Parameters rowint Row index. colint Column index. *args, **kwargs All other parameters are passed on to Cell. Returns Cell The created cell.
doc_28020
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as number. For a general Python object number, round delegates to number.__round__. Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
doc_28021
class ast.NotEq class ast.Lt class ast.LtE class ast.Gt class ast.GtE class ast.Is class ast.IsNot class ast.In class ast.NotIn Comparison operator tokens.
doc_28022
Return the integer index (from the Unicode table) of symbol. Parameters symbolstr A single unicode character, a TeX command (e.g. r'pi') or a Type1 symbol name (e.g. 'phi'). mathbool, default: True If False, always treat as a single unicode character.
doc_28023
See Migration guide for more details. tf.compat.v1.raw_ops.UnsortedSegmentJoin tf.raw_ops.UnsortedSegmentJoin( inputs, segment_ids, num_segments, separator='', name=None ) Computes the string join along segments of a tensor. Given segment_ids with rank N and data with rank N+M: `output[i, k1...kM] = strings.join([data[j1...jN, k1...kM])` where the join is over all [j1...jN] such that segment_ids[j1...jN] = i. Strings are joined in row-major order. For example: inputs = [['Y', 'q', 'c'], ['Y', '6', '6'], ['p', 'G', 'a']] output_array = string_ops.unsorted_segment_join(inputs=inputs, segment_ids=[1, 0, 1], num_segments=2, separator=':')) # output_array ==> [['Y', '6', '6'], ['Y:p', 'q:G', 'c:a']] inputs = ['this', 'is', 'a', 'test'] output_array = string_ops.unsorted_segment_join(inputs=inputs, segment_ids=[0, 0, 0, 0], num_segments=1, separator=':')) # output_array ==> ['this:is:a:test'] Args inputs A Tensor of type string. The input to be joined. segment_ids A Tensor. Must be one of the following types: int32, int64. A tensor whose shape is a prefix of data.shape. Negative segment ids are not supported. num_segments A Tensor. Must be one of the following types: int32, int64. A scalar. separator An optional string. Defaults to "". The separator to use when joining. name A name for the operation (optional). Returns A Tensor of type string.
doc_28024
Font render to text origin mode origin -> bool If set True, render_to() and render_raw_to() will take the dest position to be that of the text origin, as opposed to the top-left corner of the bounding box. See get_rect() for details.
doc_28025
The day of the week with Monday=0, Sunday=6. Return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6. This method is available on both Series with datetime values (using the dt accessor) or DatetimeIndex. Returns Series or Index Containing integers indicating the day number. See also Series.dt.dayofweek Alias. Series.dt.weekday Alias. Series.dt.day_name Returns the name of the day of the week. Examples >>> s = pd.date_range('2016-12-31', '2017-01-08', freq='D').to_series() >>> s.dt.dayofweek 2016-12-31 5 2017-01-01 6 2017-01-02 0 2017-01-03 1 2017-01-04 2 2017-01-05 3 2017-01-06 4 2017-01-07 5 2017-01-08 6 Freq: D, dtype: int64
doc_28026
Default widget: NumberInput when Field.localize is False, else TextInput. Empty value: None Normalizes to: A Python integer. Validates that the given value is an integer. Uses MaxValueValidator and MinValueValidator if max_value and min_value are provided. Leading and trailing whitespace is allowed, as in Python’s int() function. Error message keys: required, invalid, max_value, min_value The max_value and min_value error messages may contain %(limit_value)s, which will be substituted by the appropriate limit. Takes two optional arguments for validation: max_value min_value These control the range of values permitted in the field.
doc_28027
Create a pseudocolor plot with a non-regular rectangular grid. Call signature: pcolor([X, Y,] C, **kwargs) X and Y can be used to specify the corners of the quadrilaterals. Hint pcolor() can be very slow for large arrays. In most cases you should use the similar but much faster pcolormesh instead. See Differences between pcolor() and pcolormesh() for a discussion of the differences. Parameters C2D array-like The color-mapped values. X, Yarray-like, optional The coordinates of the corners of quadrilaterals of a pcolormesh: (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) +-----+ | | +-----+ (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1]) Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below. If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored. If shading='nearest', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). The color C[i, j] will be centered on (X[i, j], Y[i, j]). If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid. shading{'flat', 'nearest', 'auto'}, default: rcParams["pcolor.shading"] (default: 'auto') The fill style for the quadrilateral. Possible values: 'flat': A solid color is used for each quad. The color of the quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by C[i, j]. The dimensions of X and Y should be one greater than those of C; if they are the same as C, then a deprecation warning is raised, and the last row and column of C are dropped. 'nearest': Each grid point will have a color centered on it, extending halfway between the adjacent grid centers. The dimensions of X and Y must be the same as C. 'auto': Choose 'flat' if dimensions of X and Y are one larger than C. Choose 'nearest' if dimensions are the same. See pcolormesh grids and shading for more description. cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis') A Colormap instance or registered colormap name. The colormap maps the C values to colors. normNormalize, optional The Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors. By default, the data range is mapped to the colorbar range using linear scaling. vmin, vmaxfloat, default: None The colorbar range. If None, suitable min/max values are automatically chosen by the Normalize instance (defaults to the respective min/max values of C in case of the default linear scaling). It is an error to use vmin/vmax when norm is given. edgecolors{'none', None, 'face', color, color sequence}, optional The color of the edges. Defaults to 'none'. Possible values: 'none' or '': No edge. None: rcParams["patch.edgecolor"] (default: 'black') will be used. Note that currently rcParams["patch.force_edgecolor"] (default: False) has to be True for this to work. 'face': Use the adjacent face color. A color or sequence of colors will set the edge color. The singular form edgecolor works as an alias. alphafloat, default: None The alpha blending value of the face color, between 0 (transparent) and 1 (opaque). Note: The edgecolor is currently not affected by this. snapbool, default: False Whether to snap the mesh to pixel boundaries. Returns matplotlib.collections.Collection Other Parameters antialiasedsbool, default: False The default antialiaseds is False if the default edgecolors="none" is used. This eliminates artificial lines at patch boundaries, and works regardless of the value of alpha. If edgecolors is not "none", then the default antialiaseds is taken from rcParams["patch.antialiased"] (default: True). Stroking the edges may be preferred if alpha is 1, but will cause artifacts otherwise. dataindexable object, optional If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). **kwargs Additionally, the following arguments are allowed. They are passed along to the PolyCollection constructor: Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha array-like or scalar or None animated bool antialiased or aa or antialiaseds bool or list of bools array array-like or None capstyle CapStyle or {'butt', 'projecting', 'round'} clim (vmin: float, vmax: float) clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None cmap Colormap or str or None color color or list of rgba tuples edgecolor or ec or edgecolors color or list of colors or 'face' facecolor or facecolors or fc color or list of colors figure Figure gid str hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} in_layout bool joinstyle JoinStyle or {'miter', 'round', 'bevel'} label object linestyle or dashes or linestyles or ls str or tuple or list thereof linewidth or linewidths or lw float or list of floats norm Normalize or None offset_transform Transform offsets (N, 2) or (2,) array-like path_effects AbstractPathEffect paths list of array-like picker None or bool or float or callable pickradius float rasterized bool sizes ndarray or None sketch_params (scale: float, length: float, randomness: float) snap bool or None transform Transform url str urls list of str or None verts list of array-like verts_and_codes unknown visible bool zorder float See also pcolormesh for an explanation of the differences between pcolor and pcolormesh. imshow If X and Y are each equidistant, imshow can be a faster alternative. Notes Masked arrays X, Y and C may be masked arrays. If either C[i, j], or one of the vertices surrounding C[i, j] (X or Y at [i, j], [i+1, j], [i, j+1], [i+1, j+1]) is masked, nothing is plotted. Grid orientation The grid orientation follows the standard matrix convention: An array C with shape (nrows, ncolumns) is plotted with the column number as X and the row number as Y.
doc_28028
Reset the warnings filter. This discards the effect of all previous calls to filterwarnings(), including that of the -W command line options and calls to simplefilter().
doc_28029
This method does nothing.
doc_28030
Renders a widget to HTML using the given renderer. If renderer is None, the renderer from the FORM_RENDERER setting is used.
doc_28031
Return whether the artist is pickable. See also set_picker, get_picker, pick
doc_28032
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
doc_28033
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. The name of the section must be a string; if not, TypeError is raised. Changed in version 3.2: Non-string section names raise TypeError.
doc_28034
Convert o to a JSON serializable type. See json.JSONEncoder.default(). Python does not support overriding how basic types like str or list are serialized, they are handled before this method. Parameters o (Any) – Return type Any
doc_28035
tf.compat.v1.get_variable( name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, custom_getter=None, constraint=None, synchronization=tf.VariableSynchronization.AUTO, aggregation=tf.compat.v1.VariableAggregation.NONE ) This function prefixes the name with the current variable scope and performs reuse checks. See the Variable Scope How To for an extensive description of how reusing works. Here is a basic example: def foo(): with tf.variable_scope("foo", reuse=tf.AUTO_REUSE): v = tf.get_variable("v", [1]) return v v1 = foo() # Creates v. v2 = foo() # Gets the same, existing v. assert v1 == v2 If initializer is None (the default), the default initializer passed in the variable scope will be used. If that one is None too, a glorot_uniform_initializer will be used. The initializer can also be a Tensor, in which case the variable is initialized to this value and shape. Similarly, if the regularizer is None (the default), the default regularizer passed in the variable scope will be used (if that is None too, then by default no regularization is performed). If a partitioner is provided, a PartitionedVariable is returned. Accessing this object as a Tensor returns the shards concatenated along the partition axis. Some useful partitioners are available. See, e.g., variable_axis_size_partitioner and min_max_variable_partitioner. Args name The name of the new or existing variable. shape Shape of the new or existing variable. dtype Type of the new or existing variable (defaults to DT_FLOAT). initializer Initializer for the variable if one is created. Can either be an initializer object or a Tensor. If it's a Tensor, its shape must be known unless validate_shape is False. regularizer A (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection tf.GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. trainable If True also add the variable to the graph collection GraphKeys.TRAINABLE_VARIABLES (see tf.Variable). collections List of graph collections keys to add the Variable to. Defaults to [GraphKeys.GLOBAL_VARIABLES] (see tf.Variable). caching_device Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. If not None, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through Switch and other conditional statements. partitioner Optional callable that accepts a fully defined TensorShape and dtype of the Variable to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). validate_shape If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known. For this to be used the initializer must be a Tensor and not an initializer object. use_resource If False, creates a regular Variable. If true, creates an experimental ResourceVariable instead with well-defined semantics. Defaults to False (will later change to True). When eager execution is enabled this argument is always forced to be True. custom_getter Callable that takes as a first argument the true getter, and allows overwriting the internal get_variable method. The signature of custom_getter should match that of this method, but the most future-proof version will allow for changes: def custom_getter(getter, *args, **kwargs). Direct access to all get_variable parameters is also allowed: def custom_getter(getter, name, *args, **kwargs). A simple identity custom getter that simply creates variables with modified names is: def custom_getter(getter, name, *args, **kwargs): return getter(name + '_suffix', *args, **kwargs) constraint An optional projection function to be applied to the variable after being updated by an Optimizer (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. synchronization Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class tf.VariableSynchronization. By default the synchronization is set to AUTO and the current DistributionStrategy chooses when to synchronize. aggregation Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class tf.VariableAggregation. Returns The created or existing Variable (or PartitionedVariable, if a partitioner was used). Raises ValueError when creating a new variable and shape is not declared, when violating reuse during variable creation, or when initializer dtype and dtype don't match. Reuse is set inside variable_scope.
doc_28036
Returns a copy of the calling offset object with n=1 and all other attributes equal.
doc_28037
Returns the logarithm of x to the given base. If the base is not specified, returns the natural logarithm of x. There is one branch cut, from 0 along the negative real axis to -∞, continuous from above.
doc_28038
Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer. See glossary entry for cross-validation estimator. The optimization objective for MultiTaskLasso is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2 + alpha * ||W||_21 Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2} i.e. the sum of norm of each row. Read more in the User Guide. New in version 0.15. Parameters epsfloat, default=1e-3 Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3. n_alphasint, default=100 Number of alphas along the regularization path. alphasarray-like, default=None List of alphas where to compute the models. If not provided, set automatically. fit_interceptbool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered). normalizebool, default=False This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False. max_iterint, default=1000 The maximum number of iterations. tolfloat, default=1e-4 The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol. copy_Xbool, default=True If True, X will be copied; else, it may be overwritten. cvint, cross-validation generator or iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross-validation, int, to specify the number of folds. CV splitter, An iterable yielding (train, test) splits as arrays of indices. For int/None inputs, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here. Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold. verbosebool or int, default=False Amount of verbosity. n_jobsint, default=None Number of CPUs to use during the cross validation. Note that this is used only if multiple values for l1_ratio are given. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. random_stateint, RandomState instance, default=None The seed of the pseudo random number generator that selects a random feature to update. Used when selection == ‘random’. Pass an int for reproducible output across multiple function calls. See Glossary. selection{‘cyclic’, ‘random’}, default=’cyclic’ If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4. Attributes intercept_ndarray of shape (n_tasks,) Independent term in decision function. coef_ndarray of shape (n_tasks, n_features) Parameter vector (W in the cost function formula). Note that coef_ stores the transpose of W, W.T. alpha_float The amount of penalization chosen by cross validation. mse_path_ndarray of shape (n_alphas, n_folds) Mean square error for the test set on each fold, varying alpha. alphas_ndarray of shape (n_alphas,) The grid of alphas used for fitting. n_iter_int Number of iterations run by the coordinate descent solver to reach the specified tolerance for the optimal alpha. dual_gap_float The dual gap at the end of the optimization for the optimal alpha. See also MultiTaskElasticNet ElasticNetCV MultiTaskElasticNetCV Notes The algorithm used to fit the model is coordinate descent. To avoid unnecessary memory duplication the X and y arguments of the fit method should be directly passed as Fortran-contiguous numpy arrays. Examples >>> from sklearn.linear_model import MultiTaskLassoCV >>> from sklearn.datasets import make_regression >>> from sklearn.metrics import r2_score >>> X, y = make_regression(n_targets=2, noise=4, random_state=0) >>> reg = MultiTaskLassoCV(cv=5, random_state=0).fit(X, y) >>> r2_score(y, reg.predict(X)) 0.9994... >>> reg.alpha_ 0.5713... >>> reg.predict(X[:1,]) array([[153.7971..., 94.9015...]]) Methods fit(X, y) Fit linear model with coordinate descent. get_params([deep]) Get parameters for this estimator. path(*args, **kwargs) Compute Lasso path with coordinate descent predict(X) Predict using the linear model. score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction. set_params(**params) Set the parameters of this estimator. fit(X, y) [source] Fit linear model with coordinate descent. Fit is on grid of alphas and best alpha estimated by cross-validation. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output, X can be sparse. yarray-like of shape (n_samples,) or (n_samples, n_targets) Target values. 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. static path(*args, **kwargs) [source] Compute Lasso path with coordinate descent The Lasso optimization function varies for mono and multi-outputs. For mono-output tasks it is: (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 For multi-output tasks it is: (1 / (2 * n_samples)) * ||Y - XW||^2_Fro + alpha * ||W||_21 Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2} i.e. the sum of norm of each row. Read more in the User Guide. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output then X can be sparse. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values epsfloat, default=1e-3 Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3 n_alphasint, default=100 Number of alphas along the regularization path alphasndarray, default=None List of alphas where to compute the models. If None alphas are set automatically precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’ Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument. Xyarray-like of shape (n_features,) or (n_features, n_outputs), default=None Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed. copy_Xbool, default=True If True, X will be copied; else, it may be overwritten. coef_initndarray of shape (n_features, ), default=None The initial values of the coefficients. verbosebool or int, default=False Amount of verbosity. return_n_iterbool, default=False whether to return the number of iterations or not. positivebool, default=False If set to True, forces coefficients to be positive. (Only allowed when y.ndim == 1). **paramskwargs keyword arguments passed to the coordinate descent solver. Returns alphasndarray of shape (n_alphas,) The alphas along the path where models are computed. coefsndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas) Coefficients along the path. dual_gapsndarray of shape (n_alphas,) The dual gaps at the end of the optimization for each alpha. n_iterslist of int The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. See also lars_path Lasso LassoLars LassoCV LassoLarsCV sklearn.decomposition.sparse_encode Notes For an example, see examples/linear_model/plot_lasso_coordinate_descent_path.py. To avoid unnecessary memory duplication the X argument of the fit method should be directly passed as a Fortran-contiguous numpy array. Note that in certain cases, the Lars solver may be significantly faster to implement this functionality. In particular, linear interpolation can be used to retrieve model coefficients between the values output by lars_path Examples Comparing lasso_path and lars_path with interpolation: >>> X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T >>> y = np.array([1, 2, 3.1]) >>> # Use lasso_path to compute a coefficient path >>> _, coef_path, _ = lasso_path(X, y, alphas=[5., 1., .5]) >>> print(coef_path) [[0. 0. 0.46874778] [0.2159048 0.4425765 0.23689075]] >>> # Now use lars_path and 1D linear interpolation to compute the >>> # same path >>> from sklearn.linear_model import lars_path >>> alphas, active, coef_path_lars = lars_path(X, y, method='lasso') >>> from scipy import interpolate >>> coef_path_continuous = interpolate.interp1d(alphas[::-1], ... coef_path_lars[:, ::-1]) >>> print(coef_path_continuous([5., 1., .5])) [[0. 0. 0.46915237] [0.2159048 0.4425765 0.23668876]] predict(X) [source] Predict using the linear model. Parameters Xarray-like or sparse matrix, shape (n_samples, n_features) Samples. Returns Carray, shape (n_samples,) Returns predicted values. score(X, y, sample_weight=None) [source] Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred) ** 2).sum() and \(v\) is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters Xarray-like of shape (n_samples, n_features) Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True values for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat \(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor). set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_28039
Evaluates the lowest cost contraction order for an einsum expression by considering the creation of intermediate arrays. Parameters subscriptsstr Specifies the subscripts for summation. *operandslist of array_like These are the arrays for the operation. optimize{bool, list, tuple, ‘greedy’, ‘optimal’} Choose the type of path. If a tuple is provided, the second argument is assumed to be the maximum intermediate size created. If only a single argument is provided the largest input or output array size is used as a maximum intermediate size. if a list is given that starts with einsum_path, uses this as the contraction path if False no optimization is taken if True defaults to the ‘greedy’ algorithm ‘optimal’ An algorithm that combinatorially explores all possible ways of contracting the listed tensors and choosest the least costly path. Scales exponentially with the number of terms in the contraction. ‘greedy’ An algorithm that chooses the best pair contraction at each step. Effectively, this algorithm searches the largest inner, Hadamard, and then outer products at each step. Scales cubically with the number of terms in the contraction. Equivalent to the ‘optimal’ path for most contractions. Default is ‘greedy’. Returns pathlist of tuples A list representation of the einsum path. string_reprstr A printable representation of the einsum path. See also einsum, linalg.multi_dot Notes The resulting path indicates which terms of the input contraction should be contracted first, the result of this contraction is then appended to the end of the contraction list. This list can then be iterated over until all intermediate contractions are complete. Examples We can begin with a chain dot example. In this case, it is optimal to contract the b and c tensors first as represented by the first element of the path (1, 2). The resulting tensor is added to the end of the contraction and the remaining contraction (0, 1) is then completed. >>> np.random.seed(123) >>> a = np.random.rand(2, 2) >>> b = np.random.rand(2, 5) >>> c = np.random.rand(5, 2) >>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy') >>> print(path_info[0]) ['einsum_path', (1, 2), (0, 1)] >>> print(path_info[1]) Complete contraction: ij,jk,kl->il # may vary Naive scaling: 4 Optimized scaling: 3 Naive FLOP count: 1.600e+02 Optimized FLOP count: 5.600e+01 Theoretical speedup: 2.857 Largest intermediate: 4.000e+00 elements ------------------------------------------------------------------------- scaling current remaining ------------------------------------------------------------------------- 3 kl,jk->jl ij,jl->il 3 jl,ij->il il->il A more complex index transformation example. >>> I = np.random.rand(10, 10, 10, 10) >>> C = np.random.rand(10, 10) >>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C, ... optimize='greedy') >>> print(path_info[0]) ['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)] >>> print(path_info[1]) Complete contraction: ea,fb,abcd,gc,hd->efgh # may vary Naive scaling: 8 Optimized scaling: 5 Naive FLOP count: 8.000e+08 Optimized FLOP count: 8.000e+05 Theoretical speedup: 1000.000 Largest intermediate: 1.000e+04 elements -------------------------------------------------------------------------- scaling current remaining -------------------------------------------------------------------------- 5 abcd,ea->bcde fb,gc,hd,bcde->efgh 5 bcde,fb->cdef gc,hd,cdef->efgh 5 cdef,gc->defg hd,defg->efgh 5 defg,hd->efgh efgh->efgh
doc_28040
Force the mask to soft. Whether the mask of a masked array is hard or soft is determined by its hardmask property. soften_mask sets hardmask to False. See also ma.MaskedArray.hardmask
doc_28041
Concrete implementation of InspectLoader.get_source().
doc_28042
tf.experimental.numpy.around( a, decimals=0 ) Unsupported arguments: out. See the NumPy documentation for numpy.around.
doc_28043
Return whether y values increase from top to bottom. Note that this only affects drawing of texts and images.
doc_28044
Return the lowercased value (without parameters) of the message’s Content-Disposition header if it has one, or None. The possible values for this method are inline, attachment or None if the message follows RFC 2183. New in version 3.5.
doc_28045
tf.compat.v1.arg_max( input, dimension, output_type=tf.dtypes.int64, name=None ) Note that in case of ties the identity of the return value is not guaranteed. Usage: import tensorflow as tf a = [1, 10, 26.9, 2.8, 166.32, 62.3] b = tf.math.argmax(input = a) c = tf.keras.backend.eval(b) # c = 4 # here a[4] = 166.32 which is the largest element of a across axis 0 Args input 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, bool. dimension A Tensor. Must be one of the following types: int32, int64. int32 or int64, must be in the range [-rank(input), rank(input)). Describes which dimension of the input Tensor to reduce across. For vectors, use dimension = 0. output_type An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int64. name A name for the operation (optional). Returns A Tensor of type output_type.
doc_28046
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. 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. check_inputbool, default=True Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns yarray-like of shape (n_samples,) or (n_samples, n_outputs) The predicted classes, or the predict values.
doc_28047
Mark the breakpoint as enabled.
doc_28048
Loader that wraps Python’s “classic” import algorithm. Deprecated since version 3.3: This emulation is no longer needed, as the standard import mechanism is now fully PEP 302 compliant and available in importlib.
doc_28049
Bases: matplotlib.backend_bases.RendererBase The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles buffer_rgba()[source] clear()[source] draw_mathtext(gc, x, y, s, prop, angle)[source] Draw mathtext using matplotlib.mathtext. draw_path(gc, path, transform, rgbFace=None)[source] Draw a Path instance using the given affine transform. draw_tex(gc, x, y, s, prop, angle, *, mtext=None)[source] draw_text(gc, x, y, s, prop, angle, ismath=False, mtext=None)[source] Draw the text instance. Parameters gcGraphicsContextBase The graphics context. xfloat The x location of the text in display coords. yfloat The y location of the text baseline in display coords. sstr The text string. propmatplotlib.font_manager.FontProperties The font properties. anglefloat The rotation angle in degrees anti-clockwise. mtextmatplotlib.text.Text The original text object to be rendered. Notes Note for backend implementers: When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in text.py: if 0: bbox_artist(self, renderer) to if 1, and then the actual bounding box will be plotted along with your text. get_canvas_width_height()[source] Return the canvas width and height in display coords. get_content_extents()[source] [Deprecated] Notes Deprecated since version 3.4: get_text_width_height_descent(s, prop, ismath)[source] Get the width, height, and descent (offset from the bottom to the baseline), in display coords, of the string s with FontProperties prop. lock=<unlocked _thread.RLock object owner=0 count=0> option_image_nocomposite()[source] Return whether image composition by Matplotlib should be skipped. Raster backends should usually return False (letting the C-level rasterizer take care of image composition); vector backends should usually return not rcParams["image.composite_image"]. option_scale_image()[source] Return whether arbitrary affine transformations in draw_image() are supported (True for most vector backends). points_to_pixels(points)[source] Convert points to display units. You need to override this function (unless your backend doesn't have a dpi, e.g., postscript or svg). Some imaging systems assume some value for pixels per inch: points to pixels = points * pixels_per_inch/72 * dpi/72 Parameters pointsfloat or array-like a float or a numpy array of float Returns Points converted to pixels restore_region(region, bbox=None, xy=None)[source] Restore the saved region. If bbox (instance of BboxBase, or its extents) is given, only the region specified by the bbox will be restored. xy (a pair of floats) optionally specifies the new position (the LLC of the original region, not the LLC of the bbox) where the region will be restored. >>> region = renderer.copy_from_bbox() >>> x1, y1, x2, y2 = region.get_extents() >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2), ... xy=(x1-dx, y1)) start_filter()[source] Start filtering. It simply create a new canvas (the old one is saved). stop_filter(post_processing)[source] Save the plot in the current canvas as a image and apply the post_processing function. def post_processing(image, dpi): # ny, nx, depth = image.shape # image (numpy array) has RGBA channels and has a depth of 4. ... # create a new_image (numpy array of 4 channels, size can be # different). The resulting image may have offsets from # lower-left corner of the original image return new_image, offset_x, offset_y The saved renderer is restored and the returned image from post_processing is plotted (using draw_image) on it. tostring_argb()[source] tostring_rgb()[source] tostring_rgba_minimized()[source] [Deprecated] Notes Deprecated since version 3.4:
doc_28050
Averages all events. Returns A FunctionEventAvg object.
doc_28051
See Migration guide for more details. tf.compat.v1.image.crop_to_bounding_box tf.image.crop_to_bounding_box( image, offset_height, offset_width, target_height, target_width ) This op cuts a rectangular part out of image. The top-left corner of the returned image is at offset_height, offset_width in image, and its lower-right corner is at offset_height + target_height, offset_width + target_width. Args image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels]. offset_height Vertical coordinate of the top-left corner of the result in the input. offset_width Horizontal coordinate of the top-left corner of the result in the input. target_height Height of the result. target_width Width of the result. Returns If image was 4-D, a 4-D float Tensor of shape [batch, target_height, target_width, channels] If image was 3-D, a 3-D float Tensor of shape [target_height, target_width, channels] Raises ValueError If the shape of image is incompatible with the offset_* or target_* arguments, or either offset_height or offset_width is negative, or either target_height or target_width is not positive.
doc_28052
Bases: matplotlib.lines.Line2D 3D line object. Keyword arguments are passed onto Line2D(). draw(renderer)[source] 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. get_data_3d()[source] Get the current data Returns verts3dlength-3 tuple or array-like The current data as a tuple or array-like. set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, dash_capstyle=<UNSET>, dash_joinstyle=<UNSET>, dashes=<UNSET>, data=<UNSET>, data_3d=<UNSET>, drawstyle=<UNSET>, fillstyle=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, marker=<UNSET>, markeredgecolor=<UNSET>, markeredgewidth=<UNSET>, markerfacecolor=<UNSET>, markerfacecoloralt=<UNSET>, markersize=<UNSET>, markevery=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, solid_capstyle=<UNSET>, solid_joinstyle=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, xdata=<UNSET>, ydata=<UNSET>, zorder=<UNSET>)[source] Set multiple properties at once. Supported properties are Property Description 3d_properties unknown agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None animated bool antialiased or aa bool clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None color or c color dash_capstyle CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle JoinStyle or {'miter', 'round', 'bevel'} dashes sequence of floats (on/off ink in points) or (None, None) data (2, N) array or two 1D arrays data_3d unknown drawstyle or ds {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure Figure fillstyle {'full', 'left', 'right', 'bottom', 'top', 'none'} gid str in_layout bool label object linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw float marker marker style string, Path or MarkerStyle markeredgecolor or mec color markeredgewidth or mew float markerfacecolor or mfc color markerfacecoloralt or mfcalt color markersize or ms float markevery None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects AbstractPathEffect picker float or callable[[Artist, Event], tuple[bool, dict]] pickradius float rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None solid_capstyle CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle JoinStyle or {'miter', 'round', 'bevel'} transform Transform url str visible bool xdata 1D array ydata 1D array zorder float set_3d_properties(zs=0, zdir='z')[source] set_data_3d(*args)[source] Set the x, y and z data Parameters xarray-like The x-data to be plotted. yarray-like The y-data to be plotted. zarray-like The z-data to be plotted. Notes Accepts x, y, z arguments or a single array-like (x, y, z) Examples using mpl_toolkits.mplot3d.art3d.Line3D 3D stem
doc_28053
Returns the Model with the given model_name. model_name is case-insensitive. Raises LookupError if no such model exists in this application. Requires the app registry to be fully populated unless the require_ready argument is set to False. require_ready behaves exactly as in apps.get_model().
doc_28054
Return the image extent as tuple (left, right, bottom, top).
doc_28055
data: The serialized data for the response. status: A status code for the response. Defaults to 200. See also status codes. template_name: A template name to use if HTMLRenderer is selected. headers: A dictionary of HTTP headers to use in the response. content_type: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly. Attributes .data The unrendered, serialized data of the response. .status_code The numeric status code of the HTTP response. .content The rendered content of the response. The .render() method must have been called before .content can be accessed. .template_name The template_name, if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response. .accepted_renderer The renderer instance that will be used to render the response. Set automatically by the APIView or @api_view immediately before the response is returned from the view. .accepted_media_type The media type that was selected by the content negotiation stage. Set automatically by the APIView or @api_view immediately before the response is returned from the view. .renderer_context A dictionary of additional context information that will be passed to the renderer's .render() method. Set automatically by the APIView or @api_view immediately before the response is returned from the view. Standard HttpResponse attributes The Response class extends SimpleTemplateResponse, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way: response = Response() response['Cache-Control'] = 'no-cache' .render() Signature: .render() As with any other TemplateResponse, this method is called to render the serialized data of the response into the final response content. When .render() is called, the response content will be set to the result of calling the .render(data, accepted_media_type, renderer_context) method on the accepted_renderer instance. You won't typically need to call .render() yourself, as it's handled by Django's standard response cycle. response.py
doc_28056
Return whether the mouse event occurred inside the axis-aligned bounding-box of the text.
doc_28057
Apply only the affine part of this transformation on the given array of values. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). In non-affine transformations, this is generally a no-op. In affine transformations, this is equivalent to transform(values). Parameters valuesarray The input values as NumPy array of length input_dims or shape (N x input_dims). Returns array The output values as NumPy array of length input_dims or shape (N x output_dims), depending on the input.
doc_28058
Return this Axis' scale (as a str).
doc_28059
tf.compat.v1.train.NewCheckpointReader( filepattern ) Args filepattern The filename. Returns A CheckpointReader object.
doc_28060
A dictionary of additional attributes for process creation as given in STARTUPINFOEX, see UpdateProcThreadAttribute. Supported attributes: handle_list Sequence of handles that will be inherited. close_fds must be true if non-empty. The handles must be temporarily made inheritable by os.set_handle_inheritable() when passed to the Popen constructor, else OSError will be raised with Windows error ERROR_INVALID_PARAMETER (87). Warning In a multithreaded process, use caution to avoid leaking handles that are marked inheritable when combining this feature with concurrent calls to other process creation functions that inherit all handles such as os.system(). This also applies to standard handle redirection, which temporarily creates inheritable handles. New in version 3.7.
doc_28061
Return the appropriate pdf operator to cause the path to be stroked, filled, or both.
doc_28062
Sets the module in training mode. This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc. Parameters mode (bool) – whether to set training mode (True) or evaluation mode (False). Default: True. Returns self Return type Module
doc_28063
Identifier of the device on which this file resides.
doc_28064
Scale back the data to the original representation Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The data that should be transformed back. Returns X_tr{ndarray, sparse matrix} of shape (n_samples, n_features) Transformed array.
doc_28065
Handles the Content-Transfer-Encoding header. cte Valid values are 7bit, 8bit, base64, and quoted-printable. See RFC 2045 for more information.
doc_28066
See Migration guide for more details. tf.compat.v1.fft2d, tf.compat.v1.signal.fft2d, tf.compat.v1.spectral.fft2d tf.signal.fft2d( input, name=None ) Computes the 2-dimensional discrete Fourier transform over the inner-most 2 dimensions of input. Args input A Tensor. Must be one of the following types: complex64, complex128. A complex tensor. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
doc_28067
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_28068
Reads the logging configuration from a configparser-format file. The format of the file should be as described in Configuration file format. This function can be called several times from an application, allowing an end user to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). Parameters fname – A filename, or a file-like object, or an instance derived from RawConfigParser. If a RawConfigParser-derived instance is passed, it is used as is. Otherwise, a Configparser is instantiated, and the configuration read by it from the object passed in fname. If that has a readline() method, it is assumed to be a file-like object and read using read_file(); otherwise, it is assumed to be a filename and passed to read(). defaults – Defaults to be passed to the ConfigParser can be specified in this argument. disable_existing_loggers – If specified as False, loggers which exist when this call is made are left enabled. The default is True because this enables old behaviour in a backward-compatible way. This behaviour is to disable any existing non-root loggers unless they or their ancestors are explicitly named in the logging configuration. Changed in version 3.4: An instance of a subclass of RawConfigParser is now accepted as a value for fname. This facilitates: Use of a configuration file where logging configuration is just part of the overall application configuration. Use of a configuration read from a file, and then modified by the using application (e.g. based on command-line parameters or other aspects of the runtime environment) before being passed to fileConfig.
doc_28069
tf.multiply Compat aliases for migration See Migration guide for more details. tf.compat.v1.math.multiply, tf.compat.v1.multiply tf.math.multiply( x, y, name=None ) For example: x = tf.constant(([1, 2, 3, 4])) tf.math.multiply(x, x) <tf.Tensor: shape=(4,), dtype=..., numpy=array([ 1, 4, 9, 16], dtype=int32)> Since tf.math.multiply will convert its arguments to Tensors, you can also pass in non-Tensor arguments: tf.math.multiply(7,6) <tf.Tensor: shape=(), dtype=int32, numpy=42> If x.shape is not thes same as y.shape, they will be broadcast to a compatible shape. (More about broadcasting here.) For example: x = tf.ones([1, 2]); y = tf.ones([2, 1]); x * y # Taking advantage of operator overriding <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[1., 1.], [1., 1.]], dtype=float32)> Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x. Raises InvalidArgumentError: When x and y have incomptatible shapes or types.
doc_28070
Return True if cookie has the named cookie-attribute.
doc_28071
tf.compat.v1.substr( input, pos, len, name=None, unit='BYTE' ) For each string in the input Tensor, creates a substring starting at index pos with a total length of len. If len defines a substring that would extend beyond the length of the input string, or if len is negative, then as many characters as possible are used. A negative pos indicates distance within the string backwards from the end. If pos specifies an index which is out of range for any of the input strings, then an InvalidArgumentError is thrown. pos and len must have the same shape, otherwise a ValueError is thrown on Op creation. Note: Substr supports broadcasting up to two dimensions. More about broadcasting here Examples Using scalar pos and len: input = [b'Hello', b'World'] position = 1 length = 3 output = [b'ell', b'orl'] Using pos and len with same shape as input: input = [[b'ten', b'eleven', b'twelve'], [b'thirteen', b'fourteen', b'fifteen'], [b'sixteen', b'seventeen', b'eighteen']] position = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] length = [[2, 3, 4], [4, 3, 2], [5, 5, 5]] output = [[b'en', b'eve', b'lve'], [b'hirt', b'urt', b'te'], [b'ixtee', b'vente', b'hteen']] Broadcasting pos and len onto input: input = [[b'ten', b'eleven', b'twelve'], [b'thirteen', b'fourteen', b'fifteen'], [b'sixteen', b'seventeen', b'eighteen'], [b'nineteen', b'twenty', b'twentyone']] position = [1, 2, 3] length = [1, 2, 3] output = [[b'e', b'ev', b'lve'], [b'h', b'ur', b'tee'], [b'i', b've', b'hte'], [b'i', b'en', b'nty']] Broadcasting input onto pos and len: input = b'thirteen' position = [1, 5, 7] length = [3, 2, 1] output = [b'hir', b'ee', b'n'] Raises ValueError: If the first argument cannot be converted to a Tensor of dtype string. InvalidArgumentError: If indices are out of range. ValueError: If pos and len are not the same shape. Args input A Tensor of type string. Tensor of strings pos A Tensor. Must be one of the following types: int32, int64. Scalar defining the position of first character in each substring len A Tensor. Must have the same type as pos. Scalar defining the number of characters to include in each substring unit An optional string from: "BYTE", "UTF8_CHAR". Defaults to "BYTE". The unit that is used to create the substring. One of: "BYTE" (for defining position and length by bytes) or "UTF8_CHAR" (for the UTF-8 encoded Unicode code points). The default is "BYTE". Results are undefined if unit=UTF8_CHAR and the input strings do not contain structurally valid UTF-8. name A name for the operation (optional). Returns A Tensor of type string.
doc_28072
Get a list of artists contained in the figure.
doc_28073
See Migration guide for more details. tf.compat.v1.train.Example Attributes features Features features
doc_28074
Wraps an int. This is used when reading or writing NSKeyedArchiver encoded data, which contains UID (see PList manual). It has one attribute, data, which can be used to retrieve the int value of the UID. data must be in the range 0 <= data < 2**64. New in version 3.8.
doc_28075
Rewind the read pointer. The next readframes() will start from the beginning.
doc_28076
Print a help message, including the program usage and information about the arguments registered with the ArgumentParser. If file is None, sys.stdout is assumed.
doc_28077
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns self.tree_.max_depthint The maximum depth of the tree.
doc_28078
Return a list of the child Artists of this Artist.
doc_28079
Similar to the guess_all_extensions() function, using the tables stored as part of the object.
doc_28080
Given a Tensor quantized by linear(affine) quantization, returns the scale of the underlying quantizer().
doc_28081
tf.experimental.numpy.polyval( p, x ) See the NumPy documentation for numpy.polyval.
doc_28082
Return the result of shifting the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to shift. If the second operand is positive then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. The sign and exponent of the first operand are unchanged.
doc_28083
Retrieves the value set by set_tabsize(). New in version 3.9.
doc_28084
Set the pick radius used for containment tests. See contains for more details. Parameters dfloat Pick radius, in points.
doc_28085
See Migration guide for more details. tf.compat.v1.raw_ops.Min tf.raw_ops.Min( input, axis, keep_dims=False, name=None ) Reduces input along the dimensions given in axis. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in axis. If keep_dims is true, the reduced dimensions are retained with length 1. Args input A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64, qint8, quint8, qint32, qint16, quint16. The tensor to reduce. axis A Tensor. Must be one of the following types: int32, int64. The dimensions to reduce. Must be in the range [-rank(input), rank(input)). keep_dims An optional bool. Defaults to False. If true, retain reduced dimensions with length 1. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
doc_28086
tf.compat.v1.losses.mean_pairwise_squared_error( labels, predictions, weights=1.0, scope=None, loss_collection=tf.GraphKeys.LOSSES ) Unlike mean_squared_error, which is a measure of the differences between corresponding elements of predictions and labels, mean_pairwise_squared_error is a measure of the differences between pairs of corresponding elements of predictions and labels. For example, if labels=[a, b, c] and predictions=[x, y, z], there are three pairs of differences are summed to compute the loss: loss = [ ((a-b) - (x-y)).^2 + ((a-c) - (x-z)).^2 + ((b-c) - (y-z)).^2 ] / 3 Note that since the inputs are of shape [batch_size, d0, ... dN], the corresponding pairs are computed within each batch sample but not across samples within a batch. For example, if predictions represents a batch of 16 grayscale images of dimension [batch_size, 100, 200], then the set of pairs is drawn from each image, but not across images. 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 size [batch_size], then the total loss for each sample of the batch is rescaled by the corresponding element in the weights vector. Args labels The ground truth output tensor, whose shape must match the shape of predictions. predictions The predicted outputs, a tensor of size [batch_size, d0, .. dN] where N+1 is the total number of dimensions in predictions. weights Coefficients for the loss a scalar, a tensor of shape [batch_size] or a tensor whose shape matches predictions. scope The scope for the operations performed in computing the loss. loss_collection collection to which the loss will be added. Returns A scalar Tensor that returns the weighted loss. Raises ValueError If the shape of predictions doesn't match that of labels or if the shape of weights is invalid. Also if labels or predictions 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_28087
Scalar method identical to the corresponding array attribute. Please see ndarray.mean.
doc_28088
Return True if the float instance is finite with integral value, and False otherwise: >>> (-2.0).is_integer() True >>> (3.2).is_integer() False
doc_28089
See Migration guide for more details. tf.compat.v1.math.sobol_sample tf.math.sobol_sample( dim, num_results, skip=0, dtype=tf.dtypes.float32, name=None ) Creates a Sobol sequence with num_results samples. Each sample has dimension dim. Skips the first skip samples. Args dim Positive scalar Tensor representing each sample's dimension. num_results Positive scalar Tensor of dtype int32. The number of Sobol points to return in the output. skip (Optional) Positive scalar Tensor of dtype int32. The number of initial points of the Sobol sequence to skip. Default value is 0. dtype (Optional) The tf.Dtype of the sample. One of: tf.float32 or tf.float64. Defaults to tf.float32. name (Optional) Python str name prefixed to ops created by this function. Returns Tensor of samples from Sobol sequence with shape [num_results, dim].
doc_28090
Return all the non-masked data as a 1-D array. This function is equivalent to calling the “compressed” method of a ma.MaskedArray, see ma.MaskedArray.compressed for details. See also ma.MaskedArray.compressed Equivalent method.
doc_28091
Set the x-axis scale. Parameters value{"linear"} The axis scale type to apply. 3D axes currently only support linear scales; other scales yield nonsensical results. **kwargs Keyword arguments are nominally forwarded to the scale class, but none of them is applicable for linear scales.
doc_28092
Sets gradients of all model parameters to zero. See similar function under torch.optim.Optimizer for more context. Parameters set_to_none (bool) – instead of setting to zero, set the grads to None. See torch.optim.Optimizer.zero_grad() for details.
doc_28093
Token value for ">".
doc_28094
ContentType also has a custom manager, ContentTypeManager, which adds the following methods: clear_cache() Clears an internal cache used by ContentType to keep track of models for which it has created ContentType instances. You probably won’t ever need to call this method yourself; Django will call it automatically when it’s needed. get_for_id(id) Lookup a ContentType by ID. Since this method uses the same shared cache as get_for_model(), it’s preferred to use this method over the usual ContentType.objects.get(pk=id) get_for_model(model, for_concrete_model=True) Takes either a model class or an instance of a model, and returns the ContentType instance representing that model. for_concrete_model=False allows fetching the ContentType of a proxy model. get_for_models(*models, for_concrete_models=True) Takes a variadic number of model classes, and returns a dictionary mapping the model classes to the ContentType instances representing them. for_concrete_models=False allows fetching the ContentType of proxy models. get_by_natural_key(app_label, model) Returns the ContentType instance uniquely identified by the given application label and model name. The primary purpose of this method is to allow ContentType objects to be referenced via a natural key during deserialization.
doc_28095
Return divmod(self, value).
doc_28096
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.
doc_28097
Set the artist offset transform. Parameters transOffsetTransform
doc_28098
Initialize self. See help(type(self)) for accurate signature.
doc_28099
Resolve MRO entries dynamically as specified by PEP 560. This function looks for items in bases that are not instances of type, and returns a tuple where each such object that has an __mro_entries__ method is replaced with an unpacked result of calling this method. If a bases item is an instance of type, or it doesn’t have an __mro_entries__ method, then it is included in the return tuple unchanged. New in version 3.7.