_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_27000 |
Draw the math text using matplotlib.mathtext. | |
doc_27001 |
Call decision_function on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports decision_function. Parameters
Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator. | |
doc_27002 | See Migration guide for more details. tf.compat.v1.nn.scale_regularization_loss
tf.nn.scale_regularization_loss(
regularization_loss
)
Usage with distribution strategy and custom training loop: with strategy.scope():
def compute_loss(self, label, predictions):
per_example_loss = tf.keras.losses.sparse_categorical_crossentropy(
labels, predictions)
# Compute loss that is scaled by sample_weight and by global batch size.
loss = tf.nn.compute_average_loss(
per_example_loss,
sample_weight=sample_weight,
global_batch_size=GLOBAL_BATCH_SIZE)
# Add scaled regularization losses.
loss += tf.nn.scale_regularization_loss(tf.nn.l2_loss(weights))
return loss
Args
regularization_loss Regularization loss.
Returns Scalar loss value. | |
doc_27003 |
Create a new figure manager instance. | |
doc_27004 |
Return the group id. | |
doc_27005 | Pretend the whole window has been changed, for purposes of drawing optimizations. | |
doc_27006 | See torch.mul(). | |
doc_27007 | This signal is sent right before the response is sent to the client. It is passed the response to be sent named response. Example subscriber: def log_response(sender, response, **extra):
sender.logger.debug('Request context is about to close down. '
'Response: %s', response)
from flask import request_finished
request_finished.connect(log_response, app) | |
doc_27008 | See Migration guide for more details. tf.compat.v1.keras.layers.experimental.preprocessing.Hashing
tf.keras.layers.experimental.preprocessing.Hashing(
num_bins, salt=None, name=None, **kwargs
)
This layer transforms single or multiple categorical inputs to hashed output. It converts a sequence of int or string to a sequence of int. The stable hash function uses tensorflow::ops::Fingerprint to produce universal output that is consistent across platforms. This layer uses FarmHash64 by default, which provides a consistent hashed output across different platforms and is stable across invocations, regardless of device and context, by mixing the input bits thoroughly. If you want to obfuscate the hashed output, you can also pass a random salt argument in the constructor. In that case, the layer will use the SipHash64 hash function, with the salt value serving as additional input to the hash function. Example (FarmHash64):
layer = tf.keras.layers.experimental.preprocessing.Hashing(num_bins=3)
inp = [['A'], ['B'], ['C'], ['D'], ['E']]
layer(inp)
<tf.Tensor: shape=(5, 1), dtype=int64, numpy=
array([[1],
[0],
[1],
[1],
[2]])>
Example (FarmHash64) with list of inputs: >>> layer = tf.keras.layers.experimental.preprocessing.Hashing(num_bins=3)
>>> inp_1 = [['A'], ['B'], ['C'], ['D'], ['E']]
>>> inp_2 = np.asarray([[5], [4], [3], [2], [1]])
>>> layer([inp_1, inp_2])
<tf.Tensor: shape=(5, 1), dtype=int64, numpy=
array([[1],
[1],
[0],
[2],
[0]])>
Example (SipHash64):
layer = tf.keras.layers.experimental.preprocessing.Hashing(num_bins=3,
salt=[133, 137])
inp = [['A'], ['B'], ['C'], ['D'], ['E']]
layer(inp)
<tf.Tensor: shape=(5, 1), dtype=int64, numpy=
array([[1],
[2],
[1],
[0],
[2]])>
Example (Siphash64 with a single integer, same as salt=[133, 133]
layer = tf.keras.layers.experimental.preprocessing.Hashing(num_bins=3,
salt=133)
inp = [['A'], ['B'], ['C'], ['D'], ['E']]
layer(inp)
<tf.Tensor: shape=(5, 1), dtype=int64, numpy=
array([[0],
[0],
[2],
[1],
[0]])>
Reference: SipHash with salt
Arguments
num_bins Number of hash bins.
salt A single unsigned integer or None. If passed, the hash function used will be SipHash64, with these values used as an additional input (known as a "salt" in cryptography). These should be non-zero. Defaults to None (in that case, the FarmHash64 hash function is used). It also supports tuple/list of 2 unsigned integer numbers, see reference paper for details.
name Name to give to the layer.
**kwargs Keyword arguments to construct a layer. Input shape: A single or list of string, int32 or int64 Tensor, SparseTensor or RaggedTensor of shape [batch_size, ...,] Output shape: An int64 Tensor, SparseTensor or RaggedTensor of shape [batch_size, ...]. If any input is RaggedTensor then output is RaggedTensor, otherwise if any input is SparseTensor then output is SparseTensor, otherwise the output is Tensor. Methods adapt View source
adapt(
data, reset_state=True
)
Fits the state of the preprocessing layer to the data being passed.
Arguments
data The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array.
reset_state Optional argument specifying whether to clear the state of the layer at the start of the call to adapt, or whether to start from the existing state. This argument may not be relevant to all preprocessing layers: a subclass of PreprocessingLayer may choose to throw if 'reset_state' is set to False. | |
doc_27009 | Return the higher-level protocol that was selected during the TLS/SSL handshake. If SSLContext.set_npn_protocols() was not called, or if the other party does not support NPN, or if the handshake has not yet happened, this will return None. New in version 3.3. | |
doc_27010 |
Bases: skimage.viewer.viewers.core.ImageViewer Viewer for displaying image collections. Select the displayed frame of the image collection using the slider or with the following keyboard shortcuts: left/right arrows
Previous/next image in collection. number keys, 0–9
0% to 90% of collection. For example, “5” goes to the image in the middle (i.e. 50%) of the collection. home/end keys
First/last image in collection. Parameters
image_collectionlist of images
List of images to be displayed.
update_on{‘move’ | ‘release’}
Control whether image is updated on slide or release of the image slider. Using ‘on_release’ will give smoother behavior when displaying large images or when writing a plugin/subclass that requires heavy computation.
__init__(image_collection, update_on='move', **kwargs) [source]
Initialize self. See help(type(self)) for accurate signature.
keyPressEvent(event) [source]
update_index(name, index) [source]
Select image on display using index into image collection. | |
doc_27011 | Create a pipe with flags set atomically. flags can be constructed by ORing together one or more of these values: O_NONBLOCK, O_CLOEXEC. Return a pair of file descriptors (r, w) usable for reading and writing, respectively. Availability: some flavors of Unix. New in version 3.3. | |
doc_27012 | os.O_RSYNC
os.O_SYNC
os.O_NDELAY
os.O_NONBLOCK
os.O_NOCTTY
os.O_CLOEXEC
The above constants are only available on Unix. Changed in version 3.3: Add O_CLOEXEC constant. | |
doc_27013 |
Return the clipping behavior. See set_annotation_clip for the meaning of the return value. | |
doc_27014 | Convert the color from RGB coordinates to HLS coordinates. | |
doc_27015 | See Migration guide for more details. tf.compat.v1.raw_ops.OptimizeDatasetV2
tf.raw_ops.OptimizeDatasetV2(
input_dataset, optimizations_enabled, optimizations_disabled,
optimizations_default, output_types, output_shapes, optimization_configs=[],
name=None
)
Creates a dataset by applying related optimizations to input_dataset.
Args
input_dataset A Tensor of type variant. A variant tensor representing the input dataset.
optimizations_enabled A Tensor of type string. A tf.string vector tf.Tensor identifying user enabled optimizations.
optimizations_disabled A Tensor of type string. A tf.string vector tf.Tensor identifying user disabled optimizations.
optimizations_default A Tensor of type string. A tf.string vector tf.Tensor identifying optimizations by default.
output_types A list of tf.DTypes that has length >= 1.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1.
optimization_configs An optional list of strings. Defaults to [].
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_27016 |
Abstract base class for classes used to find the triangles of a Triangulation in which (x, y) points lie. Rather than instantiate an object of a class derived from TriFinder, it is usually better to use the function Triangulation.get_trifinder. Derived classes implement __call__(x, y) where x and y are array-like point coordinates of the same shape. | |
doc_27017 |
Set halfrange to max(abs(A-vcenter)), then set vmin and vmax. | |
doc_27018 | Enter the debugger at the calling stack frame. This is useful to hard-code a breakpoint at a given point in a program, even if the code is not otherwise being debugged (e.g. when an assertion fails). If given, header is printed to the console just before debugging begins. Changed in version 3.7: The keyword-only argument header. | |
doc_27019 |
Return the sizes ('areas') of the elements in the collection. Returns
array
The 'area' of each element. | |
doc_27020 |
Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js, so it allows users to interact with the rendered object. Besides the basic definitions such as vertices, faces, users can further provide camera parameter, lighting condition, etc. Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for advanced usage. Parameters
tag (string) – Data identifier
vertices (torch.Tensor) – List of the 3D coordinates of vertices.
colors (torch.Tensor) – Colors for each vertex
faces (torch.Tensor) – Indices of vertices within each triangle. (Optional)
config_dict – Dictionary with ThreeJS classes names and configuration.
global_step (int) – Global step value to record
walltime (float) – Optional override default walltime (time.time()) seconds after epoch of event Shape:
vertices: (B,N,3)(B, N, 3) . (batch, number_of_vertices, channels) colors: (B,N,3)(B, N, 3) . The values should lie in [0, 255] for type uint8 or [0, 1] for type float. faces: (B,N,3)(B, N, 3) . The values should lie in [0, number_of_vertices] for type uint8. Examples: from torch.utils.tensorboard import SummaryWriter
vertices_tensor = torch.as_tensor([
[1, 1, 1],
[-1, -1, 1],
[1, -1, -1],
[-1, 1, -1],
], dtype=torch.float).unsqueeze(0)
colors_tensor = torch.as_tensor([
[255, 0, 0],
[0, 255, 0],
[0, 0, 255],
[255, 0, 255],
], dtype=torch.int).unsqueeze(0)
faces_tensor = torch.as_tensor([
[0, 2, 3],
[0, 3, 1],
[0, 1, 2],
[1, 3, 2],
], dtype=torch.int).unsqueeze(0)
writer = SummaryWriter()
writer.add_mesh('my_mesh', vertices=vertices_tensor, colors=colors_tensor, faces=faces_tensor)
writer.close() | |
doc_27021 | Returns a GEOSGeometry representing all the points in this geometry and the other. | |
doc_27022 | See Migration guide for more details. tf.compat.v1.raw_ops.Squeeze
tf.raw_ops.Squeeze(
input, axis=[], name=None
)
Given a tensor input, this operation returns a tensor of the same type with all dimensions of size 1 removed. If you don't want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying axis. For example: # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
shape(squeeze(t)) ==> [2, 3]
Or, to remove specific size 1 dimensions: # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]
Args
input A Tensor. The input to squeeze.
axis An optional list of ints. Defaults to []. If specified, only squeezes the dimensions listed. The dimension index starts at 0. It is an error to squeeze a dimension that is not 1. Must be in the range [-rank(input), rank(input)).
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_27023 |
Alias for is_monotonic. | |
doc_27024 | skimage.metrics.adapted_rand_error([…]) Compute Adapted Rand error as defined by the SNEMI3D contest.
skimage.metrics.contingency_table(im_true, …) Return the contingency table for all regions in matched segmentations.
skimage.metrics.hausdorff_distance(image0, …) Calculate the Hausdorff distance between nonzero elements of given images.
skimage.metrics.mean_squared_error(image0, …) Compute the mean-squared error between two images.
skimage.metrics.normalized_root_mse(…[, …]) Compute the normalized root mean-squared error (NRMSE) between two images.
skimage.metrics.peak_signal_noise_ratio(…) Compute the peak signal to noise ratio (PSNR) for an image.
skimage.metrics.structural_similarity(im1, …) Compute the mean structural similarity index between two images.
skimage.metrics.variation_of_information([…]) Return symmetric conditional entropies associated with the VI. adapted_rand_error
skimage.metrics.adapted_rand_error(image_true=None, image_test=None, *, table=None, ignore_labels=(0, )) [source]
Compute Adapted Rand error as defined by the SNEMI3D contest. [1] Parameters
image_truendarray of int
Ground-truth label image, same shape as im_test.
image_testndarray of int
Test image.
tablescipy.sparse array in crs format, optional
A contingency table built with skimage.evaluate.contingency_table. If None, it will be computed on the fly.
ignore_labelssequence of int, optional
Labels to ignore. Any part of the true image labeled with any of these values will not be counted in the score. Returns
arefloat
The adapted Rand error; equal to \(1 - \frac{2pr}{p + r}\), where p and r are the precision and recall described below.
precfloat
The adapted Rand precision: this is the number of pairs of pixels that have the same label in the test label image and in the true image, divided by the number in the test image.
recfloat
The adapted Rand recall: this is the number of pairs of pixels that have the same label in the test label image and in the true image, divided by the number in the true image. Notes Pixels with label 0 in the true segmentation are ignored in the score. References
1
Arganda-Carreras I, Turaga SC, Berger DR, et al. (2015) Crowdsourcing the creation of image segmentation algorithms for connectomics. Front. Neuroanat. 9:142. DOI:10.3389/fnana.2015.00142
contingency_table
skimage.metrics.contingency_table(im_true, im_test, *, ignore_labels=None, normalize=False) [source]
Return the contingency table for all regions in matched segmentations. Parameters
im_truendarray of int
Ground-truth label image, same shape as im_test.
im_testndarray of int
Test image.
ignore_labelssequence of int, optional
Labels to ignore. Any part of the true image labeled with any of these values will not be counted in the score.
normalizebool
Determines if the contingency table is normalized by pixel count. Returns
contscipy.sparse.csr_matrix
A contingency table. cont[i, j] will equal the number of voxels labeled i in im_true and j in im_test.
hausdorff_distance
skimage.metrics.hausdorff_distance(image0, image1) [source]
Calculate the Hausdorff distance between nonzero elements of given images. The Hausdorff distance [1] is the maximum distance between any point on image0 and its nearest point on image1, and vice-versa. Parameters
image0, image1ndarray
Arrays where True represents a point that is included in a set of points. Both arrays must have the same shape. Returns
distancefloat
The Hausdorff distance between coordinates of nonzero pixels in image0 and image1, using the Euclidian distance. References
1
http://en.wikipedia.org/wiki/Hausdorff_distance Examples >>> points_a = (3, 0)
>>> points_b = (6, 0)
>>> shape = (7, 1)
>>> image_a = np.zeros(shape, dtype=bool)
>>> image_b = np.zeros(shape, dtype=bool)
>>> image_a[points_a] = True
>>> image_b[points_b] = True
>>> hausdorff_distance(image_a, image_b)
3.0
Examples using skimage.metrics.hausdorff_distance
Hausdorff Distance mean_squared_error
skimage.metrics.mean_squared_error(image0, image1) [source]
Compute the mean-squared error between two images. Parameters
image0, image1ndarray
Images. Any dimensionality, must have same shape. Returns
msefloat
The mean-squared error (MSE) metric. Notes Changed in version 0.16: This function was renamed from skimage.measure.compare_mse to skimage.metrics.mean_squared_error.
normalized_root_mse
skimage.metrics.normalized_root_mse(image_true, image_test, *, normalization='euclidean') [source]
Compute the normalized root mean-squared error (NRMSE) between two images. Parameters
image_truendarray
Ground-truth image, same shape as im_test.
image_testndarray
Test image.
normalization{‘euclidean’, ‘min-max’, ‘mean’}, optional
Controls the normalization method to use in the denominator of the NRMSE. There is no standard method of normalization across the literature [1]. The methods available here are as follows:
‘euclidean’ : normalize by the averaged Euclidean norm of im_true: NRMSE = RMSE * sqrt(N) / || im_true ||
where || . || denotes the Frobenius norm and N = im_true.size. This result is equivalent to: NRMSE = || im_true - im_test || / || im_true ||.
‘min-max’ : normalize by the intensity range of im_true. ‘mean’ : normalize by the mean of im_true
Returns
nrmsefloat
The NRMSE metric. Notes Changed in version 0.16: This function was renamed from skimage.measure.compare_nrmse to skimage.metrics.normalized_root_mse. References
1
https://en.wikipedia.org/wiki/Root-mean-square_deviation
peak_signal_noise_ratio
skimage.metrics.peak_signal_noise_ratio(image_true, image_test, *, data_range=None) [source]
Compute the peak signal to noise ratio (PSNR) for an image. Parameters
image_truendarray
Ground-truth image, same shape as im_test.
image_testndarray
Test image.
data_rangeint, optional
The data range of the input image (distance between minimum and maximum possible values). By default, this is estimated from the image data-type. Returns
psnrfloat
The PSNR metric. Notes Changed in version 0.16: This function was renamed from skimage.measure.compare_psnr to skimage.metrics.peak_signal_noise_ratio. References
1
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
structural_similarity
skimage.metrics.structural_similarity(im1, im2, *, win_size=None, gradient=False, data_range=None, multichannel=False, gaussian_weights=False, full=False, **kwargs) [source]
Compute the mean structural similarity index between two images. Parameters
im1, im2ndarray
Images. Any dimensionality with same shape.
win_sizeint or None, optional
The side-length of the sliding window used in comparison. Must be an odd value. If gaussian_weights is True, this is ignored and the window size will depend on sigma.
gradientbool, optional
If True, also return the gradient with respect to im2.
data_rangefloat, optional
The data range of the input image (distance between minimum and maximum possible values). By default, this is estimated from the image data-type.
multichannelbool, optional
If True, treat the last dimension of the array as channels. Similarity calculations are done independently for each channel then averaged.
gaussian_weightsbool, optional
If True, each patch has its mean and variance spatially weighted by a normalized Gaussian kernel of width sigma=1.5.
fullbool, optional
If True, also return the full structural similarity image. Returns
mssimfloat
The mean structural similarity index over the image.
gradndarray
The gradient of the structural similarity between im1 and im2 [2]. This is only returned if gradient is set to True.
Sndarray
The full SSIM image. This is only returned if full is set to True. Other Parameters
use_sample_covariancebool
If True, normalize covariances by N-1 rather than, N where N is the number of pixels within the sliding window.
K1float
Algorithm parameter, K1 (small constant, see [1]).
K2float
Algorithm parameter, K2 (small constant, see [1]).
sigmafloat
Standard deviation for the Gaussian when gaussian_weights is True. Notes To match the implementation of Wang et. al. [1], set gaussian_weights to True, sigma to 1.5, and use_sample_covariance to False. Changed in version 0.16: This function was renamed from skimage.measure.compare_ssim to skimage.metrics.structural_similarity. References
1(1,2,3)
Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004). Image quality assessment: From error visibility to structural similarity. IEEE Transactions on Image Processing, 13, 600-612. https://ece.uwaterloo.ca/~z70wang/publications/ssim.pdf, DOI:10.1109/TIP.2003.819861
2
Avanaki, A. N. (2009). Exact global histogram specification optimized for structural similarity. Optical Review, 16, 613-621. arXiv:0901.0065 DOI:10.1007/s10043-009-0119-z
variation_of_information
skimage.metrics.variation_of_information(image0=None, image1=None, *, table=None, ignore_labels=()) [source]
Return symmetric conditional entropies associated with the VI. [1] The variation of information is defined as VI(X,Y) = H(X|Y) + H(Y|X). If X is the ground-truth segmentation, then H(X|Y) can be interpreted as the amount of under-segmentation and H(X|Y) as the amount of over-segmentation. In other words, a perfect over-segmentation will have H(X|Y)=0 and a perfect under-segmentation will have H(Y|X)=0. Parameters
image0, image1ndarray of int
Label images / segmentations, must have same shape.
tablescipy.sparse array in csr format, optional
A contingency table built with skimage.evaluate.contingency_table. If None, it will be computed with skimage.evaluate.contingency_table. If given, the entropies will be computed from this table and any images will be ignored.
ignore_labelssequence of int, optional
Labels to ignore. Any part of the true image labeled with any of these values will not be counted in the score. Returns
vindarray of float, shape (2,)
The conditional entropies of image1|image0 and image0|image1. References
1
Marina Meilă (2007), Comparing clusterings—an information based distance, Journal of Multivariate Analysis, Volume 98, Issue 5, Pages 873-895, ISSN 0047-259X, DOI:10.1016/j.jmva.2006.11.013. | |
doc_27025 | ArrayLike: objects that can be converted to arrays
DTypeLike: objects that can be converted to dtypes Mypy plugin New in version 1.21. A mypy plugin for managing a number of platform-specific annotations. Its functionality can be split into three distinct parts: Assigning the (platform-dependent) precisions of certain number subclasses, including the likes of int_, intp and longlong. See the documentation on scalar types for a comprehensive overview of the affected classes. Without the plugin the precision of all relevant classes will be inferred as Any. Removing all extended-precision number subclasses that are unavailable for the platform in question. Most notably this includes the likes of float128 and complex256. Without the plugin all extended-precision types will, as far as mypy is concerned, be available to all platforms.
Assigning the (platform-dependent) precision of c_intp. Without the plugin the type will default to ctypes.c_int64. New in version 1.22. Examples To enable the plugin, one must add it to their mypy configuration file: [mypy]
plugins = numpy.typing.mypy_plugin
Differences from the runtime NumPy API NumPy is very flexible. Trying to describe the full range of possibilities statically would result in types that are not very helpful. For that reason, the typed NumPy API is often stricter than the runtime NumPy API. This section describes some notable differences. ArrayLike The ArrayLike type tries to avoid creating object arrays. For example, >>> np.array(x**2 for x in range(10))
array(<generator object <genexpr> at ...>, dtype=object)
is valid NumPy code which will create a 0-dimensional object array. Type checkers will complain about the above example when using the NumPy types however. If you really intended to do the above, then you can either use a # type: ignore comment: >>> np.array(x**2 for x in range(10)) # type: ignore
or explicitly type the array like object as Any: >>> from typing import Any
>>> array_like: Any = (x**2 for x in range(10))
>>> np.array(array_like)
array(<generator object <genexpr> at ...>, dtype=object)
ndarray It’s possible to mutate the dtype of an array at runtime. For example, the following code is valid: >>> x = np.array([1, 2])
>>> x.dtype = np.bool_
This sort of mutation is not allowed by the types. Users who want to write statically typed code should instead use the numpy.ndarray.view method to create a view of the array with a different dtype. DTypeLike The DTypeLike type tries to avoid creation of dtype objects using dictionary of fields like below: >>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)})
Although this is valid NumPy code, the type checker will complain about it, since its usage is discouraged. Please see : Data type objects Number precision The precision of numpy.number subclasses is treated as a covariant generic parameter (see NBitBase), simplifying the annotating of processes involving precision-based casting. >>> from typing import TypeVar
>>> import numpy as np
>>> import numpy.typing as npt
>>> T = TypeVar("T", bound=npt.NBitBase)
>>> def func(a: "np.floating[T]", b: "np.floating[T]") -> "np.floating[T]":
... ...
Consequently, the likes of float16, float32 and float64 are still sub-types of floating, but, contrary to runtime, they’re not necessarily considered as sub-classes. Timedelta64 The timedelta64 class is not considered a subclass of signedinteger, the former only inheriting from generic while static type checking. 0D arrays During runtime numpy aggressively casts any passed 0D arrays into their corresponding generic instance. Until the introduction of shape typing (see PEP 646) it is unfortunately not possible to make the necessary distinction between 0D and >0D arrays. While thus not strictly correct, all operations are that can potentially perform a 0D-array -> scalar cast are currently annotated as exclusively returning an ndarray. If it is known in advance that an operation _will_ perform a 0D-array -> scalar cast, then one can consider manually remedying the situation with either typing.cast or a # type: ignore comment. Record array dtypes The dtype of numpy.recarray, and the numpy.rec functions in general, can be specified in one of two ways: Directly via the dtype argument. With up to five helper arguments that operate via numpy.format_parser: formats, names, titles, aligned and byteorder. These two approaches are currently typed as being mutually exclusive, i.e. if dtype is specified than one may not specify formats. While this mutual exclusivity is not (strictly) enforced during runtime, combining both dtype specifiers can lead to unexpected or even downright buggy behavior. API numpy.typing.ArrayLike = typing.Union[...]
A Union representing objects that can be coerced into an ndarray. Among others this includes the likes of: Scalars. (Nested) sequences. Objects implementing the __array__ protocol. New in version 1.20. See Also
array_like:
Any scalar or sequence that can be interpreted as an ndarray. Examples >>> import numpy as np
>>> import numpy.typing as npt
>>> def as_array(a: npt.ArrayLike) -> np.ndarray:
... return np.array(a)
numpy.typing.DTypeLike = typing.Union[...]
A Union representing objects that can be coerced into a dtype. Among others this includes the likes of:
type objects. Character codes or the names of type objects. Objects with the .dtype attribute. New in version 1.20. See Also Specifying and constructing data types
A comprehensive overview of all objects that can be coerced into data types. Examples >>> import numpy as np
>>> import numpy.typing as npt
>>> def as_dtype(d: npt.DTypeLike) -> np.dtype:
... return np.dtype(d)
numpy.typing.NDArray = numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]][source]
A generic version of np.ndarray[Any, np.dtype[+ScalarType]]. Can be used during runtime for typing arrays with a given dtype and unspecified shape. New in version 1.21. Examples >>> import numpy as np
>>> import numpy.typing as npt
>>> print(npt.NDArray)
numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]
>>> print(npt.NDArray[np.float64])
numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
>>> NDArrayInt = npt.NDArray[np.int_]
>>> a: NDArrayInt = np.arange(10)
>>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
... return np.array(a)
final class numpy.typing.NBitBase[source]
A type representing numpy.number precision during static type checking. Used exclusively for the purpose static type checking, NBitBase represents the base of a hierarchical set of subclasses. Each subsequent subclass is herein used for representing a lower level of precision, e.g. 64Bit > 32Bit > 16Bit. New in version 1.20. Examples Below is a typical usage example: NBitBase is herein used for annotating a function that takes a float and integer of arbitrary precision as arguments and returns a new float of whichever precision is largest (e.g. np.float16 + np.int64 -> np.float64). >>> from __future__ import annotations
>>> from typing import TypeVar, TYPE_CHECKING
>>> import numpy as np
>>> import numpy.typing as npt
>>> T1 = TypeVar("T1", bound=npt.NBitBase)
>>> T2 = TypeVar("T2", bound=npt.NBitBase)
>>> def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[T1 | T2]:
... return a + b
>>> a = np.float16()
>>> b = np.int64()
>>> out = add(a, b)
>>> if TYPE_CHECKING:
... reveal_locals()
... # note: Revealed local types are:
... # note: a: numpy.floating[numpy.typing._16Bit*]
... # note: b: numpy.signedinteger[numpy.typing._64Bit*]
... # note: out: numpy.floating[numpy.typing._64Bit*] | |
doc_27026 | Validates whether the password is not entirely numeric. | |
doc_27027 | Return True if there is a Content-Disposition header and its (case insensitive) value is attachment, False otherwise. Changed in version 3.4.2: is_attachment is now a method instead of a property, for consistency with is_multipart(). | |
doc_27028 |
Extension array for string data in a pyarrow.ChunkedArray. New in version 1.2.0. Warning ArrowStringArray is considered experimental. The implementation and parts of the API may change without warning. Parameters
values:pyarrow.Array or pyarrow.ChunkedArray
The array of data. See also array
The recommended function for creating a ArrowStringArray. Series.str
The string methods are available on Series backed by a ArrowStringArray. Notes ArrowStringArray returns a BooleanArray for comparison methods. Examples
>>> pd.array(['This is', 'some text', None, 'data.'], dtype="string[pyarrow]")
<ArrowStringArray>
['This is', 'some text', <NA>, 'data.']
Length: 4, dtype: string
Attributes
None Methods
None | |
doc_27029 |
Sparse coding Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array code such that: X ~= code * dictionary
Read more in the User Guide. Parameters
Xndarray of shape (n_samples, n_features)
Data matrix.
dictionaryndarray of shape (n_components, n_features)
The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows for meaningful output.
gramndarray of shape (n_components, n_components), default=None
Precomputed Gram matrix, dictionary * dictionary'.
covndarray of shape (n_components, n_samples), default=None
Precomputed covariance, dictionary' * X.
algorithm{‘lasso_lars’, ‘lasso_cd’, ‘lars’, ‘omp’, ‘threshold’}, default=’lasso_lars’
The algorithm used:
'lars': uses the least angle regression method (linear_model.lars_path);
'lasso_lars': uses Lars to compute the Lasso solution;
'lasso_cd': uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse;
'omp': uses orthogonal matching pursuit to estimate the sparse solution;
'threshold': squashes to zero all coefficients less than regularization from the projection dictionary * data'.
n_nonzero_coefsint, default=None
Number of nonzero coefficients to target in each column of the solution. This is only used by algorithm='lars' and algorithm='omp' and is overridden by alpha in the omp case. If None, then n_nonzero_coefs=int(n_features / 10).
alphafloat, default=None
If algorithm='lasso_lars' or algorithm='lasso_cd', alpha is the penalty applied to the L1 norm. If algorithm='threshold', alpha is the absolute value of the threshold below which coefficients will be squashed to zero. If algorithm='omp', alpha is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides n_nonzero_coefs. If None, default to 1.
copy_covbool, default=True
Whether to copy the precomputed covariance matrix; if False, it may be overwritten.
initndarray of shape (n_samples, n_components), default=None
Initialization value of the sparse codes. Only used if algorithm='lasso_cd'.
max_iterint, default=1000
Maximum number of iterations to perform if algorithm='lasso_cd' or 'lasso_lars'.
n_jobsint, default=None
Number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
check_inputbool, default=True
If False, the input arrays X and dictionary will not be checked.
verboseint, default=0
Controls the verbosity; the higher, the more messages.
positivebool, default=False
Whether to enforce positivity when finding the encoding. New in version 0.20. Returns
codendarray of shape (n_samples, n_components)
The sparse codes See also
sklearn.linear_model.lars_path
sklearn.linear_model.orthogonal_mp
sklearn.linear_model.Lasso
SparseCoder | |
doc_27030 |
Dot-Product kernel. The DotProduct kernel is non-stationary and can be obtained from linear regression by putting \(N(0, 1)\) priors on the coefficients of \(x_d (d = 1, . . . , D)\) and a prior of \(N(0, \sigma_0^2)\) on the bias. The DotProduct kernel is invariant to a rotation of the coordinates about the origin, but not translations. It is parameterized by a parameter sigma_0 \(\sigma\) which controls the inhomogenity of the kernel. For \(\sigma_0^2 =0\), the kernel is called the homogeneous linear kernel, otherwise it is inhomogeneous. The kernel is given by \[k(x_i, x_j) = \sigma_0 ^ 2 + x_i \cdot x_j\] The DotProduct kernel is commonly combined with exponentiation. See [1], Chapter 4, Section 4.2, for further details regarding the DotProduct kernel. Read more in the User Guide. New in version 0.18. Parameters
sigma_0float >= 0, default=1.0
Parameter controlling the inhomogenity of the kernel. If sigma_0=0, the kernel is homogenous.
sigma_0_boundspair of floats >= 0 or “fixed”, default=(1e-5, 1e5)
The lower and upper bound on ‘sigma_0’. If set to “fixed”, ‘sigma_0’ cannot be changed during hyperparameter tuning. Attributes
bounds
Returns the log-transformed bounds on the theta. hyperparameter_sigma_0
hyperparameters
Returns a list of all hyperparameter specifications.
n_dims
Returns the number of non-fixed hyperparameters of the kernel.
requires_vector_input
Returns whether the kernel is defined on fixed-length feature vectors or generic objects.
theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. References
1
Carl Edward Rasmussen, Christopher K. I. Williams (2006). “Gaussian Processes for Machine Learning”. The MIT Press. Examples >>> from sklearn.datasets import make_friedman2
>>> from sklearn.gaussian_process import GaussianProcessRegressor
>>> from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
>>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0)
>>> kernel = DotProduct() + WhiteKernel()
>>> gpr = GaussianProcessRegressor(kernel=kernel,
... random_state=0).fit(X, y)
>>> gpr.score(X, y)
0.3680...
>>> gpr.predict(X[:2,:], return_std=True)
(array([653.0..., 592.1...]), array([316.6..., 316.6...]))
Methods
__call__(X[, Y, eval_gradient]) Return the kernel k(X, Y) and optionally its gradient.
clone_with_theta(theta) Returns a clone of self with given hyperparameters theta.
diag(X) Returns the diagonal of the kernel k(X, X).
get_params([deep]) Get parameters of this kernel.
is_stationary() Returns whether the kernel is stationary.
set_params(**params) Set the parameters of this kernel.
__call__(X, Y=None, eval_gradient=False) [source]
Return the kernel k(X, Y) and optionally its gradient. Parameters
Xndarray of shape (n_samples_X, n_features)
Left argument of the returned kernel k(X, Y)
Yndarray of shape (n_samples_Y, n_features), default=None
Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead.
eval_gradientbool, default=False
Determines whether the gradient with respect to the log of the kernel hyperparameter is computed. Only supported when Y is None. Returns
Kndarray of shape (n_samples_X, n_samples_Y)
Kernel k(X, Y)
K_gradientndarray of shape (n_samples_X, n_samples_X, n_dims), optional
The gradient of the kernel k(X, X) with respect to the log of the hyperparameter of the kernel. Only returned when eval_gradient is True.
property bounds
Returns the log-transformed bounds on the theta. Returns
boundsndarray of shape (n_dims, 2)
The log-transformed bounds on the kernel’s hyperparameters theta
clone_with_theta(theta) [source]
Returns a clone of self with given hyperparameters theta. Parameters
thetandarray of shape (n_dims,)
The hyperparameters
diag(X) [source]
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters
Xndarray of shape (n_samples_X, n_features)
Left argument of the returned kernel k(X, Y). Returns
K_diagndarray of shape (n_samples_X,)
Diagonal of kernel k(X, X).
get_params(deep=True) [source]
Get parameters of this kernel. 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.
property hyperparameters
Returns a list of all hyperparameter specifications.
is_stationary() [source]
Returns whether the kernel is stationary.
property n_dims
Returns the number of non-fixed hyperparameters of the kernel.
property requires_vector_input
Returns whether the kernel is defined on fixed-length feature vectors or generic objects. Defaults to True for backward compatibility.
set_params(**params) [source]
Set the parameters of this kernel. The method works on simple kernels as well as on nested kernels. The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Returns
self
property theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel’s hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns
thetandarray of shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel | |
doc_27031 |
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event. | |
doc_27032 |
Checkerboard image. Checkerboards are often used in image calibration, since the corner-points are easy to locate. Because of the many parallel edges, they also visualise distortions particularly well. Returns
checkerboard(200, 200) uint8 ndarray
Checkerboard image. | |
doc_27033 |
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | |
doc_27034 | See Migration guide for more details. tf.compat.v1.raw_ops.SparseCrossHashed
tf.raw_ops.SparseCrossHashed(
indices, values, shapes, dense_inputs, num_buckets, strong_hash, salt, name=None
)
The op takes two lists, one of 2D SparseTensor and one of 2D Tensor, each representing features of one feature column. It outputs a 2D SparseTensor with the batchwise crosses of these features. For example, if the inputs are inputs[0]: SparseTensor with shape = [2, 2]
[0, 0]: "a"
[1, 0]: "b"
[1, 1]: "c"
inputs[1]: SparseTensor with shape = [2, 1]
[0, 0]: "d"
[1, 0]: "e"
inputs[2]: Tensor [["f"], ["g"]]
then the output will be shape = [2, 2]
[0, 0]: "a_X_d_X_f"
[1, 0]: "b_X_e_X_g"
[1, 1]: "c_X_e_X_g"
if hashed_output=true then the output will be shape = [2, 2]
[0, 0]: FingerprintCat64(
Fingerprint64("f"), FingerprintCat64(
Fingerprint64("d"), Fingerprint64("a")))
[1, 0]: FingerprintCat64(
Fingerprint64("g"), FingerprintCat64(
Fingerprint64("e"), Fingerprint64("b")))
[1, 1]: FingerprintCat64(
Fingerprint64("g"), FingerprintCat64(
Fingerprint64("e"), Fingerprint64("c")))
Args
indices A list of Tensor objects with type int64. 2-D. Indices of each input SparseTensor.
values A list of Tensor objects with types from: int64, string. 1-D. values of each SparseTensor.
shapes A list with the same length as indices of Tensor objects with type int64. 1-D. Shapes of each SparseTensor.
dense_inputs A list of Tensor objects with types from: int64, string. 2-D. Columns represented by dense Tensor.
num_buckets A Tensor of type int64. It is used if hashed_output is true. output = hashed_value%num_buckets if num_buckets > 0 else hashed_value.
strong_hash A Tensor of type bool. boolean, if true, siphash with salt will be used instead of farmhash.
salt A Tensor of type int64. Specify the salt that will be used by the siphash function.
name A name for the operation (optional).
Returns A tuple of Tensor objects (output_indices, output_values, output_shape). output_indices A Tensor of type int64.
output_values A Tensor of type int64.
output_shape A Tensor of type int64. | |
doc_27035 | codeop.compile_command(source, filename="<input>", symbol="single")
Tries to compile source, which should be a string of Python code and return a code object if source is valid Python code. In that case, the filename attribute of the code object will be filename, which defaults to '<input>'. Returns None if source is not valid Python code, but is a prefix of valid Python code. If there is a problem with source, an exception will be raised. SyntaxError is raised if there is invalid Python syntax, and OverflowError or ValueError if there is an invalid literal. The symbol argument determines whether source is compiled as a statement ('single', the default), as a sequence of statements ('exec') or as an expression ('eval'). Any other value will cause ValueError to be raised. Note It is possible (but not likely) that the parser stops parsing with a successful outcome before reaching the end of the source; in this case, trailing symbols may be ignored instead of causing an error. For example, a backslash followed by two newlines may be followed by arbitrary garbage. This will be fixed once the API for the parser is better.
class codeop.Compile
Instances of this class have __call__() methods identical in signature to the built-in function compile(), but with the difference that if the instance compiles program text containing a __future__ statement, the instance ‘remembers’ and compiles all subsequent program texts with the statement in force.
class codeop.CommandCompiler
Instances of this class have __call__() methods identical in signature to compile_command(); the difference is that if the instance compiles program text containing a __future__ statement, the instance ‘remembers’ and compiles all subsequent program texts with the statement in force. | |
doc_27036 | See Migration guide for more details. tf.compat.v1.raw_ops.ExperimentalAutoShardDataset
tf.raw_ops.ExperimentalAutoShardDataset(
input_dataset, num_workers, index, output_types, output_shapes,
auto_shard_policy=0, name=None
)
Creates a dataset that shards the input dataset by num_workers, returning a sharded dataset for the index-th worker. This attempts to automatically shard a dataset by examining the Dataset graph and inserting a shard op before the inputs to a reader Dataset (e.g. CSVDataset, TFRecordDataset). This dataset will throw a NotFound error if we cannot shard the dataset automatically.
Args
input_dataset A Tensor of type variant. A variant tensor representing the input dataset.
num_workers A Tensor of type int64. A scalar representing the number of workers to distribute this dataset across.
index A Tensor of type int64. A scalar representing the index of the current worker out of num_workers.
output_types A list of tf.DTypes that has length >= 1.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1.
auto_shard_policy An optional int. Defaults to 0.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_27037 |
Return the corresponding inverse transformation. It holds x == self.inverted().transform(self.transform(x)). The return value of this method should be treated as temporary. An update to self does not cause a corresponding update to its inverted copy. | |
doc_27038 | Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries. This method will be used by default to compare dictionaries in calls to assertEqual(). New in version 3.1. | |
doc_27039 |
Greek coins from Pompeii. This image shows several coins outlined against a gray background. It is especially useful in, e.g. segmentation tests, where individual objects need to be identified against a background. The background shares enough grey levels with the coins that a simple segmentation is not sufficient. Returns
coins(303, 384) uint8 ndarray
Coins image. Notes This image was downloaded from the Brooklyn Museum Collection. No known copyright restrictions. | |
doc_27040 | Set the key, value and coded_value attributes. | |
doc_27041 | See Migration guide for more details. tf.compat.v1.image.random_saturation
tf.image.random_saturation(
image, lower, upper, seed=None
)
Equivalent to adjust_saturation() but uses a saturation_factor randomly picked in the interval [lower, upper). Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.random_saturation(x, 5, 10)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 0. , 1.5, 3. ],
[ 0. , 3. , 6. ]],
[[ 0. , 4.5, 9. ],
[ 0. , 6. , 12. ]]], dtype=float32)>
Args
image RGB image or images. The size of the last dimension must be 3.
lower float. Lower bound for the random saturation factor.
upper float. Upper bound for the random saturation factor.
seed An operation-specific seed. It will be used in conjunction with the graph-level seed to determine the real seeds that will be used in this operation. Please see the documentation of set_random_seed for its interaction with the graph-level random seed.
Returns Adjusted image(s), same shape and DType as image.
Raises
ValueError if upper <= lower or if lower < 0. | |
doc_27042 | New in Django 4.0. The name of the template used when calling as_ul(). By default this is 'django/forms/formsets/ul.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_ul() method. | |
doc_27043 | Return a representation of the message corresponding to key as an instance of the appropriate format-specific Message subclass, or raise a KeyError exception if no such message exists. | |
doc_27044 | turtle.onscreenclick(fun, btn=1, add=None)
Parameters
fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas
btn – number of the mouse-button, defaults to 1 (left mouse button)
add – True or False – if True, a new binding will be added, otherwise it will replace a former binding Bind fun to mouse-click events on this screen. If fun is None, existing bindings are removed. Example for a TurtleScreen instance named screen and a Turtle instance named turtle: >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>> # make the turtle move to the clicked point.
>>> screen.onclick(None) # remove event binding again
Note This TurtleScreen method is available as a global function only under the name onscreenclick. The global function onclick is another one derived from the Turtle method onclick. | |
doc_27045 | get the playback volume get_volume() -> value Return a value from 0.0 to 1.0 representing the volume for this Sound. | |
doc_27046 |
Set the parameters Parameters
Xarray-like, shape (n_samples, n_features)
Training data, where n_samples in the number of samples and n_features is the number of features. Returns
selfobject
Returns the transformer. | |
doc_27047 | Get the given distance metric from the string identifier. See the docstring of DistanceMetric for a list of available metrics. Parameters
metricstring or class name
The distance metric to use **kwargs
additional arguments will be passed to the requested metric | |
doc_27048 |
Set the Figure instance the artist belongs to. Parameters
figFigure | |
doc_27049 |
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable | |
doc_27050 | tf.compat.v1.add_to_collection(
name, value
)
See tf.Graph.add_to_collection for more details.
Args
name The key for the collection. For example, the GraphKeys class contains many standard names for collections.
value The value to add to the collection. Eager Compatibility Collections are only supported in eager when variables are created inside an EagerVariableStore (e.g. as part of a layer or template). | |
doc_27051 | Exit code that means a specified host did not exist. Availability: Unix. | |
doc_27052 | """
May be applied as a `default=...` value on a serializer field.
Returns the current user.
"""
requires_context = True
def __call__(self, serializer_field):
return serializer_field.context['request'].user
When serializing the instance, default will be used if the object attribute or dictionary key is not present in the instance. Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error. allow_null Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. Note that, without an explicit default, setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization. Defaults to False source The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email'). When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal. The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. Defaults to the name of the field. validators A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError, but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages. error_messages A dictionary of error codes to error messages. label A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. help_text A text string that may be used as a description of the field in HTML form fields or other descriptive elements. initial A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as you may do with any regular Django Field: import datetime
from rest_framework import serializers
class ExampleSerializer(serializers.Serializer):
day = serializers.DateField(initial=datetime.date.today)
style A dictionary of key-value pairs that can be used to control how renderers should render the field. Two examples here are 'input_type' and 'base_template': # Use <input type="password"> for the input.
password = serializers.CharField(
style={'input_type': 'password'}
)
# Use a radio input instead of a select input.
color_channel = serializers.ChoiceField(
choices=['red', 'green', 'blue'],
style={'base_template': 'radio.html'}
)
For more details see the HTML & Forms documentation. Boolean fields BooleanField A boolean representation. When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to False, even if it has a default=True option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input. Note that Django 2.1 removed the blank kwarg from models.BooleanField. Prior to Django 2.1 models.BooleanField fields were always blank=True. Thus since Django 2.1 default serializers.BooleanField instances will be generated without the required kwarg (i.e. equivalent to required=True) whereas with previous versions of Django, default BooleanField instances will be generated with a required=False option. If you want to control this behaviour manually, explicitly declare the BooleanField on the serializer class, or use the extra_kwargs option to set the required flag. Corresponds to django.db.models.fields.BooleanField. Signature: BooleanField() NullBooleanField A boolean representation that also accepts None as a valid value. Corresponds to django.db.models.fields.NullBooleanField. Signature: NullBooleanField() String fields CharField A text representation. Optionally validates the text to be shorter than max_length and longer than min_length. Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField. Signature: CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
max_length - Validates that the input contains no more than this number of characters.
min_length - Validates that the input contains no fewer than this number of characters.
allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
trim_whitespace - If set to True then leading and trailing whitespace is trimmed. Defaults to True. The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank. It is valid to set both allow_blank=True and allow_null=True, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. EmailField A text representation, validates the text to be a valid e-mail address. Corresponds to django.db.models.fields.EmailField Signature: EmailField(max_length=None, min_length=None, allow_blank=False) RegexField A text representation, that validates the given value matches against a certain regular expression. Corresponds to django.forms.fields.RegexField. Signature: RegexField(regex, max_length=None, min_length=None, allow_blank=False) The mandatory regex argument may either be a string, or a compiled python regular expression object. Uses Django's django.core.validators.RegexValidator for validation. SlugField A RegexField that validates the input against the pattern [a-zA-Z0-9_-]+. Corresponds to django.db.models.fields.SlugField. Signature: SlugField(max_length=50, min_length=None, allow_blank=False) URLField A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http://<host>/<path>. Corresponds to django.db.models.fields.URLField. Uses Django's django.core.validators.URLValidator for validation. Signature: URLField(max_length=200, min_length=None, allow_blank=False) UUIDField A field that ensures the input is a valid UUID string. The to_internal_value method will return a uuid.UUID instance. On output the field will return a string in the canonical hyphenated format, for example: "de305d54-75b4-431b-adb2-eb6b9e546013"
Signature: UUIDField(format='hex_verbose')
format: Determines the representation format of the uuid value
'hex_verbose' - The canonical hex representation, including hyphens: "5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
'hex' - The compact hex representation of the UUID, not including hyphens: "5ce0e9a55ffa654bcee01238041fb31a"
'int' - A 128 bit integer representation of the UUID: "123456789012312313134124512351145145114"
'urn' - RFC 4122 URN representation of the UUID: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" Changing the format parameters only affects representation values. All formats are accepted by to_internal_value
FilePathField A field whose choices are limited to the filenames in a certain directory on the filesystem Corresponds to django.forms.fields.FilePathField. Signature: FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)
path - The absolute filesystem path to a directory from which this FilePathField should get its choice.
match - A regular expression, as a string, that FilePathField will use to filter filenames.
recursive - Specifies whether all subdirectories of path should be included. Default is False.
allow_files - Specifies whether files in the specified location should be included. Default is True. Either this or allow_folders must be True.
allow_folders - Specifies whether folders in the specified location should be included. Default is False. Either this or allow_files must be True. IPAddressField A field that ensures the input is a valid IPv4 or IPv6 string. Corresponds to django.forms.fields.IPAddressField and django.forms.fields.GenericIPAddressField. Signature: IPAddressField(protocol='both', unpack_ipv4=False, **options)
protocol Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
unpack_ipv4 Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. Numeric fields IntegerField An integer representation. Corresponds to django.db.models.fields.IntegerField, django.db.models.fields.SmallIntegerField, django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField. Signature: IntegerField(max_value=None, min_value=None)
max_value Validate that the number provided is no greater than this value.
min_value Validate that the number provided is no less than this value. FloatField A floating point representation. Corresponds to django.db.models.fields.FloatField. Signature: FloatField(max_value=None, min_value=None)
max_value Validate that the number provided is no greater than this value.
min_value Validate that the number provided is no less than this value. DecimalField A decimal representation, represented in Python by a Decimal instance. Corresponds to django.db.models.fields.DecimalField. Signature: DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)
max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places.
decimal_places The number of decimal places to store with the number.
coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting localize will force the value to True.
max_value Validate that the number provided is no greater than this value.
min_value Validate that the number provided is no less than this value.
localize Set to True to enable localization of input and output based on the current locale. This will also force coerce_to_string to True. Defaults to False. Note that data formatting is enabled if you have set USE_L10N=True in your settings file.
rounding Sets the rounding mode used when quantising to the configured precision. Valid values are decimal module rounding modes. Defaults to None. Example usage To validate numbers up to 999 with a resolution of 2 decimal places, you would use: serializers.DecimalField(max_digits=5, decimal_places=2)
And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10)
This field also takes an optional argument, coerce_to_string. If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer. If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise. Date and time fields DateTimeField A date and time representation. Corresponds to django.db.models.fields.DateTimeField. Signature: DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None)
format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer.
input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
default_timezone - A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive. DateTimeField format strings. Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z') When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class. auto_now and auto_now_add model fields. When using ModelSerializer or HyperlinkedModelSerializer, note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default. If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example: class CommentSerializer(serializers.ModelSerializer):
created = serializers.DateTimeField()
class Meta:
model = Comment
DateField A date representation. Corresponds to django.db.models.fields.DateField Signature: DateField(format=api_settings.DATE_FORMAT, input_formats=None)
format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer.
input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601']. DateField format strings Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style dates should be used. (eg '2013-01-29') TimeField A time representation. Corresponds to django.db.models.fields.TimeField Signature: TimeField(format=api_settings.TIME_FORMAT, input_formats=None)
format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer.
input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601']. TimeField format strings Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000') DurationField A Duration representation. Corresponds to django.db.models.fields.DurationField The validated_data for these fields will contain a datetime.timedelta instance. The representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]'. Signature: DurationField(max_value=None, min_value=None)
max_value Validate that the duration provided is no greater than this value.
min_value Validate that the duration provided is no less than this value. Choice selection fields ChoiceField A field that can accept a value out of a limited set of choices. Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=… argument. Signature: ChoiceField(choices)
choices - A list of valid values, or a list of (key, display_name) tuples.
allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"
Both the allow_blank and allow_null are valid options on ChoiceField, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices. MultipleChoiceField A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_value returns a set containing the selected values. Signature: MultipleChoiceField(choices)
choices - A list of valid values, or a list of (key, display_name) tuples.
allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"
As with ChoiceField, both the allow_blank and allow_null options are valid, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices. File upload fields Parsers and file uploads. The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser. Most parsers, such as e.g. JSON don't support file uploads. Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files. FileField A file representation. Performs Django's standard FileField validation. Corresponds to django.forms.fields.FileField. Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
max_length - Designates the maximum length for the file name.
allow_empty_file - Designates if empty files are allowed.
use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. ImageField An image representation. Validates the uploaded file content as matching a known image format. Corresponds to django.forms.fields.ImageField. Signature: ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
max_length - Designates the maximum length for the file name.
allow_empty_file - Designates if empty files are allowed.
use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. Requires either the Pillow package or PIL package. The Pillow package is recommended, as PIL is no longer actively maintained. Composite fields ListField A field class that validates a list of objects. Signature: ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)
child - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
allow_empty - Designates if empty lists are allowed.
min_length - Validates that the list contains no fewer than this number of elements.
max_length - Validates that the list contains no more than this number of elements. For example, to validate a list of integers you might use something like the following: scores = serializers.ListField(
child=serializers.IntegerField(min_value=0, max_value=100)
)
The ListField class also supports a declarative style that allows you to write reusable list field classes. class StringListField(serializers.ListField):
child = serializers.CharField()
We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it. DictField A field class that validates a dictionary of objects. The keys in DictField are always assumed to be string values. Signature: DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)
child - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
allow_empty - Designates if empty dictionaries are allowed. For example, to create a field that validates a mapping of strings to strings, you would write something like this: document = DictField(child=CharField())
You can also use the declarative style, as with ListField. For example: class DocumentField(DictField):
child = CharField()
HStoreField A preconfigured DictField that is compatible with Django's postgres HStoreField. Signature: HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)
child - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
allow_empty - Designates if empty dictionaries are allowed. Note that the child field must be an instance of CharField, as the hstore extension stores values as strings. JSONField A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. Signature: JSONField(binary, encoder)
binary - If set to True then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to False.
encoder - Use this JSON encoder to serialize input object. Defaults to None. Miscellaneous fields ReadOnlyField A field class that simply returns the value of the field without modification. This field is used by default with ModelSerializer when including field names that relate to an attribute rather than a model field. Signature: ReadOnlyField() For example, if has_expired was a property on the Account model, then the following serializer would automatically generate it as a ReadOnlyField: class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'has_expired']
HiddenField A field class that does not take a value based on user input, but instead takes its value from a default value or callable. Signature: HiddenField() For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following: modified = serializers.HiddenField(default=timezone.now)
The HiddenField class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user. For further examples on HiddenField see the validators documentation. ModelField A generic field that can be tied to any arbitrary model field. The ModelField class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. This field is used by ModelSerializer to correspond to custom model field classes. Signature: ModelField(model_field=<Django ModelField instance>) The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField, it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field')) SerializerMethodField This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Signature: SerializerMethodField(method_name=None)
method_name - The name of the method on the serializer to be called. If not included this defaults to get_<field_name>. The serializer method referred to by the method_name argument should accept a single argument (in addition to self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
days_since_joined = serializers.SerializerMethodField()
class Meta:
model = User
fields = '__all__'
def get_days_since_joined(self, obj):
return (now() - obj.date_joined).days
Custom fields If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using. The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype. The .to_internal_value() method is called to restore a primitive datatype into its internal python representation. This method should raise a serializers.ValidationError if the data is invalid. Examples A Basic Custom Field Let's look at an example of serializing a class that represents an RGB color value: class Color:
"""
A color represented in the RGB colorspace.
"""
def __init__(self, red, green, blue):
assert(red >= 0 and green >= 0 and blue >= 0)
assert(red < 256 and green < 256 and blue < 256)
self.red, self.green, self.blue = red, green, blue
class ColorField(serializers.Field):
"""
Color objects are serialized into 'rgb(#, #, #)' notation.
"""
def to_representation(self, value):
return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue)
def to_internal_value(self, data):
data = data.strip('rgb(').rstrip(')')
red, green, blue = [int(col) for col in data.split(',')]
return Color(red, green, blue)
By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .get_attribute() and/or .get_value(). As an example, let's create a field that can be used to represent the class name of the object being serialized: class ClassNameField(serializers.Field):
def get_attribute(self, instance):
# We pass the object instance onto `to_representation`,
# not just the field attribute.
return instance
def to_representation(self, value):
"""
Serialize the value's class name.
"""
return value.__class__.__name__
Raising validation errors Our ColorField class above currently does not perform any data validation. To indicate invalid data, we should raise a serializers.ValidationError, like so: def to_internal_value(self, data):
if not isinstance(data, str):
msg = 'Incorrect type. Expected a string, but got %s'
raise ValidationError(msg % type(data).__name__)
if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')
data = data.strip('rgb(').rstrip(')')
red, green, blue = [int(col) for col in data.split(',')]
if any([col > 255 or col < 0 for col in (red, green, blue)]):
raise ValidationError('Value out of range. Must be between 0 and 255.')
return Color(red, green, blue)
The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example: default_error_messages = {
'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',
'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',
'out_of_range': 'Value out of range. Must be between 0 and 255.'
}
def to_internal_value(self, data):
if not isinstance(data, str):
self.fail('incorrect_type', input_type=type(data).__name__)
if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
self.fail('incorrect_format')
data = data.strip('rgb(').rstrip(')')
red, green, blue = [int(col) for col in data.split(',')]
if any([col > 255 or col < 0 for col in (red, green, blue)]):
self.fail('out_of_range')
return Color(red, green, blue)
This style keeps your error messages cleaner and more separated from your code, and should be preferred. Using source='*' Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes. class DataPoint(models.Model):
label = models.CharField(max_length=50)
x_coordinate = models.SmallIntegerField()
y_coordinate = models.SmallIntegerField()
Using a custom field and source='*' we can provide a nested representation of the coordinate pair: class CoordinateField(serializers.Field):
def to_representation(self, value):
ret = {
"x": value.x_coordinate,
"y": value.y_coordinate
}
return ret
def to_internal_value(self, data):
ret = {
"x_coordinate": data["x"],
"y_coordinate": data["y"],
}
return ret
class DataPointSerializer(serializers.ModelSerializer):
coordinates = CoordinateField(source='*')
class Meta:
model = DataPoint
fields = ['label', 'coordinates']
Note that this example doesn't handle validation. Partly for that reason, in a real project, the coordinate nesting might be better handled with a nested serializer using source='*', with two IntegerField instances, each with their own source pointing to the relevant field. The key points from the example, though, are: to_representation is passed the entire DataPoint object and must map from that to the desired output. >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)
>>> out_serializer = DataPointSerializer(instance)
>>> out_serializer.data
ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})])
Unless our field is to be read-only, to_internal_value must map back to a dict suitable for updating our target object. With source='*', the return from to_internal_value will update the root validated data dictionary, rather than a single key. >>> data = {
... "label": "Second Example",
... "coordinates": {
... "x": 3,
... "y": 4,
... }
... }
>>> in_serializer = DataPointSerializer(data=data)
>>> in_serializer.is_valid()
True
>>> in_serializer.validated_data
OrderedDict([('label', 'Second Example'),
('y_coordinate', 4),
('x_coordinate', 3)])
For completeness lets do the same thing again but with the nested serializer approach suggested above: class NestedCoordinateSerializer(serializers.Serializer):
x = serializers.IntegerField(source='x_coordinate')
y = serializers.IntegerField(source='y_coordinate')
class DataPointSerializer(serializers.ModelSerializer):
coordinates = NestedCoordinateSerializer(source='*')
class Meta:
model = DataPoint
fields = ['label', 'coordinates']
Here the mapping between the target and source attribute pairs (x and x_coordinate, y and y_coordinate) is handled in the IntegerField declarations. It's our NestedCoordinateSerializer that takes source='*'. Our new DataPointSerializer exhibits the same behaviour as the custom field approach. Serializing: >>> out_serializer = DataPointSerializer(instance)
>>> out_serializer.data
ReturnDict([('label', 'testing'),
('coordinates', OrderedDict([('x', 1), ('y', 2)]))])
Deserializing: >>> in_serializer = DataPointSerializer(data=data)
>>> in_serializer.is_valid()
True
>>> in_serializer.validated_data
OrderedDict([('label', 'still testing'),
('x_coordinate', 3),
('y_coordinate', 4)])
But we also get the built-in validation for free: >>> invalid_data = {
... "label": "still testing",
... "coordinates": {
... "x": 'a',
... "y": 'b',
... }
... }
>>> invalid_serializer = DataPointSerializer(data=invalid_data)
>>> invalid_serializer.is_valid()
False
>>> invalid_serializer.errors
ReturnDict([('coordinates',
{'x': ['A valid integer is required.'],
'y': ['A valid integer is required.']})])
For this reason, the nested serializer approach would be the first to try. You would use the custom field approach when the nested serializer becomes infeasible or overly complex. Third party packages The following third party packages are also available. DRF Compound Fields The drf-compound-fields package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the many=True option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type. DRF Extra Fields The drf-extra-fields package provides extra serializer fields for REST framework, including Base64ImageField and PointField classes. djangorestframework-recursive the djangorestframework-recursive package provides a RecursiveField for serializing and deserializing recursive structures django-rest-framework-gis The django-rest-framework-gis package provides geographic addons for django rest framework like a GeometryField field and a GeoJSON serializer. django-rest-framework-hstore The django-rest-framework-hstore package provides an HStoreField to support django-hstore DictionaryField model field. fields.py | |
doc_27053 | Return the context variable name that will be used to contain the list of data that this view is manipulating. If object_list is a queryset of Django objects and context_object_name is not set, the context name will be the model_name of the model that the queryset is composed from, with postfix '_list' appended. For example, the model Article would have a context object named article_list. | |
doc_27054 | re.LOCALE
Make \w, \W, \b, \B and case-insensitive matching dependent on the current locale. This flag can be used only with bytes patterns. The use of this flag is discouraged as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages. Corresponds to the inline flag (?L). Changed in version 3.6: re.LOCALE can be used only with bytes patterns and is not compatible with re.ASCII. Changed in version 3.7: Compiled regular expression objects with the re.LOCALE flag no longer depend on the locale at compile time. Only the locale at matching time affects the result of matching. | |
doc_27055 | Called if the XML document hasn’t been declared as being a standalone document. This happens when there is an external subset or a reference to a parameter entity, but the XML declaration does not set standalone to yes in an XML declaration. If this handler returns 0, then the parser will raise an XML_ERROR_NOT_STANDALONE error. If this handler is not set, no exception is raised by the parser for this condition. | |
doc_27056 |
Return True if given object is complex. Returns
bool | |
doc_27057 |
Perform one Gibbs sampling step. Parameters
vndarray of shape (n_samples, n_features)
Values of the visible layer to start from. Returns
v_newndarray of shape (n_samples, n_features)
Values of the visible layer after one Gibbs step. | |
doc_27058 |
Predict multi-class targets using underlying estimators. Parameters
X(sparse) array-like of shape (n_samples, n_features)
Data. Returns
y(sparse) array-like of shape (n_samples,) or (n_samples, n_classes)
Predicted multi-class targets. | |
doc_27059 | tf.metrics.CosineSimilarity Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.CosineSimilarity
tf.keras.metrics.CosineSimilarity(
name='cosine_similarity', dtype=None, axis=-1
)
cosine similarity = (a . b) / ||a|| ||b|| See: Cosine Similarity. This metric keeps the average cosine similarity between predictions and labels over a stream of data.
Args
name (Optional) string name of the metric instance.
dtype (Optional) data type of the metric result.
axis (Optional) Defaults to -1. The dimension along which the cosine similarity is computed. Standalone usage:
# l2_norm(y_true) = [[0., 1.], [1./1.414], 1./1.414]]]
# l2_norm(y_pred) = [[1., 0.], [1./1.414], 1./1.414]]]
# l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]]
# result = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1))
# = ((0. + 0.) + (0.5 + 0.5)) / 2
m = tf.keras.metrics.CosineSimilarity(axis=1)
m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]])
m.result().numpy()
0.49999997
m.reset_states()
m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]],
sample_weight=[0.3, 0.7])
m.result().numpy()
0.6999999
Usage with compile() API: model.compile(
optimizer='sgd',
loss='mse',
metrics=[tf.keras.metrics.CosineSimilarity(axis=1)])
Methods reset_states View source
reset_states()
Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
y_true, y_pred, sample_weight=None
)
Accumulates metric statistics. y_true and y_pred should have the same shape.
Args
y_true Ground truth values. shape = [batch_size, d0, .. dN].
y_pred The predicted values. shape = [batch_size, d0, .. dN].
sample_weight Optional sample_weight acts as a coefficient for the metric. If a scalar is provided, then the metric is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the metric for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each metric element of y_pred is scaled by the corresponding value of sample_weight. (Note on dN-1: all metric functions reduce by 1 dimension, usually the last axis (-1)).
Returns Update op. | |
doc_27060 | testing.assert_raises(exception_class) → None
Fail unless an exception of class exception_class is thrown by callable when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. Alternatively, assert_raises can be used as a context manager: >>> from numpy.testing import assert_raises
>>> with assert_raises(ZeroDivisionError):
... 1 / 0
is equivalent to >>> def div(x, y):
... return x / y
>>> assert_raises(ZeroDivisionError, div, 1, 0) | |
doc_27061 | See Migration guide for more details. tf.compat.v1.math.special.bessel_y1
tf.math.special.bessel_y1(
x, name=None
)
Modified Bessel function of order 1.
tf.math.special.bessel_y1([0.5, 1., 2., 4.]).numpy()
array([-1.47147239, -0.78121282, -0.10703243, 0.39792571], dtype=float32)
Args
x A Tensor or SparseTensor. Must be one of the following types: half, float32, float64.
name A name for the operation (optional).
Returns A Tensor or SparseTensor, respectively. Has the same type as x.
Scipy Compatibility Equivalent to scipy.special.y1 | |
doc_27062 | Equivalent to as_string(policy=self.policy.clone(utf8=True)). Allows str(msg) to produce a string containing the serialized message in a readable format. Changed in version 3.4: the method was changed to use utf8=True, thus producing an RFC 6531-like message representation, instead of being a direct alias for as_string(). | |
doc_27063 | This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised. If you pass in a function it will be called with same arguments as the mock and unless the function returns the DEFAULT singleton the call to the mock will then return whatever the function returns. If the function returns DEFAULT then the mock will return its normal value (from the return_value). If you pass in an iterable, it is used to retrieve an iterator which must yield a value on every call. This value can either be an exception instance to be raised, or a value to be returned from the call to the mock (DEFAULT handling is identical to the function case). An example of a mock that raises an exception (to test exception handling of an API): >>> mock = Mock()
>>> mock.side_effect = Exception('Boom!')
>>> mock()
Traceback (most recent call last):
...
Exception: Boom!
Using side_effect to return a sequence of values: >>> mock = Mock()
>>> mock.side_effect = [3, 2, 1]
>>> mock(), mock(), mock()
(3, 2, 1)
Using a callable: >>> mock = Mock(return_value=3)
>>> def side_effect(*args, **kwargs):
... return DEFAULT
...
>>> mock.side_effect = side_effect
>>> mock()
3
side_effect can be set in the constructor. Here’s an example that adds one to the value the mock is called with and returns it: >>> side_effect = lambda value: value + 1
>>> mock = Mock(side_effect=side_effect)
>>> mock(3)
4
>>> mock(-8)
-7
Setting side_effect to None clears it: >>> m = Mock(side_effect=KeyError, return_value=3)
>>> m()
Traceback (most recent call last):
...
KeyError
>>> m.side_effect = None
>>> m()
3 | |
doc_27064 |
Return indices of the minimum values along the given axis. Refer to numpy.argmin for detailed documentation. See also numpy.argmin
equivalent function | |
doc_27065 |
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data | |
doc_27066 | Resets the string buffer with the given data. | |
doc_27067 | Creates a new Surface from the current PixelArray. make_surface() -> Surface Creates a new Surface from the current PixelArray. Depending on the current PixelArray the size, pixel order etc. will be different from the original Surface. # Create a new surface flipped around the vertical axis.
sf = pxarray[:,::-1].make_surface () New in pygame 1.8.1. | |
doc_27068 | os.SF_MNOWAIT
os.SF_SYNC
Parameters to the sendfile() function, if the implementation supports them. Availability: Unix. New in version 3.3. | |
doc_27069 | queue a Sound object to follow the current queue(Sound) -> None When a Sound is queued on a Channel, it will begin playing immediately after the current Sound is finished. Each channel can only have a single Sound queued at a time. The queued Sound will only play if the current playback finished automatically. It is cleared on any other call to Channel.stop() or Channel.play(). If there is no sound actively playing on the Channel then the Sound will begin playing immediately. | |
doc_27070 | See Migration guide for more details. tf.compat.v1.raw_ops.TopK
tf.raw_ops.TopK(
input, k, sorted=True, name=None
)
If the input is a vector (rank-1), finds the k largest entries in the vector and outputs their values and indices as vectors. Thus values[j] is the j-th largest entry in input, and its index is indices[j]. For matrices (resp. higher rank input), computes the top k entries in each row (resp. vector along the last dimension). Thus, values.shape = indices.shape = input.shape[:-1] + [k]
If two elements are equal, the lower-index element appears first. If k varies dynamically, use TopKV2 below.
Args
input A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. 1-D or higher with last dimension at least k.
k An int that is >= 0. Number of top elements to look for along the last dimension (along each row for matrices).
sorted An optional bool. Defaults to True. If true the resulting k elements will be sorted by the values in descending order.
name A name for the operation (optional).
Returns A tuple of Tensor objects (values, indices). values A Tensor. Has the same type as input.
indices A Tensor of type int32. | |
doc_27071 | Return the natural (base e) logarithm of the operand. The result is correctly rounded using the ROUND_HALF_EVEN rounding mode. | |
doc_27072 | tf.logical_or Compat aliases for migration See Migration guide for more details. tf.compat.v1.logical_or, tf.compat.v1.math.logical_or
tf.math.logical_or(
x, y, name=None
)
Note: math.logical_or supports broadcasting. More about broadcasting here
Args
x A Tensor of type bool.
y A Tensor of type bool.
name A name for the operation (optional).
Returns A Tensor of type bool. | |
doc_27073 |
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_27074 |
Return (x1 <= x2) element-wise. Unlike numpy.less_equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters
x1, x2array_like of str or unicode
Input arrays of the same shape. Returns
outndarray
Output array of bools. See also
equal, not_equal, greater_equal, greater, less | |
doc_27075 | Temporarily set the environment variable envvar to the value of value. | |
doc_27076 |
Return element-wise title cased version of string or unicode. Title case words start with uppercase characters, all remaining cased characters are lowercase. Calls str.title element-wise. For 8-bit strings, this method is locale-dependent. Parameters
aarray_like, {str, unicode}
Input array. Returns
outndarray
Output array of str or unicode, depending on input type See also str.title
Examples >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
dtype='|S5')
>>> np.char.title(c)
array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
dtype='|S5') | |
doc_27077 | Timer signal from alarm(2). Availability: Unix. | |
doc_27078 | Returns a new tensor with the floor of the elements of input, the largest integer less than or equal to each element. outi=⌊inputi⌋\text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([-0.8166, 1.5308, -0.2530, -0.2091])
>>> torch.floor(a)
tensor([-1., 1., -1., -1.]) | |
doc_27079 | The 1-based page number for this page. | |
doc_27080 |
Range of values (maximum - minimum) along an axis. The name of the function comes from the acronym for ‘peak to peak’. Warning ptp preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. np.int8, np.int16, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than 2**(n-1)-1 will be returned as negative values. An example with a work-around is shown below. Parameters
aarray_like
Input values.
axisNone or int or tuple of ints, optional
Axis along which to find the peaks. By default, flatten the array. axis may be negative, in which case it counts from the last to the first axis. New in version 1.15.0. If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.
outarray_like
Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type of the output values will be cast if necessary.
keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the ptp method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns
ptpndarray
A new array holding the result, unless out was specified, in which case a reference to out is returned. Examples >>> x = np.array([[4, 9, 2, 10],
... [6, 9, 7, 12]])
>>> np.ptp(x, axis=1)
array([8, 6])
>>> np.ptp(x, axis=0)
array([2, 0, 5, 2])
>>> np.ptp(x)
10
This example shows that a negative value can be returned when the input is an array of signed integers. >>> y = np.array([[1, 127],
... [0, 127],
... [-1, 127],
... [-2, 127]], dtype=np.int8)
>>> np.ptp(y, axis=1)
array([ 126, 127, -128, -127], dtype=int8)
A work-around is to use the view() method to view the result as unsigned integers with the same bit width: >>> np.ptp(y, axis=1).view(np.uint8)
array([126, 127, 128, 129], dtype=uint8) | |
doc_27081 |
Perform classification on test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Predicted target values for X. | |
doc_27082 |
Alias for get_fontstyle. | |
doc_27083 | See Migration guide for more details. tf.compat.v1.raw_ops.TensorScatterSub
tf.raw_ops.TensorScatterSub(
tensor, indices, updates, name=None
)
This operation creates a new tensor by subtracting sparse updates from the passed in tensor. This operation is very similar to tf.scatter_nd_sub, except that the updates are subtracted from an existing tensor (as opposed to a variable). If the memory for the existing tensor cannot be re-used, a copy is made and updated. indices is an integer tensor containing indices into a new tensor of shape shape. The last dimension of indices can be at most the rank of shape: indices.shape[-1] <= shape.rank
The last dimension of indices corresponds to indices into elements (if indices.shape[-1] = shape.rank) or slices (if indices.shape[-1] < shape.rank) along dimension indices.shape[-1] of shape. updates is a tensor with shape indices.shape[:-1] + shape[indices.shape[-1]:]
The simplest form of tensor_scatter_sub is to subtract individual elements from a tensor by index. For example, say we want to insert 4 scattered elements in a rank-1 tensor with 8 elements. In Python, this scatter subtract operation would look like this: indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
tensor = tf.ones([8], dtype=tf.int32)
updated = tf.tensor_scatter_nd_sub(tensor, indices, updates)
print(updated)
The resulting tensor would look like this: [1, -10, 1, -9, -8, 1, 1, -11]
We can also, insert entire slices of a higher rank tensor all at once. For example, if we wanted to insert two slices in the first dimension of a rank-3 tensor with two matrices of new values. In Python, this scatter add operation would look like this: indices = tf.constant([[0], [2]])
updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],
[7, 7, 7, 7], [8, 8, 8, 8]],
[[5, 5, 5, 5], [6, 6, 6, 6],
[7, 7, 7, 7], [8, 8, 8, 8]]])
tensor = tf.ones([4, 4, 4],dtype=tf.int32)
updated = tf.tensor_scatter_nd_sub(tensor, indices, updates)
print(updated)
The resulting tensor would look like this: [[[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]],
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
[[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]],
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]
Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, the index is ignored.
Args
tensor A Tensor. Tensor to copy/update.
indices A Tensor. Must be one of the following types: int32, int64. Index tensor.
updates A Tensor. Must have the same type as tensor. Updates to scatter into output.
name A name for the operation (optional).
Returns A Tensor. Has the same type as tensor. | |
doc_27084 |
Combine regions separated by weight less than threshold. Given an image’s labels and its RAG, output new labels by combining regions whose nodes are separated by a weight less than the given threshold. Parameters
labelsndarray
The array of labels.
ragRAG
The region adjacency graph.
threshfloat
The threshold. Regions connected by edges with smaller weights are combined.
in_placebool
If set, modifies rag in place. The function will remove the edges with weights less that thresh. If set to False the function makes a copy of rag before proceeding. Returns
outndarray
The new labelled array. References
1
Alain Tremeau and Philippe Colantoni “Regions Adjacency Graph Applied To Color Image Segmentation” DOI:10.1109/83.841950 Examples >>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels)
>>> new_labels = graph.cut_threshold(labels, rag, 10) | |
doc_27085 | sklearn.datasets.make_blobs(n_samples=100, n_features=2, *, centers=None, cluster_std=1.0, center_box=- 10.0, 10.0, shuffle=True, random_state=None, return_centers=False) [source]
Generate isotropic Gaussian blobs for clustering. Read more in the User Guide. Parameters
n_samplesint or array-like, default=100
If int, it is the total number of points equally divided among clusters. If array-like, each element of the sequence indicates the number of samples per cluster. Changed in version v0.20: one can now pass an array-like to the n_samples parameter
n_featuresint, default=2
The number of features for each sample.
centersint or ndarray of shape (n_centers, n_features), default=None
The number of centers to generate, or the fixed center locations. If n_samples is an int and centers is None, 3 centers are generated. If n_samples is array-like, centers must be either None or an array of length equal to the length of n_samples.
cluster_stdfloat or array-like of float, default=1.0
The standard deviation of the clusters.
center_boxtuple of float (min, max), default=(-10.0, 10.0)
The bounding box for each cluster center when centers are generated at random.
shufflebool, default=True
Shuffle the samples.
random_stateint, RandomState instance or None, default=None
Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. See Glossary.
return_centersbool, default=False
If True, then return the centers of each cluster New in version 0.23. Returns
Xndarray of shape (n_samples, n_features)
The generated samples.
yndarray of shape (n_samples,)
The integer labels for cluster membership of each sample.
centersndarray of shape (n_centers, n_features)
The centers of each cluster. Only returned if return_centers=True. See also
make_classification
A more intricate variant. Examples >>> from sklearn.datasets import make_blobs
>>> X, y = make_blobs(n_samples=10, centers=3, n_features=2,
... random_state=0)
>>> print(X.shape)
(10, 2)
>>> y
array([0, 0, 1, 0, 2, 2, 2, 1, 1, 0])
>>> X, y = make_blobs(n_samples=[3, 3, 4], centers=None, n_features=2,
... random_state=0)
>>> print(X.shape)
(10, 2)
>>> y
array([0, 1, 2, 0, 2, 2, 2, 1, 1, 0])
Examples using sklearn.datasets.make_blobs
Release Highlights for scikit-learn 0.23
Probability calibration of classifiers
Probability Calibration for 3-class classification
Normal, Ledoit-Wolf and OAS Linear Discriminant Analysis for classification
An example of K-Means++ initialization
A demo of the mean-shift clustering algorithm
Demonstration of k-means assumptions
Demo of affinity propagation clustering algorithm
Demo of DBSCAN clustering algorithm
Inductive Clustering
Compare BIRCH and MiniBatchKMeans
Comparison of the K-Means and MiniBatchKMeans clustering algorithms
Comparing different hierarchical linkage methods on toy datasets
Selecting the number of clusters with silhouette analysis on KMeans clustering
Comparing different clustering algorithms on toy datasets
Plot randomly generated classification dataset
SGD: Maximum margin separating hyperplane
Plot multinomial and One-vs-Rest Logistic Regression
Comparing anomaly detection algorithms for outlier detection on toy datasets
Demonstrating the different strategies of KBinsDiscretizer
SVM: Maximum margin separating hyperplane
SVM Tie Breaking Example
Plot the support vectors in LinearSVC
SVM: Separating hyperplane for unbalanced classes | |
doc_27086 | This function is identical to the fcntl() function, except that the argument handling is even more complicated. The request parameter is limited to values that can fit in 32-bits. Additional constants of interest for use as the request argument can be found in the termios module, under the same names as used in the relevant C header files. The parameter arg can be one of an integer, an object supporting the read-only buffer interface (like bytes) or an object supporting the read-write buffer interface (like bytearray). In all but the last case, behaviour is as for the fcntl() function. If a mutable buffer is passed, then the behaviour is determined by the value of the mutate_flag parameter. If it is false, the buffer’s mutability is ignored and behaviour is as for a read-only buffer, except that the 1024 byte limit mentioned above is avoided – so long as the buffer you pass is at least as long as what the operating system wants to put there, things should work. If mutate_flag is true (the default), then the buffer is (in effect) passed to the underlying ioctl() system call, the latter’s return code is passed back to the calling Python, and the buffer’s new contents reflect the action of the ioctl(). This is a slight simplification, because if the supplied buffer is less than 1024 bytes long it is first copied into a static buffer 1024 bytes long which is then passed to ioctl() and copied back into the supplied buffer. If the ioctl() fails, an OSError exception is raised. An example: >>> import array, fcntl, struct, termios, os
>>> os.getpgrp()
13341
>>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0]
13341
>>> buf = array.array('h', [0])
>>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)
0
>>> buf
array('h', [13341])
Raises an auditing event fcntl.ioctl with arguments fd, request, arg. | |
doc_27087 |
Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc))
<type 'Locator'>
>>> print(loc())
[1, 2, 3, 4] | |
doc_27088 |
Update the dimensions of the passed parameters. None means unchanged. | |
doc_27089 |
Return an array with the elements of self converted to lowercase. See also char.lower | |
doc_27090 | skimage.viewer.utils.figimage(image[, …]) Return figure and axes with figure tightly surrounding image.
skimage.viewer.utils.init_qtapp() Initialize QAppliction.
skimage.viewer.utils.new_plot([parent, …]) Return new figure and axes.
skimage.viewer.utils.start_qtapp([app]) Start Qt mainloop
skimage.viewer.utils.update_axes_image(…) Update the image displayed by an image plot.
skimage.viewer.utils.ClearColormap(rgb[, …]) Color map that varies linearly from alpha = 0 to 1
skimage.viewer.utils.FigureCanvas(figure, …) Canvas for displaying images.
skimage.viewer.utils.LinearColormap(name, …) LinearSegmentedColormap in which color varies smoothly.
skimage.viewer.utils.RequiredAttr([init_val]) A class attribute that must be set before use.
skimage.viewer.utils.canvas
skimage.viewer.utils.core
skimage.viewer.utils.dialogs figimage
skimage.viewer.utils.figimage(image, scale=1, dpi=None, **kwargs) [source]
Return figure and axes with figure tightly surrounding image. Unlike pyplot.figimage, this actually plots onto an axes object, which fills the figure. Plotting the image onto an axes allows for subsequent overlays of axes artists. Parameters
imagearray
image to plot
scalefloat
If scale is 1, the figure and axes have the same dimension as the image. Smaller values of scale will shrink the figure.
dpiint
Dots per inch for figure. If None, use the default rcParam.
init_qtapp
skimage.viewer.utils.init_qtapp() [source]
Initialize QAppliction. The QApplication needs to be initialized before creating any QWidgets
new_plot
skimage.viewer.utils.new_plot(parent=None, subplot_kw=None, **fig_kw) [source]
Return new figure and axes. Parameters
parentQtWidget
Qt widget that displays the plot objects. If None, you must manually call canvas.setParent and pass the parent widget.
subplot_kwdict
Keyword arguments passed matplotlib.figure.Figure.add_subplot.
fig_kwdict
Keyword arguments passed matplotlib.figure.Figure.
start_qtapp
skimage.viewer.utils.start_qtapp(app=None) [source]
Start Qt mainloop
update_axes_image
skimage.viewer.utils.update_axes_image(image_axes, image) [source]
Update the image displayed by an image plot. This sets the image plot’s array and updates its shape appropriately Parameters
image_axesmatplotlib.image.AxesImage
Image axes to update.
imagearray
Image array.
ClearColormap
class skimage.viewer.utils.ClearColormap(rgb, max_alpha=1, name='clear_color') [source]
Bases: skimage.viewer.utils.core.LinearColormap Color map that varies linearly from alpha = 0 to 1
__init__(rgb, max_alpha=1, name='clear_color') [source]
Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of x, y0, y1 tuples, forming rows in a table. Entries for alpha are optional. Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use: cdict = {'red': [(0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'green': [(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0)]}
Each row in the table for a given color is a sequence of x, y0, y1 tuples. In each sequence, x must increase monotonically from 0 to 1. For any input value z falling between x[i] and x[i+1], the output value of a given color will be linearly interpolated between y1[i] and y0[i+1]: row i: x y0 y1
/
/
row i+1: x y0 y1
Hence y0 in the first row and y1 in the last row are never used. See also
LinearSegmentedColormap.from_list
Static method; factory function for generating a smoothly-varying LinearSegmentedColormap.
makeMappingArray
For information about making a mapping array.
FigureCanvas
class skimage.viewer.utils.FigureCanvas(figure, **kwargs) [source]
Bases: object Canvas for displaying images.
__init__(figure, **kwargs) [source]
Initialize self. See help(type(self)) for accurate signature.
resizeEvent(event) [source]
LinearColormap
class skimage.viewer.utils.LinearColormap(name, segmented_data, **kwargs) [source]
Bases: matplotlib.colors.LinearSegmentedColormap LinearSegmentedColormap in which color varies smoothly. This class is a simplification of LinearSegmentedColormap, which doesn’t support jumps in color intensities. Parameters
namestr
Name of colormap.
segmented_datadict
Dictionary of ‘red’, ‘green’, ‘blue’, and (optionally) ‘alpha’ values. Each color key contains a list of x, y tuples. x must increase monotonically from 0 to 1 and corresponds to input values for a mappable object (e.g. an image). y corresponds to the color intensity.
__init__(name, segmented_data, **kwargs) [source]
Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of x, y0, y1 tuples, forming rows in a table. Entries for alpha are optional. Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use: cdict = {'red': [(0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'green': [(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0)]}
Each row in the table for a given color is a sequence of x, y0, y1 tuples. In each sequence, x must increase monotonically from 0 to 1. For any input value z falling between x[i] and x[i+1], the output value of a given color will be linearly interpolated between y1[i] and y0[i+1]: row i: x y0 y1
/
/
row i+1: x y0 y1
Hence y0 in the first row and y1 in the last row are never used. See also
LinearSegmentedColormap.from_list
Static method; factory function for generating a smoothly-varying LinearSegmentedColormap.
makeMappingArray
For information about making a mapping array.
RequiredAttr
class skimage.viewer.utils.RequiredAttr(init_val=None) [source]
Bases: object A class attribute that must be set before use.
__init__(init_val=None) [source]
Initialize self. See help(type(self)) for accurate signature.
instances = {(<skimage.viewer.utils.core.RequiredAttr object>, None): 'Widget is not attached to a Plugin.', (<skimage.viewer.utils.core.RequiredAttr object>, None): 'Plugin is not attached to ImageViewer'} | |
doc_27091 |
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values. | |
doc_27092 |
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str. | |
doc_27093 | class ast.USub
class ast.Not
class ast.Invert
Unary operator tokens. Not is the not keyword, Invert is the ~ operator. >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
Expression(
body=UnaryOp(
op=Not(),
operand=Name(id='x', ctx=Load()))) | |
doc_27094 | A Popen creationflags parameter to specify that a new process will have a high priority. New in version 3.7. | |
doc_27095 | This method is not defined in BaseHandler, but subclasses should define it if they want to post-process responses of the given protocol. This method, if defined, will be called by the parent OpenerDirector. req will be a Request object. response will be an object implementing the same interface as the return value of urlopen(). The return value should implement the same interface as the return value of urlopen(). | |
doc_27096 |
Load and return the physical excercise linnerud dataset. This dataset is suitable for multi-ouput regression tasks.
Samples total 20
Dimensionality 3 (for both data and target)
Features integer
Targets integer Read more in the User Guide. Parameters
return_X_ybool, default=False
If True, returns (data, target) instead of a Bunch object. See below for more information about the data and target object. New in version 0.18.
as_framebool, default=False
If True, the data is a pandas DataFrame including columns with appropriate dtypes (numeric, string or categorical). The target is a pandas DataFrame or Series depending on the number of target columns. If return_X_y is True, then (data, target) will be pandas DataFrames or Series as described below. New in version 0.23. Returns
dataBunch
Dictionary-like object, with the following attributes.
data{ndarray, dataframe} of shape (20, 3)
The data matrix. If as_frame=True, data will be a pandas DataFrame. target: {ndarray, dataframe} of shape (20, 3)
The regression targets. If as_frame=True, target will be a pandas DataFrame. feature_names: list
The names of the dataset columns. target_names: list
The names of the target columns. frame: DataFrame of shape (20, 6)
Only present when as_frame=True. DataFrame with data and target. New in version 0.23. DESCR: str
The full description of the dataset. data_filename: str
The path to the location of the data. target_filename: str
The path to the location of the target. New in version 0.20.
(data, target)tuple if return_X_y is True
New in version 0.18. | |
doc_27097 | os.P_NOWAITO
Possible values for the mode parameter to the spawn* family of functions. If either of these values is given, the spawn*() functions will return as soon as the new process has been created, with the process id as the return value. Availability: Unix, Windows. | |
doc_27098 |
Check if windows match. New in version 1.6.0. Parameters
otherclass instance
The other class must have the window attribute. Returns
boolboolean
True if the windows are the same, False otherwise. | |
doc_27099 | tf.experimental.numpy.moveaxis(
a, source, destination
)
Raises ValueError if source, destination not in (-ndim(a), ndim(a)). See the NumPy documentation for numpy.moveaxis. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.