_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_3300 |
Call self as a function. | |
doc_3301 | See torch.multiply(). | |
doc_3302 |
Gathers picklable objects from the whole group into a list. Similar to all_gather(), but Python objects can be passed in. Note that the object must be picklable in order to be gathered. Parameters
object_list (list[Any]) – Output list. It should be correctly sized as the size of the group for this collective and will contain the output.
object (Any) – Pickable Python object to be broadcast from current process.
group (ProcessGroup, optional) – The process group to work on. If None, the default process group will be used. Default is None. Returns
None. If the calling rank is part of this group, the output of the collective will be populated into the input object_list. If the calling rank is not part of the group, the passed in object_list will be unmodified. Note Note that this API differs slightly from the all_gather() collective since it does not provide an async_op handle and thus will be a blocking call. Note For NCCL-based processed groups, internal tensor representations of objects must be moved to the GPU device before communication takes place. In this case, the device used is given by torch.cuda.current_device() and it is the user’s responsiblity to ensure that this is set so that each rank has an individual GPU, via torch.cuda.set_device(). Warning all_gather_object() uses pickle module implicitly, which is known to be insecure. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. Only call this function with data you trust. Example::
>>> # Note: Process group initialization omitted on each rank.
>>> import torch.distributed as dist
>>> # Assumes world_size of 3.
>>> gather_objects = ["foo", 12, {1: 2}] # any picklable object
>>> output = [None for _ in gather_objects]
>>> dist.all_gather_object(output, gather_objects[dist.get_rank()])
>>> output
['foo', 12, {1: 2}] | |
doc_3303 |
Set the point at which create_node and companion methods will insert into the graph. When used within a ‘with’ statement, this will temporary set the insert point and then restore it when the with statement exits: with g.inserting_after(n):
... # inserting after node n
... # insert point restored to what it was previously
g.inserting_after(n) # set the insert point permanently
Parameters
n (Optional[Node]) – The node before which to insert. If None this will insert after the beginning of the entire graph. Returns
A resource manager that will restore the insert point on __exit__. | |
doc_3304 | tf.experimental.numpy.ndarray(
shape, dtype=float, buffer=None
)
This does not support all features of NumPy ndarrays e.g. strides and memory order since, unlike NumPy, the backing storage is not a raw memory buffer. or if there are any differences in behavior.
Args
shape The shape of the array. Must be a scalar, an iterable of integers or a TensorShape object.
dtype Optional. The dtype of the array. Must be a python type, a numpy type or a tensorflow DType object.
buffer Optional. The backing buffer of the array. Must have shape shape. Must be a ndarray, np.ndarray or a Tensor.
Raises
ValueError If buffer is specified and its shape does not match shape.
Attributes
T
data Tensor object containing the array data. This has a few key differences from the Python buffer object used in NumPy arrays. Tensors are immutable. So operations requiring in-place edit, e.g. setitem, are performed by replacing the underlying buffer with a new one. Tensors do not provide access to their raw buffer.
dtype
ndim
shape Returns a tuple or tf.Tensor of array dimensions.
size Returns the number of elements in the array. Methods astype View source
astype(
dtype
)
clip View source
clip(
a, a_min, a_max
)
TensorFlow variant of NumPy's clip. Unsupported arguments: out, kwargs. See the NumPy documentation for numpy.clip. from_tensor View source
@classmethod
from_tensor(
tensor
)
ravel View source
ravel(
a
)
TensorFlow variant of NumPy's ravel. Unsupported arguments: order. See the NumPy documentation for numpy.ravel. reshape View source
reshape(
a, *newshape, **kwargs
)
tolist View source
tolist()
transpose View source
transpose(
a, axes=None
)
TensorFlow variant of NumPy's transpose. See the NumPy documentation for numpy.transpose. __abs__ View source
__abs__(
x
)
TensorFlow variant of NumPy's absolute. Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.absolute. __add__ View source
__add__(
a, b
)
__bool__ View source
__bool__()
__eq__ View source
__eq__(
a, b
)
__floordiv__ View source
__floordiv__(
a, b
)
__ge__ View source
__ge__(
a, b
)
__getitem__ View source
__getitem__(
slice_spec
)
Implementation of ndarray.getitem. __gt__ View source
__gt__(
a, b
)
__invert__ View source
__invert__(
x
)
TensorFlow variant of NumPy's logical_not. Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.logical_not. __iter__ View source
__iter__()
__le__ View source
__le__(
a, b
)
__len__ View source
__len__()
__lt__ View source
__lt__(
a, b
)
__matmul__ View source
__matmul__(
a, b
)
__mod__ View source
__mod__(
a, b
)
__mul__ View source
__mul__(
a, b
)
__ne__ View source
__ne__(
a, b
)
__neg__ View source
__neg__()
__nonzero__ View source
__nonzero__()
__pos__ View source
__pos__()
__pow__ View source
__pow__(
a, b
)
__radd__ View source
__radd__(
a, b
)
__rfloordiv__ View source
__rfloordiv__(
a, b
)
__rmatmul__ View source
__rmatmul__(
a, b
)
__rmod__ View source
__rmod__(
a, b
)
__rmul__ View source
__rmul__(
a, b
)
__rpow__ View source
__rpow__(
a, b
)
__rsub__ View source
__rsub__(
a, b
)
__rtruediv__ View source
__rtruediv__(
a, b
)
__sub__ View source
__sub__(
a, b
)
__truediv__ View source
__truediv__(
a, b
) | |
doc_3305 |
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats | |
doc_3306 | sklearn.metrics.make_scorer(score_func, *, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs) [source]
Make a scorer from a performance metric or loss function. This factory function wraps scoring functions for use in GridSearchCV and cross_val_score. It takes a score function, such as accuracy_score, mean_squared_error, adjusted_rand_index or average_precision and returns a callable that scores an estimator’s output. The signature of the call is (estimator, X, y) where estimator is the model to be evaluated, X is the data and y is the ground truth labeling (or None in the case of unsupervised models). Read more in the User Guide. Parameters
score_funccallable
Score function (or loss function) with signature score_func(y, y_pred, **kwargs).
greater_is_betterbool, default=True
Whether score_func is a score function (default), meaning high is good, or a loss function, meaning low is good. In the latter case, the scorer object will sign-flip the outcome of the score_func.
needs_probabool, default=False
Whether score_func requires predict_proba to get probability estimates out of a classifier. If True, for binary y_true, the score function is supposed to accept a 1D y_pred (i.e., probability of the positive class, shape (n_samples,)).
needs_thresholdbool, default=False
Whether score_func takes a continuous decision certainty. This only works for binary classification using estimators that have either a decision_function or predict_proba method. If True, for binary y_true, the score function is supposed to accept a 1D y_pred (i.e., probability of the positive class or the decision function, shape (n_samples,)). For example average_precision or the area under the roc curve can not be computed using discrete predictions alone.
**kwargsadditional arguments
Additional parameters to be passed to score_func. Returns
scorercallable
Callable object that returns a scalar score; greater is better. Notes If needs_proba=False and needs_threshold=False, the score function is supposed to accept the output of predict. If needs_proba=True, the score function is supposed to accept the output of predict_proba (For binary y_true, the score function is supposed to accept probability of the positive class). If needs_threshold=True, the score function is supposed to accept the output of decision_function. Examples >>> from sklearn.metrics import fbeta_score, make_scorer
>>> ftwo_scorer = make_scorer(fbeta_score, beta=2)
>>> ftwo_scorer
make_scorer(fbeta_score, beta=2)
>>> from sklearn.model_selection import GridSearchCV
>>> from sklearn.svm import LinearSVC
>>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]},
... scoring=ftwo_scorer)
Examples using sklearn.metrics.make_scorer
Demonstration of multi-metric evaluation on cross_val_score and GridSearchCV | |
doc_3307 |
Computes the (weighted) graph of k-Neighbors for points in X Parameters
Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None
The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features).
n_neighborsint, default=None
Number of neighbors for each sample. The default is the value passed to the constructor.
mode{‘connectivity’, ‘distance’}, default=’connectivity’
Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns
Asparse-matrix of shape (n_queries, n_samples_fit)
n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also
NearestNeighbors.radius_neighbors_graph
Examples >>> X = [[0], [3], [1]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(n_neighbors=2)
>>> neigh.fit(X)
NearestNeighbors(n_neighbors=2)
>>> A = neigh.kneighbors_graph(X)
>>> A.toarray()
array([[1., 0., 1.],
[0., 1., 1.],
[1., 0., 1.]]) | |
doc_3308 |
Compute the Calinski and Harabasz score. It is also known as the Variance Ratio Criterion. The score is defined as ratio between the within-cluster dispersion and the between-cluster dispersion. Read more in the User Guide. Parameters
Xarray-like of shape (n_samples, n_features)
A list of n_features-dimensional data points. Each row corresponds to a single data point.
labelsarray-like of shape (n_samples,)
Predicted labels for each sample. Returns
scorefloat
The resulting Calinski-Harabasz score. References
1
T. Calinski and J. Harabasz, 1974. “A dendrite method for cluster analysis”. Communications in Statistics | |
doc_3309 |
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
angle float
animated bool
antialiased or aa bool or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
center (float, float)
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
color color
edgecolor or ec color or None
facecolor or fc color or None
figure Figure
fill bool
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
height float
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw float or None
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
width float
zorder float | |
doc_3310 | Load a snapshot from a file. See also dump(). | |
doc_3311 |
An object for detecting outliers in a Gaussian distributed dataset. Read more in the User Guide. Parameters
store_precisionbool, default=True
Specify if the estimated precision is stored.
assume_centeredbool, default=False
If True, the support of robust location and covariance estimates is computed, and a covariance estimate is recomputed from it, without centering the data. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, the robust location and covariance are directly computed with the FastMCD algorithm without additional treatment.
support_fractionfloat, default=None
The proportion of points to be included in the support of the raw MCD estimate. If None, the minimum value of support_fraction will be used within the algorithm: [n_sample + n_features + 1] / 2. Range is (0, 1).
contaminationfloat, default=0.1
The amount of contamination of the data set, i.e. the proportion of outliers in the data set. Range is (0, 0.5).
random_stateint, RandomState instance or None, default=None
Determines the pseudo random number generator for shuffling the data. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Attributes
location_ndarray of shape (n_features,)
Estimated robust location.
covariance_ndarray of shape (n_features, n_features)
Estimated robust covariance matrix.
precision_ndarray of shape (n_features, n_features)
Estimated pseudo inverse matrix. (stored only if store_precision is True)
support_ndarray of shape (n_samples,)
A mask of the observations that have been used to compute the robust estimates of location and shape.
offset_float
Offset used to define the decision function from the raw scores. We have the relation: decision_function = score_samples - offset_. The offset depends on the contamination parameter and is defined in such a way we obtain the expected number of outliers (samples with decision function < 0) in training. New in version 0.20.
raw_location_ndarray of shape (n_features,)
The raw robust estimated location before correction and re-weighting.
raw_covariance_ndarray of shape (n_features, n_features)
The raw robust estimated covariance before correction and re-weighting.
raw_support_ndarray of shape (n_samples,)
A mask of the observations that have been used to compute the raw robust estimates of location and shape, before correction and re-weighting.
dist_ndarray of shape (n_samples,)
Mahalanobis distances of the training set (on which fit is called) observations. See also
EmpiricalCovariance, MinCovDet
Notes Outlier detection from covariance estimation may break or not perform well in high-dimensional settings. In particular, one will always take care to work with n_samples > n_features ** 2. References
1
Rousseeuw, P.J., Van Driessen, K. “A fast algorithm for the minimum covariance determinant estimator” Technometrics 41(3), 212 (1999) Examples >>> import numpy as np
>>> from sklearn.covariance import EllipticEnvelope
>>> true_cov = np.array([[.8, .3],
... [.3, .4]])
>>> X = np.random.RandomState(0).multivariate_normal(mean=[0, 0],
... cov=true_cov,
... size=500)
>>> cov = EllipticEnvelope(random_state=0).fit(X)
>>> # predict returns 1 for an inlier and -1 for an outlier
>>> cov.predict([[0, 0],
... [3, 3]])
array([ 1, -1])
>>> cov.covariance_
array([[0.7411..., 0.2535...],
[0.2535..., 0.3053...]])
>>> cov.location_
array([0.0813... , 0.0427...])
Methods
correct_covariance(data) Apply a correction to raw Minimum Covariance Determinant estimates.
decision_function(X) Compute the decision function of the given observations.
error_norm(comp_cov[, norm, scaling, squared]) Computes the Mean Squared Error between two covariance estimators.
fit(X[, y]) Fit the EllipticEnvelope model.
fit_predict(X[, y]) Perform fit on X and returns labels for X.
get_params([deep]) Get parameters for this estimator.
get_precision() Getter for the precision matrix.
mahalanobis(X) Computes the squared Mahalanobis distances of given observations.
predict(X) Predict the labels (1 inlier, -1 outlier) of X according to the fitted model.
reweight_covariance(data) Re-weight raw Minimum Covariance Determinant estimates.
score(X, y[, sample_weight]) Returns the mean accuracy on the given test data and labels.
score_samples(X) Compute the negative Mahalanobis distances.
set_params(**params) Set the parameters of this estimator.
correct_covariance(data) [source]
Apply a correction to raw Minimum Covariance Determinant estimates. Correction using the empirical correction factor suggested by Rousseeuw and Van Driessen in [RVD]. Parameters
dataarray-like of shape (n_samples, n_features)
The data matrix, with p features and n samples. The data set must be the one which was used to compute the raw estimates. Returns
covariance_correctedndarray of shape (n_features, n_features)
Corrected robust covariance estimate. References
RVD
A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS
decision_function(X) [source]
Compute the decision function of the given observations. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
decisionndarray of shape (n_samples,)
Decision function of the samples. It is equal to the shifted Mahalanobis distances. The threshold for being an outlier is 0, which ensures a compatibility with other outlier detection algorithms.
error_norm(comp_cov, norm='frobenius', scaling=True, squared=True) [source]
Computes the Mean Squared Error between two covariance estimators. (In the sense of the Frobenius norm). Parameters
comp_covarray-like of shape (n_features, n_features)
The covariance to compare with.
norm{“frobenius”, “spectral”}, default=”frobenius”
The type of norm used to compute the error. Available error types: - ‘frobenius’ (default): sqrt(tr(A^t.A)) - ‘spectral’: sqrt(max(eigenvalues(A^t.A)) where A is the error (comp_cov - self.covariance_).
scalingbool, default=True
If True (default), the squared error norm is divided by n_features. If False, the squared error norm is not rescaled.
squaredbool, default=True
Whether to compute the squared error norm or the error norm. If True (default), the squared error norm is returned. If False, the error norm is returned. Returns
resultfloat
The Mean Squared Error (in the sense of the Frobenius norm) between self and comp_cov covariance estimators.
fit(X, y=None) [source]
Fit the EllipticEnvelope model. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
yIgnored
Not used, present for API consistency by convention.
fit_predict(X, y=None) [source]
Perform fit on X and returns labels for X. Returns -1 for outliers and 1 for inliers. Parameters
X{array-like, sparse matrix, dataframe} of shape (n_samples, n_features)
yIgnored
Not used, present for API consistency by convention. Returns
yndarray of shape (n_samples,)
1 for inliers, -1 for outliers.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
get_precision() [source]
Getter for the precision matrix. Returns
precision_array-like of shape (n_features, n_features)
The precision matrix associated to the current covariance object.
mahalanobis(X) [source]
Computes the squared Mahalanobis distances of given observations. Parameters
Xarray-like of shape (n_samples, n_features)
The observations, the Mahalanobis distances of the which we compute. Observations are assumed to be drawn from the same distribution than the data used in fit. Returns
distndarray of shape (n_samples,)
Squared Mahalanobis distances of the observations.
predict(X) [source]
Predict the labels (1 inlier, -1 outlier) of X according to the fitted model. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
is_inlierndarray of shape (n_samples,)
Returns -1 for anomalies/outliers and +1 for inliers.
reweight_covariance(data) [source]
Re-weight raw Minimum Covariance Determinant estimates. Re-weight observations using Rousseeuw’s method (equivalent to deleting outlying observations from the data set before computing location and covariance estimates) described in [RVDriessen]. Parameters
dataarray-like of shape (n_samples, n_features)
The data matrix, with p features and n samples. The data set must be the one which was used to compute the raw estimates. Returns
location_reweightedndarray of shape (n_features,)
Re-weighted robust location estimate.
covariance_reweightedndarray of shape (n_features, n_features)
Re-weighted robust covariance estimate.
support_reweightedndarray of shape (n_samples,), dtype=bool
A mask of the observations that have been used to compute the re-weighted robust location and covariance estimates. References
RVDriessen
A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS
score(X, y, sample_weight=None) [source]
Returns the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) w.r.t. y.
score_samples(X) [source]
Compute the negative Mahalanobis distances. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
negative_mahal_distancesarray-like of shape (n_samples,)
Opposite of the Mahalanobis distances.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_3312 | Like SSLContext.maximum_version except it is the lowest supported version or TLSVersion.MINIMUM_SUPPORTED. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer. New in version 3.7. | |
doc_3313 |
Return the binary path to the commandline tool used by a specific subclass. This is a class method so that the tool can be looked for before making a particular MovieWriter subclass available. | |
doc_3314 |
Transform from unconstrained space to the simplex via y=exp(x)y = \exp(x) then normalizing. This is not bijective and cannot be used for HMC. However this acts mostly coordinate-wise (except for the final normalization), and thus is appropriate for coordinate-wise optimization algorithms. | |
doc_3315 |
Returns whether PyTorch is built with MKL support. | |
doc_3316 | See torch.expm1() | |
doc_3317 | Run until the future (an instance of Future) has completed. If the argument is a coroutine object it is implicitly scheduled to run as a asyncio.Task. Return the Future’s result or raise its exception. | |
doc_3318 | Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode. This method is a shorthand for certain settimeout() calls:
sock.setblocking(True) is equivalent to sock.settimeout(None)
sock.setblocking(False) is equivalent to sock.settimeout(0.0)
Changed in version 3.7: The method no longer applies SOCK_NONBLOCK flag on socket.type. | |
doc_3319 | Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class. Note that when locals are captured, they are also shown in the traceback.
__cause__
A TracebackException of the original __cause__.
__context__
A TracebackException of the original __context__.
__suppress_context__
The __suppress_context__ value from the original exception.
stack
A StackSummary representing the traceback.
exc_type
The class of the original traceback.
filename
For syntax errors - the file name where the error occurred.
lineno
For syntax errors - the line number where the error occurred.
text
For syntax errors - the text where the error occurred.
offset
For syntax errors - the offset into the text where the error occurred.
msg
For syntax errors - the compiler error message.
classmethod from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False)
Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class. Note that when locals are captured, they are also shown in the traceback.
format(*, chain=True)
Format the exception. If chain is not True, __cause__ and __context__ will not be formatted. The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file. The message indicating which exception occurred is always the last string in the output.
format_exception_only()
Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. | |
doc_3320 |
Attributes
attr repeated AttrEntry attr
device string device
experimental_debug_info ExperimentalDebugInfo experimental_debug_info
input repeated string input
name string name
op string op Child Classes class AttrEntry class ExperimentalDebugInfo | |
doc_3321 |
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_3322 | The get_list_select_related method is given the HttpRequest and should return a boolean or list as ModelAdmin.list_select_related does. | |
doc_3323 | See Migration guide for more details. tf.compat.v1.signal.dct, tf.compat.v1.spectral.dct
tf.signal.dct(
input, type=2, n=None, axis=-1, norm=None, name=None
)
Types I, II, III and IV are supported. Type I is implemented using a length 2N padded tf.signal.rfft. Type II is implemented using a length 2N padded tf.signal.rfft, as described here: Type 2 DCT using 2N FFT padded (Makhoul). Type III is a fairly straightforward inverse of Type II (i.e. using a length 2N padded tf.signal.irfft). Type IV is calculated through 2N length DCT2 of padded signal and picking the odd indices.
Args
input A [..., samples] float32/float64 Tensor containing the signals to take the DCT of.
type The DCT type to perform. Must be 1, 2, 3 or 4.
n The length of the transform. If length is less than sequence length, only the first n elements of the sequence are considered for the DCT. If n is greater than the sequence length, zeros are padded and then the DCT is computed as usual.
axis For future expansion. The axis to compute the DCT along. Must be -1.
norm The normalization to apply. None for no normalization or 'ortho' for orthonormal normalization.
name An optional name for the operation.
Returns A [..., samples] float32/float64 Tensor containing the DCT of input.
Raises
ValueError If type is not 1, 2, 3 or 4, axis is not -1, n is not None or greater than 0, or norm is not None or 'ortho'.
ValueError If type is 1 and norm is ortho. Scipy Compatibility Equivalent to scipy.fftpack.dct for Type-I, Type-II, Type-III and Type-IV DCT. | |
doc_3324 |
Indicator for whether the date is the last day of a quarter. Returns
is_quarter_end:Series or DatetimeIndex
The same type as the original data with boolean values. Series will have the same name and index. DatetimeIndex will have the same name. See also quarter
Return the quarter of the date. is_quarter_start
Similar property indicating the quarter start. Examples This method is available on Series with datetime values under the .dt accessor, and directly on DatetimeIndex.
>>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30",
... periods=4)})
>>> df.assign(quarter=df.dates.dt.quarter,
... is_quarter_end=df.dates.dt.is_quarter_end)
dates quarter is_quarter_end
0 2017-03-30 1 False
1 2017-03-31 1 True
2 2017-04-01 2 False
3 2017-04-02 2 False
>>> idx = pd.date_range('2017-03-30', periods=4)
>>> idx
DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'],
dtype='datetime64[ns]', freq='D')
>>> idx.is_quarter_end
array([False, True, False, False]) | |
doc_3325 | See Migration guide for more details. tf.compat.v1.raw_ops.ShuffleAndRepeatDataset
tf.raw_ops.ShuffleAndRepeatDataset(
input_dataset, buffer_size, seed, seed2, count, output_types, output_shapes,
reshuffle_each_iteration=True, name=None
)
pseudorandomly.
Args
input_dataset A Tensor of type variant.
buffer_size A Tensor of type int64. The number of output elements to buffer in an iterator over this dataset. Compare with the min_after_dequeue attr when creating a RandomShuffleQueue.
seed A Tensor of type int64. A scalar seed for the random number generator. If either seed or seed2 is set to be non-zero, the random number generator is seeded by the given seed. Otherwise, a random seed is used.
seed2 A Tensor of type int64. A second scalar seed to avoid seed collision.
count A Tensor of type int64. A scalar representing the number of times the underlying dataset should be repeated. The default is -1, which results in infinite repetition.
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.
reshuffle_each_iteration An optional bool. Defaults to True.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_3326 | Acquire a semaphore. When invoked without arguments: If the internal counter is larger than zero on entry, decrement it by one and return True immediately. If the internal counter is zero on entry, block until awoken by a call to release(). Once awoken (and the counter is greater than 0), decrement the counter by 1 and return True. Exactly one thread will be awoken by each call to release(). The order in which threads are awoken should not be relied on. When invoked with blocking set to false, do not block. If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True. When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return False. Return True otherwise. Changed in version 3.2: The timeout parameter is new. | |
doc_3327 |
Linear Support Vector Regression. Similar to SVR with parameter kernel=’linear’, but implemented in terms of liblinear rather than libsvm, so it has more flexibility in the choice of penalties and loss functions and should scale better to large numbers of samples. This class supports both dense and sparse input. Read more in the User Guide. New in version 0.16. Parameters
epsilonfloat, default=0.0
Epsilon parameter in the epsilon-insensitive loss function. Note that the value of this parameter depends on the scale of the target variable y. If unsure, set epsilon=0.
tolfloat, default=1e-4
Tolerance for stopping criteria.
Cfloat, default=1.0
Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive.
loss{‘epsilon_insensitive’, ‘squared_epsilon_insensitive’}, default=’epsilon_insensitive’
Specifies the loss function. The epsilon-insensitive loss (standard SVR) is the L1 loss, while the squared epsilon-insensitive loss (‘squared_epsilon_insensitive’) is the L2 loss.
fit_interceptbool, default=True
Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be already centered).
intercept_scalingfloat, default=1.
When self.fit_intercept is True, instance vector x becomes [x, self.intercept_scaling], i.e. a “synthetic” feature with constant value equals to intercept_scaling is appended to the instance vector. The intercept becomes intercept_scaling * synthetic feature weight Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased.
dualbool, default=True
Select the algorithm to either solve the dual or primal optimization problem. Prefer dual=False when n_samples > n_features.
verboseint, default=0
Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in liblinear that, if enabled, may not work properly in a multithreaded context.
random_stateint, RandomState instance or None, default=None
Controls the pseudo random number generation for shuffling the data. Pass an int for reproducible output across multiple function calls. See Glossary.
max_iterint, default=1000
The maximum number of iterations to be run. Attributes
coef_ndarray of shape (n_features) if n_classes == 2 else (n_classes, n_features)
Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel. coef_ is a readonly property derived from raw_coef_ that follows the internal memory layout of liblinear.
intercept_ndarray of shape (1) if n_classes == 2 else (n_classes)
Constants in decision function.
n_iter_int
Maximum number of iterations run across all classes. See also
LinearSVC
Implementation of Support Vector Machine classifier using the same library as this class (liblinear).
SVR
Implementation of Support Vector Machine regression using libsvm: the kernel can be non-linear but its SMO algorithm does not scale to large number of samples as LinearSVC does.
sklearn.linear_model.SGDRegressor
SGDRegressor can optimize the same cost function as LinearSVR by adjusting the penalty and loss parameters. In addition it requires less memory, allows incremental (online) learning, and implements various loss functions and regularization regimes. Examples >>> from sklearn.svm import LinearSVR
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, random_state=0)
>>> regr = make_pipeline(StandardScaler(),
... LinearSVR(random_state=0, tol=1e-5))
>>> regr.fit(X, y)
Pipeline(steps=[('standardscaler', StandardScaler()),
('linearsvr', LinearSVR(random_state=0, tol=1e-05))])
>>> print(regr.named_steps['linearsvr'].coef_)
[18.582... 27.023... 44.357... 64.522...]
>>> print(regr.named_steps['linearsvr'].intercept_)
[-4...]
>>> print(regr.predict([[0, 0, 0, 0]]))
[-2.384...]
Methods
fit(X, y[, sample_weight]) Fit the model according to the given training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit the model according to the given training data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where n_samples in the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
Target vector relative to X
sample_weightarray-like of shape (n_samples,), default=None
Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. New in version 0.18. Returns
selfobject
An instance of the estimator.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X) [source]
Predict using the linear model. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape (n_samples,)
Returns predicted values.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_3328 | Writes the object’s contents encoded to the stream. | |
doc_3329 |
Bases: matplotlib.colors.SymLogNorm The symmetrical logarithmic scale is logarithmic in both the positive and negative directions from the origin. Since the values close to zero tend toward infinity, there is a need to have a range around zero that is linear. The parameter linthresh allows the user to specify the size of this range (-linthresh, linthresh). Parameters
linthreshfloat
The range within which the plot is linear (to avoid having the plot go to infinity around zero).
linscalefloat, default: 1
This allows the linear range (-linthresh to linthresh) to be stretched relative to the logarithmic range. Its value is the number of decades to use for each half of the linear range. For example, when linscale == 1.0 (the default), the space used for the positive and negative halves of the linear range will be equal to one decade in the logarithmic range.
basefloat, default: 10
Parameters
vmin, vmaxfloat or None
If vmin and/or vmax is not given, they are initialized from the minimum and maximum value, respectively, of the first input processed; i.e., __call__(A) calls autoscale_None(A).
clipbool, default: False
If True values falling outside the range [vmin, vmax], are mapped to 0 or 1, whichever is closer, and masked values are set to 1. If False masked values remain masked. Clipping silently defeats the purpose of setting the over, under, and masked colors in a colormap, so it is likely to lead to surprises; therefore the default is clip=False. Notes Returns 0 if vmin == vmax. __call__(value, clip=None)[source]
Normalize value data in the [vmin, vmax] interval into the [0.0, 1.0] interval and return it. Parameters
value
Data to normalize.
clipbool
If None, defaults to self.clip (which defaults to False). Notes If not already initialized, self.vmin and self.vmax are initialized using self.autoscale_None(value).
inverse(value)[source]
Examples using matplotlib.colors.SymLogNorm
Colormap Normalizations
Colormap Normalizations Symlognorm
Colormap Normalization | |
doc_3330 | Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__(), which should return an Integral value. | |
doc_3331 |
Parameters
namestr
Extension name.
sourceslist of str
List of source file locations relative to the top directory of the package.
extra_compile_argslist of str
Extra command line arguments to pass to the compiler.
extra_f77_compile_argslist of str
Extra command line arguments to pass to the fortran77 compiler.
extra_f90_compile_argslist of str
Extra command line arguments to pass to the fortran90 compiler. Methods
has_cxx_sources
has_f2py_sources | |
doc_3332 |
Return a match score between stretch1 and stretch2. The result is the absolute value of the difference between the CSS numeric values of stretch1 and stretch2, normalized between 0.0 and 1.0. | |
doc_3333 | The file may not be renamed or deleted. | |
doc_3334 |
Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. See also char.isalpha | |
doc_3335 |
Return an array with the elements of a right-justified in a string of length width. Calls str.rjust element-wise. Parameters
aarray_like of str or unicode
widthint
The length of the resulting strings
fillcharstr or unicode, optional
The character to use for padding Returns
outndarray
Output array of str or unicode, depending on input type See also str.rjust | |
doc_3336 |
add_child_handler(pid, callback, *args)
Register a new child handler. Arrange for callback(pid, returncode, *args) to be called when a process with PID equal to pid terminates. Specifying another callback for the same process replaces the previous handler. The callback callable must be thread-safe.
remove_child_handler(pid)
Removes the handler for process with PID equal to pid. The function returns True if the handler was successfully removed, False if there was nothing to remove.
attach_loop(loop)
Attach the watcher to an event loop. If the watcher was previously attached to an event loop, then it is first detached before attaching to the new loop. Note: loop may be None.
is_active()
Return True if the watcher is ready to use. Spawning a subprocess with inactive current child watcher raises RuntimeError. New in version 3.8.
close()
Close the watcher. This method has to be called to ensure that underlying resources are cleaned-up. | |
doc_3337 | This member is either None or a dictionary containing Python objects that need to be kept alive so that the memory block contents is kept valid. This object is only exposed for debugging; never modify the contents of this dictionary. | |
doc_3338 |
CIE-LCH to CIE-LAB color space conversion. LCH is the cylindrical representation of the LAB (Cartesian) colorspace Parameters
lch(…, 3) array_like
The N-D image in CIE-LCH format. The last (N+1-th) dimension must have at least 3 elements, corresponding to the L, a, and b color channels. Subsequent elements are copied. Returns
out(…, 3) ndarray
The image in LAB format, with same shape as input lch. Raises
ValueError
If lch does not have at least 3 color channels (i.e. l, c, h). Examples >>> from skimage import data
>>> from skimage.color import rgb2lab, lch2lab
>>> img = data.astronaut()
>>> img_lab = rgb2lab(img)
>>> img_lch = lab2lch(img_lab)
>>> img_lab2 = lch2lab(img_lch) | |
doc_3339 |
Disconnect the callback with id cid. Examples cid = canvas.mpl_connect('button_press_event', on_press)
# ... later
canvas.mpl_disconnect(cid)
Examples using matplotlib.pyplot.disconnect
Mouse move and click events | |
doc_3340 | A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError. See get() for explanation of raw, vars and fallback. | |
doc_3341 |
Return the color of the text. | |
doc_3342 | See Migration guide for more details. tf.compat.v1.raw_ops.LogMatrixDeterminant
tf.raw_ops.LogMatrixDeterminant(
input, name=None
)
one or more square matrices. The input is a tensor of shape [N, M, M] whose inner-most 2 dimensions form square matrices. The outputs are two tensors containing the signs and absolute values of the log determinants for all N input submatrices [..., :, :] such that determinant = sign*exp(log_abs_determinant). The log_abs_determinant is computed as det(P)*sum(log(diag(LU))) where LU is the LU decomposition of the input and P is the corresponding permutation matrix.
Args
input A Tensor. Must be one of the following types: half, float32, float64, complex64, complex128. Shape is [N, M, M].
name A name for the operation (optional).
Returns A tuple of Tensor objects (sign, log_abs_determinant). sign A Tensor. Has the same type as input.
log_abs_determinant A Tensor. Has the same type as input. | |
doc_3343 | A TracebackException of the original __cause__. | |
doc_3344 |
Split an array into multiple sub-arrays as views into ary. Parameters
aryndarray
Array to be divided into sub-arrays.
indices_or_sectionsint or 1-D array
If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised. If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in ary[:2] ary[2:3] ary[3:] If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.
axisint, optional
The axis along which to split, default is 0. Returns
sub-arrayslist of ndarrays
A list of sub-arrays as views into ary. Raises
ValueError
If indices_or_sections is given as an integer, but a split does not result in equal division. See also array_split
Split an array into multiple sub-arrays of equal or near-equal size. Does not raise an exception if an equal division cannot be made. hsplit
Split array into multiple sub-arrays horizontally (column-wise). vsplit
Split array into multiple sub-arrays vertically (row wise). dsplit
Split array into multiple sub-arrays along the 3rd axis (depth). concatenate
Join a sequence of arrays along an existing axis. stack
Join a sequence of arrays along a new axis. hstack
Stack arrays in sequence horizontally (column wise). vstack
Stack arrays in sequence vertically (row wise). dstack
Stack arrays in sequence depth wise (along third dimension). Examples >>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])]
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
[array([0., 1., 2.]),
array([3., 4.]),
array([5.]),
array([6., 7.]),
array([], dtype=float64)] | |
doc_3345 | tf.compat.v1.IdentityReader(
name=None
)
To use, enqueue strings in a Queue. Read will take the front work string and output (work, work). See ReaderBase for supported methods.
Args
name A name for the operation (optional). Eager Compatibility Readers are not compatible with eager execution. Instead, please use tf.data to get data into your model.
Attributes
reader_ref Op that implements the reader.
supports_serialize Whether the Reader implementation can serialize its state. Methods num_records_produced View source
num_records_produced(
name=None
)
Returns the number of records this reader has produced. This is the same as the number of Read executions that have succeeded.
Args
name A name for the operation (optional).
Returns An int64 Tensor.
num_work_units_completed View source
num_work_units_completed(
name=None
)
Returns the number of work units this reader has finished processing.
Args
name A name for the operation (optional).
Returns An int64 Tensor.
read View source
read(
queue, name=None
)
Returns the next record (key, value) pair produced by a reader. Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file).
Args
queue A Queue or a mutable string Tensor representing a handle to a Queue, with string work items.
name A name for the operation (optional).
Returns A tuple of Tensors (key, value). key A string scalar Tensor.
value A string scalar Tensor. read_up_to View source
read_up_to(
queue, num_records, name=None
)
Returns up to num_records (key, value) pairs produced by a reader. Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num_records even before the last batch.
Args
queue A Queue or a mutable string Tensor representing a handle to a Queue, with string work items.
num_records Number of records to read.
name A name for the operation (optional).
Returns A tuple of Tensors (keys, values). keys A 1-D string Tensor.
values A 1-D string Tensor. reset View source
reset(
name=None
)
Restore a reader to its initial clean state.
Args
name A name for the operation (optional).
Returns The created Operation.
restore_state View source
restore_state(
state, name=None
)
Restore a reader to a previously saved state. Not all Readers support being restored, so this can produce an Unimplemented error.
Args
state A string Tensor. Result of a SerializeState of a Reader with matching type.
name A name for the operation (optional).
Returns The created Operation.
serialize_state View source
serialize_state(
name=None
)
Produce a string tensor that encodes the state of a reader. Not all Readers support being serialized, so this can produce an Unimplemented error.
Args
name A name for the operation (optional).
Returns A string Tensor. | |
doc_3346 | See Migration guide for more details. tf.compat.v1.math.reduce_logsumexp
tf.compat.v1.reduce_logsumexp(
input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None,
keep_dims=None
)
Warning: SOME ARGUMENTS ARE DEPRECATED: (keep_dims). They will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims instead Reduces input_tensor along the dimensions given in axis. Unless keepdims is true, the rank of the tensor is reduced by 1 for each of the entries in axis, which must be unique. If keepdims is true, the reduced dimensions are retained with length 1. If axis has no entries, all dimensions are reduced, and a tensor with a single element is returned. This function is more numerically stable than log(sum(exp(input))). It avoids overflows caused by taking the exp of large inputs and underflows caused by taking the log of small inputs. For example: x = tf.constant([[0., 0., 0.], [0., 0., 0.]])
tf.reduce_logsumexp(x) # log(6)
tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)]
tf.reduce_logsumexp(x, 1) # [log(3), log(3)]
tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]]
tf.reduce_logsumexp(x, [0, 1]) # log(6)
Args
input_tensor The tensor to reduce. Should have numeric type.
axis The dimensions to reduce. If None (the default), reduces all dimensions. Must be in the range [-rank(input_tensor), rank(input_tensor)).
keepdims If true, retains reduced dimensions with length 1.
name A name for the operation (optional).
reduction_indices The old (deprecated) name for axis.
keep_dims Deprecated alias for keepdims.
Returns The reduced tensor. | |
doc_3347 | class sklearn.kernel_approximation.Nystroem(kernel='rbf', *, gamma=None, coef0=None, degree=None, kernel_params=None, n_components=100, random_state=None, n_jobs=None) [source]
Approximate a kernel map using a subset of the training data. Constructs an approximate feature map for an arbitrary kernel using a subset of the data as basis. Read more in the User Guide. New in version 0.13. Parameters
kernelstring or callable, default=’rbf’
Kernel map to be approximated. A callable should accept two arguments and the keyword arguments passed to this object as kernel_params, and should return a floating point number.
gammafloat, default=None
Gamma parameter for the RBF, laplacian, polynomial, exponential chi2 and sigmoid kernels. Interpretation of the default value is left to the kernel; see the documentation for sklearn.metrics.pairwise. Ignored by other kernels.
coef0float, default=None
Zero coefficient for polynomial and sigmoid kernels. Ignored by other kernels.
degreefloat, default=None
Degree of the polynomial kernel. Ignored by other kernels.
kernel_paramsdict, default=None
Additional parameters (keyword arguments) for kernel function passed as callable object.
n_componentsint, default=100
Number of features to construct. How many data points will be used to construct the mapping.
random_stateint, RandomState instance or None, default=None
Pseudo-random number generator to control the uniform sampling without replacement of n_components of the training data to construct the basis kernel. Pass an int for reproducible output across multiple function calls. See Glossary.
n_jobsint, default=None
The number of jobs to use for the computation. This works by breaking down the kernel matrix into n_jobs even slices and computing them in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. New in version 0.24. Attributes
components_ndarray of shape (n_components, n_features)
Subset of training points used to construct the feature map.
component_indices_ndarray of shape (n_components)
Indices of components_ in the training set.
normalization_ndarray of shape (n_components, n_components)
Normalization matrix needed for embedding. Square root of the kernel matrix on components_. See also
RBFSampler
An approximation to the RBF kernel using random Fourier features.
sklearn.metrics.pairwise.kernel_metrics
List of built-in kernels. References Williams, C.K.I. and Seeger, M. “Using the Nystroem method to speed up kernel machines”, Advances in neural information processing systems 2001 T. Yang, Y. Li, M. Mahdavi, R. Jin and Z. Zhou “Nystroem Method vs Random Fourier Features: A Theoretical and Empirical Comparison”, Advances in Neural Information Processing Systems 2012 Examples >>> from sklearn import datasets, svm
>>> from sklearn.kernel_approximation import Nystroem
>>> X, y = datasets.load_digits(n_class=9, return_X_y=True)
>>> data = X / 16.
>>> clf = svm.LinearSVC()
>>> feature_map_nystroem = Nystroem(gamma=.2,
... random_state=1,
... n_components=300)
>>> data_transformed = feature_map_nystroem.fit_transform(data)
>>> clf.fit(data_transformed, y)
LinearSVC()
>>> clf.score(data_transformed, y)
0.9987...
Methods
fit(X[, y]) Fit estimator to data.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
transform(X) Apply feature map to X.
fit(X, y=None) [source]
Fit estimator to data. Samples a subset of training points, computes kernel on these and computes normalization matrix. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
transform(X) [source]
Apply feature map to X. Computes an approximate feature map using the kernel between some training points and X. Parameters
Xarray-like of shape (n_samples, n_features)
Data to transform. Returns
X_transformedndarray of shape (n_samples, n_components)
Transformed data.
Examples using sklearn.kernel_approximation.Nystroem
Explicit feature map approximation for RBF kernels | |
doc_3348 |
Return a flattened array. Refer to numpy.ravel for full documentation. See also numpy.ravel
equivalent function ndarray.flat
a flat iterator on the array. | |
doc_3349 | Return True if the feature identified by the pair of strings feature and version is implemented. | |
doc_3350 | Creates an exclusion constraint in the database. Internally, PostgreSQL implements exclusion constraints using indexes. The default index type is GiST. To use them, you need to activate the btree_gist extension on PostgreSQL. You can install it using the BtreeGistExtension migration operation. If you attempt to insert a new row that conflicts with an existing row, an IntegrityError is raised. Similarly, when update conflicts with an existing row. | |
doc_3351 | Wait until all output written to file descriptor fd has been transmitted. | |
doc_3352 | tf.data.experimental.make_csv_dataset(
file_pattern, batch_size, column_names=None, column_defaults=None,
label_name=None, select_columns=None, field_delim=',',
use_quote_delim=True, na_value='', header=True, num_epochs=None,
shuffle=True, shuffle_buffer_size=10000, shuffle_seed=None,
prefetch_buffer_size=None, num_parallel_reads=None, sloppy=False,
num_rows_for_inference=100, compression_type=None, ignore_errors=False
)
Reads CSV files into a dataset, where each element is a (features, labels) tuple that corresponds to a batch of CSV rows. The features dictionary maps feature column names to Tensors containing the corresponding feature data, and labels is a Tensor containing the batch's label data.
Args
file_pattern List of files or patterns of file paths containing CSV records. See tf.io.gfile.glob for pattern rules.
batch_size An int representing the number of records to combine in a single batch.
column_names An optional list of strings that corresponds to the CSV columns, in order. One per column of the input record. If this is not provided, infers the column names from the first row of the records. These names will be the keys of the features dict of each dataset element.
column_defaults A optional list of default values for the CSV fields. One item per selected column of the input record. Each item in the list is either a valid CSV dtype (float32, float64, int32, int64, or string), or a Tensor with one of the aforementioned types. The tensor can either be a scalar default value (if the column is optional), or an empty tensor (if the column is required). If a dtype is provided instead of a tensor, the column is also treated as required. If this list is not provided, tries to infer types based on reading the first num_rows_for_inference rows of files specified, and assumes all columns are optional, defaulting to 0 for numeric values and "" for string values. If both this and select_columns are specified, these must have the same lengths, and column_defaults is assumed to be sorted in order of increasing column index.
label_name A optional string corresponding to the label column. If provided, the data for this column is returned as a separate Tensor from the features dictionary, so that the dataset complies with the format expected by a tf.Estimator.train or tf.Estimator.evaluate input function.
select_columns An optional list of integer indices or string column names, that specifies a subset of columns of CSV data to select. If column names are provided, these must correspond to names provided in column_names or inferred from the file header lines. When this argument is specified, only a subset of CSV columns will be parsed and returned, corresponding to the columns specified. Using this results in faster parsing and lower memory usage. If both this and column_defaults are specified, these must have the same lengths, and column_defaults is assumed to be sorted in order of increasing column index.
field_delim An optional string. Defaults to ",". Char delimiter to separate fields in a record.
use_quote_delim An optional bool. Defaults to True. If false, treats double quotation marks as regular characters inside of the string fields.
na_value Additional string to recognize as NA/NaN.
header A bool that indicates whether the first rows of provided CSV files correspond to header lines with column names, and should not be included in the data.
num_epochs An int specifying the number of times this dataset is repeated. If None, cycles through the dataset forever.
shuffle A bool that indicates whether the input should be shuffled.
shuffle_buffer_size Buffer size to use for shuffling. A large buffer size ensures better shuffling, but increases memory usage and startup time.
shuffle_seed Randomization seed to use for shuffling.
prefetch_buffer_size An int specifying the number of feature batches to prefetch for performance improvement. Recommended value is the number of batches consumed per training step. Defaults to auto-tune.
num_parallel_reads Number of threads used to read CSV records from files. If >1, the results will be interleaved. Defaults to 1.
sloppy If True, reading performance will be improved at the cost of non-deterministic ordering. If False, the order of elements produced is deterministic prior to shuffling (elements are still randomized if shuffle=True. Note that if the seed is set, then order of elements after shuffling is deterministic). Defaults to False.
num_rows_for_inference Number of rows of a file to use for type inference if record_defaults is not provided. If None, reads all the rows of all the files. Defaults to 100.
compression_type (Optional.) A tf.string scalar evaluating to one of "" (no compression), "ZLIB", or "GZIP". Defaults to no compression.
ignore_errors (Optional.) If True, ignores errors with CSV file parsing, such as malformed data or empty lines, and moves on to the next valid CSV record. Otherwise, the dataset raises an error and stops processing when encountering any invalid records. Defaults to False.
Returns A dataset, where each element is a (features, labels) tuple that corresponds to a batch of batch_size CSV rows. The features dictionary maps feature column names to Tensors containing the corresponding column data, and labels is a Tensor containing the column data for the label column specified by label_name.
Raises
ValueError If any of the arguments is malformed. | |
doc_3353 |
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description. | |
doc_3354 | Returns the filtered dictionary of local variables for the given traceback frame. Sensitive values are replaced with cleansed_substitute. | |
doc_3355 |
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array. | |
doc_3356 | Registers a forward hook on the module. The hook will be called every time after forward() has computed an output. It should have the following signature: hook(module, input, output) -> None or modified output
The input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after forward() is called. Returns
a handle that can be used to remove the added hook by calling handle.remove() Return type
torch.utils.hooks.RemovableHandle | |
doc_3357 | Returns True if the specified item is present in the tree. | |
doc_3358 |
Set the (group) id for the artist. Parameters
gidstr | |
doc_3359 | tf.optimizers.schedules.PolynomialDecay Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.optimizers.schedules.PolynomialDecay
tf.keras.optimizers.schedules.PolynomialDecay(
initial_learning_rate, decay_steps, end_learning_rate=0.0001, power=1.0,
cycle=False, name=None
)
It is commonly observed that a monotonically decreasing learning rate, whose degree of change is carefully chosen, results in a better performing model. This schedule applies a polynomial decay function to an optimizer step, given a provided initial_learning_rate, to reach an end_learning_rate in the given decay_steps. It requires a step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step. The schedule is a 1-arg callable that produces a decayed learning rate when passed the current optimizer step. This can be useful for changing the learning rate value across different invocations of optimizer functions. It is computed as: def decayed_learning_rate(step):
step = min(step, decay_steps)
return ((initial_learning_rate - end_learning_rate) *
(1 - step / decay_steps) ^ (power)
) + end_learning_rate
If cycle is True then a multiple of decay_steps is used, the first one that is bigger than step. def decayed_learning_rate(step):
decay_steps = decay_steps * ceil(step / decay_steps)
return ((initial_learning_rate - end_learning_rate) *
(1 - step / decay_steps) ^ (power)
) + end_learning_rate
You can pass this schedule directly into a tf.keras.optimizers.Optimizer as the learning rate. Example: Fit a model while decaying from 0.1 to 0.01 in 10000 steps using sqrt (i.e. power=0.5): ...
starter_learning_rate = 0.1
end_learning_rate = 0.01
decay_steps = 10000
learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(
starter_learning_rate,
decay_steps,
end_learning_rate,
power=0.5)
model.compile(optimizer=tf.keras.optimizers.SGD(
learning_rate=learning_rate_fn),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(data, labels, epochs=5)
The learning rate schedule is also serializable and deserializable using tf.keras.optimizers.schedules.serialize and tf.keras.optimizers.schedules.deserialize.
Returns A 1-arg callable learning rate schedule that takes the current optimizer step and outputs the decayed learning rate, a scalar Tensor of the same type as initial_learning_rate.
Args
initial_learning_rate A scalar float32 or float64 Tensor or a Python number. The initial learning rate.
decay_steps A scalar int32 or int64 Tensor or a Python number. Must be positive. See the decay computation above.
end_learning_rate A scalar float32 or float64 Tensor or a Python number. The minimal end learning rate.
power A scalar float32 or float64 Tensor or a Python number. The power of the polynomial. Defaults to linear, 1.0.
cycle A boolean, whether or not it should cycle beyond decay_steps.
name String. Optional name of the operation. Defaults to 'PolynomialDecay'. Methods from_config View source
@classmethod
from_config(
config
)
Instantiates a LearningRateSchedule from its config.
Args
config Output of get_config().
Returns A LearningRateSchedule instance.
get_config View source
get_config()
__call__ View source
__call__(
step
)
Call self as a function. | |
doc_3360 | Return a string containing the “info” for a message. This is useful for accessing and modifying “info” that is experimental (i.e., not a list of flags). | |
doc_3361 | Takes a variadic number of model classes, and returns a dictionary mapping the model classes to the ContentType instances representing them. for_concrete_models=False allows fetching the ContentType of proxy models. | |
doc_3362 | These control the range of values permitted in the field. | |
doc_3363 |
Some classes may want to replace a hyphen for minus with the proper unicode symbol (U+2212) for typographical correctness. This is a helper method to perform such a replacement when it is enabled via rcParams["axes.unicode_minus"] (default: True). | |
doc_3364 | Prevents re-use of the same DH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets. New in version 3.3. | |
doc_3365 | bytearray.center(width[, fillbyte])
Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s). Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | |
doc_3366 |
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate. | |
doc_3367 |
Draw samples from a logistic distribution. Samples are drawn from a logistic distribution with specified parameters, loc (location or mean, also median), and scale (>0). Parameters
locfloat or array_like of floats, optional
Parameter of the distribution. Default is 0.
scalefloat or array_like of floats, optional
Parameter of the distribution. Must be non-negative. Default is 1.
sizeint or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn. Returns
outndarray or scalar
Drawn samples from the parameterized logistic distribution. See also scipy.stats.logistic
probability density function, distribution or cumulative density function, etc. Notes The probability density for the Logistic distribution is \[P(x) = P(x) = \frac{e^{-(x-\mu)/s}}{s(1+e^{-(x-\mu)/s})^2},\] where \(\mu\) = location and \(s\) = scale. The Logistic distribution is used in Extreme Value problems where it can act as a mixture of Gumbel distributions, in Epidemiology, and by the World Chess Federation (FIDE) where it is used in the Elo ranking system, assuming the performance of each player is a logistically distributed random variable. References 1
Reiss, R.-D. and Thomas M. (2001), “Statistical Analysis of Extreme Values, from Insurance, Finance, Hydrology and Other Fields,” Birkhauser Verlag, Basel, pp 132-133. 2
Weisstein, Eric W. “Logistic Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LogisticDistribution.html 3
Wikipedia, “Logistic-distribution”, https://en.wikipedia.org/wiki/Logistic_distribution Examples Draw samples from the distribution: >>> loc, scale = 10, 1
>>> s = np.random.default_rng().logistic(loc, scale, 10000)
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, bins=50)
# plot against distribution >>> def logist(x, loc, scale):
... return np.exp((loc-x)/scale)/(scale*(1+np.exp((loc-x)/scale))**2)
>>> lgst_val = logist(bins, loc, scale)
>>> plt.plot(bins, lgst_val * count.max() / lgst_val.max())
>>> plt.show() | |
doc_3368 |
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_3369 | A field which accepts JSON encoded data for a JSONField. Default widget: Textarea
Empty value: None
Normalizes to: A Python representation of the JSON value (usually as a dict, list, or None), depending on JSONField.decoder. Validates that the given value is a valid JSON. Error message keys: required, invalid
Takes two optional arguments:
encoder
A json.JSONEncoder subclass to serialize data types not supported by the standard JSON serializer (e.g. datetime.datetime or UUID). For example, you can use the DjangoJSONEncoder class. Defaults to json.JSONEncoder.
decoder
A json.JSONDecoder subclass to deserialize the input. Your deserialization may need to account for the fact that you can’t be certain of the input type. For example, you run the risk of returning a datetime that was actually a string that just happened to be in the same format chosen for datetimes. The decoder can be used to validate the input. If json.JSONDecodeError is raised during the deserialization, a ValidationError will be raised. Defaults to json.JSONDecoder.
Note If you use a ModelForm, the encoder and decoder from JSONField will be used. User friendly forms JSONField is not particularly user friendly in most cases. However, it is a useful way to format data from a client-side widget for submission to the server. | |
doc_3370 | This function takes the current request and the updated user object from which the new session hash will be derived and updates the session hash appropriately. It also rotates the session key so that a stolen session cookie will be invalidated. Example usage: from django.contrib.auth import update_session_auth_hash
def password_change(request):
if request.method == 'POST':
form = PasswordChangeForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
else:
... | |
doc_3371 | The “no data” value for a band is generally a special marker value used to mark pixels that are not valid data. Such pixels should generally not be displayed, nor contribute to analysis operations. To delete an existing “no data” value, set this property to None (requires GDAL ≥ 2.1). | |
doc_3372 |
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_3373 | tf.train.experimental.DynamicLossScale Compat aliases for migration See Migration guide for more details. tf.compat.v1.mixed_precision.DynamicLossScale, tf.compat.v1.mixed_precision.experimental.DynamicLossScale, tf.compat.v1.train.experimental.DynamicLossScale
tf.mixed_precision.experimental.DynamicLossScale(
initial_loss_scale=(2 ** 15), increment_period=2000, multiplier=2.0
)
Warning: This class is deprecated and will be unexposed from the TF 2 namespace starting in TensorFlow 2.5. In TensorFlow 2.5, this class will only be accessible as tf.compat.v1.mixed_precision.DynamicLossScale. Additionally in 2.5, you will no longer be able to pass a DynamicLossScale to a tf.keras.mixed_precision.Policy. All the functionality in this class has been merged into tf.keras.mixed_precision.LossScaleOptimizer, so this class is no longer needed. Dynamic loss scaling works by adjusting the loss scale as training progresses. The goal is to keep the loss scale as high as possible without overflowing the gradients. As long as the gradients do not overflow, raising the loss scale never hurts. The algorithm starts by setting the loss scale to an initial value. Every N steps that the gradients are finite, the loss scale is increased by some factor. However, if a NaN or Inf gradient is found, the gradients for that step are not applied, and the loss scale is decreased by the factor. This process tends to keep the loss scale as high as possible without gradients overflowing.
Args
initial_loss_scale A Python float. The loss scale to use at the beginning. It's better to start this at a very high number, because a loss scale that is too high gets lowered far more quickly than a loss scale that is too low gets raised. The default is 2 ** 15, which is approximately half the maximum float16 value.
increment_period Increases loss scale every increment_period consecutive steps that finite gradients are encountered. If a nonfinite gradient is encountered, the count is reset back to zero.
multiplier The multiplier to use when increasing or decreasing the loss scale.
Attributes
increment_period
initial_loss_scale
multiplier
Methods from_config View source
@classmethod
from_config(
config
)
Creates the LossScale from its config. get_config View source
get_config()
Returns the config of this loss scale. update View source
update(
grads
)
Updates loss scale based on if gradients are finite in current step. __call__ View source
__call__()
Returns the current loss scale as a scalar float32 tensor. | |
doc_3374 |
Roll provided date backward to next offset only if not on offset. Returns
TimeStamp
Rolled timestamp if not on offset, otherwise unchanged timestamp. | |
doc_3375 | tf.compat.v1.train.MonitoredTrainingSession(
master='', is_chief=True, checkpoint_dir=None, scaffold=None,
hooks=None, chief_only_hooks=None, save_checkpoint_secs=USE_DEFAULT,
save_summaries_steps=USE_DEFAULT, save_summaries_secs=USE_DEFAULT, config=None,
stop_grace_period_secs=120, log_step_count_steps=100, max_wait_secs=7200,
save_checkpoint_steps=USE_DEFAULT, summary_dir=None, save_graph_def=True
)
For a chief, this utility sets proper session initializer/restorer. It also creates hooks related to checkpoint and summary saving. For workers, this utility sets proper session creator which waits for the chief to initialize/restore. Please check tf.compat.v1.train.MonitoredSession for more information.
Args
master String the TensorFlow master to use.
is_chief If True, it will take care of initialization and recovery the underlying TensorFlow session. If False, it will wait on a chief to initialize or recover the TensorFlow session.
checkpoint_dir A string. Optional path to a directory where to restore variables.
scaffold A Scaffold used for gathering or building supportive ops. If not specified, a default one is created. It's used to finalize the graph.
hooks Optional list of SessionRunHook objects.
chief_only_hooks list of SessionRunHook objects. Activate these hooks if is_chief==True, ignore otherwise.
save_checkpoint_secs The frequency, in seconds, that a checkpoint is saved using a default checkpoint saver. If both save_checkpoint_steps and save_checkpoint_secs are set to None, then the default checkpoint saver isn't used. If both are provided, then only save_checkpoint_secs is used. Default 600.
save_summaries_steps The frequency, in number of global steps, that the summaries are written to disk using a default summary saver. If both save_summaries_steps and save_summaries_secs are set to None, then the default summary saver isn't used. Default 100.
save_summaries_secs The frequency, in secs, that the summaries are written to disk using a default summary saver. If both save_summaries_steps and save_summaries_secs are set to None, then the default summary saver isn't used. Default not enabled.
config an instance of tf.compat.v1.ConfigProto proto used to configure the session. It's the config argument of constructor of tf.compat.v1.Session.
stop_grace_period_secs Number of seconds given to threads to stop after close() has been called.
log_step_count_steps The frequency, in number of global steps, that the global step/sec is logged.
max_wait_secs Maximum time workers should wait for the session to become available. This should be kept relatively short to help detect incorrect code, but sometimes may need to be increased if the chief takes a while to start up.
save_checkpoint_steps The frequency, in number of global steps, that a checkpoint is saved using a default checkpoint saver. If both save_checkpoint_steps and save_checkpoint_secs are set to None, then the default checkpoint saver isn't used. If both are provided, then only save_checkpoint_secs is used. Default not enabled.
summary_dir A string. Optional path to a directory where to save summaries. If None, checkpoint_dir is used instead.
save_graph_def Whether to save the GraphDef and MetaGraphDef to checkpoint_dir. The GraphDef is saved after the session is created as graph.pbtxt. MetaGraphDefs are saved out for every checkpoint as model.ckpt-*.meta.
Returns A MonitoredSession object. | |
doc_3376 |
Gaussian Mixture. Representation of a Gaussian mixture model probability distribution. This class allows to estimate the parameters of a Gaussian mixture distribution. Read more in the User Guide. New in version 0.18. Parameters
n_componentsint, default=1
The number of mixture components.
covariance_type{‘full’, ‘tied’, ‘diag’, ‘spherical’}, default=’full’
String describing the type of covariance parameters to use. Must be one of: ‘full’
each component has its own general covariance matrix ‘tied’
all components share the same general covariance matrix ‘diag’
each component has its own diagonal covariance matrix ‘spherical’
each component has its own single variance
tolfloat, default=1e-3
The convergence threshold. EM iterations will stop when the lower bound average gain is below this threshold.
reg_covarfloat, default=1e-6
Non-negative regularization added to the diagonal of covariance. Allows to assure that the covariance matrices are all positive.
max_iterint, default=100
The number of EM iterations to perform.
n_initint, default=1
The number of initializations to perform. The best results are kept.
init_params{‘kmeans’, ‘random’}, default=’kmeans’
The method used to initialize the weights, the means and the precisions. Must be one of: 'kmeans' : responsibilities are initialized using kmeans.
'random' : responsibilities are initialized randomly.
weights_initarray-like of shape (n_components, ), default=None
The user-provided initial weights. If it is None, weights are initialized using the init_params method.
means_initarray-like of shape (n_components, n_features), default=None
The user-provided initial means, If it is None, means are initialized using the init_params method.
precisions_initarray-like, default=None
The user-provided initial precisions (inverse of the covariance matrices). If it is None, precisions are initialized using the ‘init_params’ method. The shape depends on ‘covariance_type’: (n_components,) if 'spherical',
(n_features, n_features) if 'tied',
(n_components, n_features) if 'diag',
(n_components, n_features, n_features) if 'full'
random_stateint, RandomState instance or None, default=None
Controls the random seed given to the method chosen to initialize the parameters (see init_params). In addition, it controls the generation of random samples from the fitted distribution (see the method sample). Pass an int for reproducible output across multiple function calls. See Glossary.
warm_startbool, default=False
If ‘warm_start’ is True, the solution of the last fitting is used as initialization for the next call of fit(). This can speed up convergence when fit is called several times on similar problems. In that case, ‘n_init’ is ignored and only a single initialization occurs upon the first call. See the Glossary.
verboseint, default=0
Enable verbose output. If 1 then it prints the current initialization and each iteration step. If greater than 1 then it prints also the log probability and the time needed for each step.
verbose_intervalint, default=10
Number of iteration done before the next print. Attributes
weights_array-like of shape (n_components,)
The weights of each mixture components.
means_array-like of shape (n_components, n_features)
The mean of each mixture component.
covariances_array-like
The covariance of each mixture component. The shape depends on covariance_type: (n_components,) if 'spherical',
(n_features, n_features) if 'tied',
(n_components, n_features) if 'diag',
(n_components, n_features, n_features) if 'full'
precisions_array-like
The precision matrices for each component in the mixture. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,) if 'spherical',
(n_features, n_features) if 'tied',
(n_components, n_features) if 'diag',
(n_components, n_features, n_features) if 'full'
precisions_cholesky_array-like
The cholesky decomposition of the precision matrices of each mixture component. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,) if 'spherical',
(n_features, n_features) if 'tied',
(n_components, n_features) if 'diag',
(n_components, n_features, n_features) if 'full'
converged_bool
True when convergence was reached in fit(), False otherwise.
n_iter_int
Number of step used by the best fit of EM to reach the convergence.
lower_bound_float
Lower bound value on the log-likelihood (of the training data with respect to the model) of the best fit of EM. See also
BayesianGaussianMixture
Gaussian mixture model fit with a variational inference. Examples >>> import numpy as np
>>> from sklearn.mixture import GaussianMixture
>>> X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
>>> gm = GaussianMixture(n_components=2, random_state=0).fit(X)
>>> gm.means_
array([[10., 2.],
[ 1., 2.]])
>>> gm.predict([[0, 0], [12, 3]])
array([1, 0])
Methods
aic(X) Akaike information criterion for the current model on the input X.
bic(X) Bayesian information criterion for the current model on the input X.
fit(X[, y]) Estimate model parameters with the EM algorithm.
fit_predict(X[, y]) Estimate model parameters using X and predict the labels for X.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the labels for the data samples in X using trained model.
predict_proba(X) Predict posterior probability of each component given the data.
sample([n_samples]) Generate random samples from the fitted Gaussian distribution.
score(X[, y]) Compute the per-sample average log-likelihood of the given data X.
score_samples(X) Compute the weighted log probabilities for each sample.
set_params(**params) Set the parameters of this estimator.
aic(X) [source]
Akaike information criterion for the current model on the input X. Parameters
Xarray of shape (n_samples, n_dimensions)
Returns
aicfloat
The lower the better.
bic(X) [source]
Bayesian information criterion for the current model on the input X. Parameters
Xarray of shape (n_samples, n_dimensions)
Returns
bicfloat
The lower the better.
fit(X, y=None) [source]
Estimate model parameters with the EM algorithm. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. If warm_start is True, then n_init is ignored and a single initialization is performed upon the first call. Upon consecutive calls, training starts where it left off. Parameters
Xarray-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row corresponds to a single data point. Returns
self
fit_predict(X, y=None) [source]
Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. After fitting, it predicts the most probable label for the input data points. New in version 0.20. Parameters
Xarray-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row corresponds to a single data point. Returns
labelsarray, shape (n_samples,)
Component labels.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X) [source]
Predict the labels for the data samples in X using trained model. Parameters
Xarray-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row corresponds to a single data point. Returns
labelsarray, shape (n_samples,)
Component labels.
predict_proba(X) [source]
Predict posterior probability of each component given the data. Parameters
Xarray-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row corresponds to a single data point. Returns
resparray, shape (n_samples, n_components)
Returns the probability each Gaussian (state) in the model given each sample.
sample(n_samples=1) [source]
Generate random samples from the fitted Gaussian distribution. Parameters
n_samplesint, default=1
Number of samples to generate. Returns
Xarray, shape (n_samples, n_features)
Randomly generated sample
yarray, shape (nsamples,)
Component labels
score(X, y=None) [source]
Compute the per-sample average log-likelihood of the given data X. Parameters
Xarray-like of shape (n_samples, n_dimensions)
List of n_features-dimensional data points. Each row corresponds to a single data point. Returns
log_likelihoodfloat
Log likelihood of the Gaussian mixture given X.
score_samples(X) [source]
Compute the weighted log probabilities for each sample. Parameters
Xarray-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row corresponds to a single data point. Returns
log_probarray, shape (n_samples,)
Log probabilities of each data point in X.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_3377 |
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. | |
doc_3378 |
Return self%=value. | |
doc_3379 | Is True if the stream is closed. | |
doc_3380 | tf.compat.v1.metrics.root_mean_squared_error(
labels, predictions, weights=None, metrics_collections=None,
updates_collections=None, name=None
)
The root_mean_squared_error function creates two local variables, total and count that are used to compute the root mean squared error. This average is weighted by weights, and it is ultimately returned as root_mean_squared_error: an idempotent operation that takes the square root of the division of total by count. For estimation of the metric over a stream of data, the function creates an update_op operation that updates these variables and returns the root_mean_squared_error. Internally, a squared_error operation computes the element-wise square of the difference between predictions and labels. Then update_op increments total with the reduced sum of the product of weights and squared_error, and it increments count with the reduced sum of weights. If weights is None, weights default to 1. Use weights of 0 to mask values.
Args
labels A Tensor of the same shape as predictions.
predictions A Tensor of arbitrary shape.
weights Optional Tensor whose rank is either 0, or the same rank as labels, and must be broadcastable to labels (i.e., all dimensions must be either 1, or the same as the corresponding labels dimension).
metrics_collections An optional list of collections that root_mean_squared_error should be added to.
updates_collections An optional list of collections that update_op should be added to.
name An optional variable_scope name.
Returns
root_mean_squared_error A Tensor representing the current mean, the value of total divided by count.
update_op An operation that increments the total and count variables appropriately and whose value matches root_mean_squared_error.
Raises
ValueError If predictions and labels have mismatched shapes, or if weights is not None and its shape doesn't match predictions, or if either metrics_collections or updates_collections are not a list or tuple.
RuntimeError If eager execution is enabled. | |
doc_3381 | operator.__abs__(obj)
Return the absolute value of obj. | |
doc_3382 | Get the list of Nodes that constitute this Graph. Note that this Node list representation is a doubly-linked list. Mutations during iteration (e.g. delete a Node, add a Node) are safe. Returns
A doubly-linked list of Nodes. Note that reversed can be called on this list to switch iteration order. | |
doc_3383 | tf.initializers.deserialize Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.initializers.deserialize
tf.keras.initializers.deserialize(
config, custom_objects=None
) | |
doc_3384 | Token value for "/=". | |
doc_3385 |
Define how the connection between two line segments is drawn. For a visual impression of each JoinStyle, view these docs online, or run JoinStyle.demo. Lines in Matplotlib are typically defined by a 1D Path and a finite linewidth, where the underlying 1D Path represents the center of the stroked line. By default, GraphicsContextBase defines the boundaries of a stroked line to simply be every point within some radius, linewidth/2, away from any point of the center line. However, this results in corners appearing "rounded", which may not be the desired behavior if you are drawing, for example, a polygon or pointed star. Supported values: 'miter'
the "arrow-tip" style. Each boundary of the filled-in area will extend in a straight line parallel to the tangent vector of the centerline at the point it meets the corner, until they meet in a sharp point. 'round'
stokes every point within a radius of linewidth/2 of the center lines. 'bevel'
the "squared-off" style. It can be thought of as a rounded corner where the "circular" part of the corner has been cut off. Note Very long miter tips are cut off (to form a bevel) after a backend-dependent limit called the "miter limit", which specifies the maximum allowed ratio of miter length to line width. For example, the PDF backend uses the default value of 10 specified by the PDF standard, while the SVG backend does not even specify the miter limit, resulting in a default value of 4 per the SVG specification. Matplotlib does not currently allow the user to adjust this parameter. A more detailed description of the effect of a miter limit can be found in the Mozilla Developer Docs (Source code, png, pdf) staticdemo()[source]
Demonstrate how each JoinStyle looks for various join angles.
classmatplotlib._enums.CapStyle(value)[source]
Define how the two endpoints (caps) of an unclosed line are drawn. How to draw the start and end points of lines that represent a closed curve (i.e. that end in a CLOSEPOLY) is controlled by the line's JoinStyle. For all other lines, how the start and end points are drawn is controlled by the CapStyle. For a visual impression of each CapStyle, view these docs online or run CapStyle.demo. Supported values: 'butt'
the line is squared off at its endpoint. 'projecting'
the line is squared off as in butt, but the filled in area extends beyond the endpoint a distance of linewidth/2. 'round'
like butt, but a semicircular cap is added to the end of the line, of radius linewidth/2. (Source code, png, pdf) staticdemo()[source]
Demonstrate how each CapStyle looks for a thick line segment. | |
doc_3386 |
Container for manipulating Callgrind results. It supports:
Addition and subtraction to combine or diff results. Tuple-like indexing. A denoise function which strips CPython calls which are known to be non-deterministic and quite noisy. Two higher order methods (filter and transform) for custom manipulation.
denoise() [source]
Remove known noisy instructions. Several instructions in the CPython interpreter are rather noisy. These instructions involve unicode to dictionary lookups which Python uses to map variable names. FunctionCounts is generally a content agnostic container, however this is sufficiently important for obtaining reliable results to warrant an exception.
filter(filter_fn) [source]
Keep only the elements where filter_fn applied to function name returns True.
transform(map_fn) [source]
Apply map_fn to all of the function names. This can be used to regularize function names (e.g. stripping irrelevant parts of the file path), coalesce entries by mapping multiple functions to the same name (in which case the counts are added together), etc. | |
doc_3387 | """
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_3388 | tf.summary.experimental.get_step()
Returns The step set by tf.summary.experimental.set_step() if one has been set, otherwise None. | |
doc_3389 |
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly. | |
doc_3390 | Represents the C 64-bit signed int datatype. Usually an alias for c_longlong. | |
doc_3391 |
Check if indexer is a valid array indexer for array. For a boolean mask, array and indexer are checked to have the same length. The dtype is validated, and if it is an integer or boolean ExtensionArray, it is checked if there are missing values present, and it is converted to the appropriate numpy array. Other dtypes will raise an error. Non-array indexers (integer, slice, Ellipsis, tuples, ..) are passed through as is. New in version 1.0.0. Parameters
array:array-like
The array that is being indexed (only used for the length).
indexer:array-like or list-like
The array-like that’s used to index. List-like input that is not yet a numpy array or an ExtensionArray is converted to one. Other input types are passed through as is. Returns
numpy.ndarray
The validated indexer as a numpy array that can be used to index. Raises
IndexError
When the lengths don’t match. ValueError
When indexer cannot be converted to a numpy ndarray to index (e.g. presence of missing values). See also api.types.is_bool_dtype
Check if key is of boolean dtype. Examples When checking a boolean mask, a boolean ndarray is returned when the arguments are all valid.
>>> mask = pd.array([True, False])
>>> arr = pd.array([1, 2])
>>> pd.api.indexers.check_array_indexer(arr, mask)
array([ True, False])
An IndexError is raised when the lengths don’t match.
>>> mask = pd.array([True, False, True])
>>> pd.api.indexers.check_array_indexer(arr, mask)
Traceback (most recent call last):
...
IndexError: Boolean index has wrong length: 3 instead of 2.
NA values in a boolean array are treated as False.
>>> mask = pd.array([True, pd.NA])
>>> pd.api.indexers.check_array_indexer(arr, mask)
array([ True, False])
A numpy boolean mask will get passed through (if the length is correct):
>>> mask = np.array([True, False])
>>> pd.api.indexers.check_array_indexer(arr, mask)
array([ True, False])
Similarly for integer indexers, an integer ndarray is returned when it is a valid indexer, otherwise an error is (for integer indexers, a matching length is not required):
>>> indexer = pd.array([0, 2], dtype="Int64")
>>> arr = pd.array([1, 2, 3])
>>> pd.api.indexers.check_array_indexer(arr, indexer)
array([0, 2])
>>> indexer = pd.array([0, pd.NA], dtype="Int64")
>>> pd.api.indexers.check_array_indexer(arr, indexer)
Traceback (most recent call last):
...
ValueError: Cannot index with an integer indexer containing NA values
For non-integer/boolean dtypes, an appropriate error is raised:
>>> indexer = np.array([0., 2.], dtype="float64")
>>> pd.api.indexers.check_array_indexer(arr, indexer)
Traceback (most recent call last):
...
IndexError: arrays used as indices must be of integer or boolean type | |
doc_3392 | tf.compat.v1.to_double(
x, name='ToDouble'
)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.cast instead.
Args
x A Tensor or SparseTensor or IndexedSlices.
name A name for the operation (optional).
Returns A Tensor or SparseTensor or IndexedSlices with same shape as x with type float64.
Raises
TypeError If x cannot be cast to the float64. | |
doc_3393 | unlock()
Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. | |
doc_3394 | Decode a binhex file input. input may be a filename or a file-like object supporting read() and close() methods. The resulting file is written to a file named output, unless the argument is None in which case the output filename is read from the binhex file. | |
doc_3395 | This controls the minimum number of forms to show in the inline. See modelformset_factory() for more information. InlineModelAdmin.get_min_num() also allows you to customize the minimum number of displayed forms. | |
doc_3396 |
Call self as a function. | |
doc_3397 |
Parameters
padfloat
Fraction of the axes height.
Examples using mpl_toolkits.axes_grid1.axes_rgb.make_rgb_axes
Showing RGB channels using RGBAxes | |
doc_3398 |
Fit the imputer on X. Parameters
Xarray-like shape of (n_samples, n_features)
Input data, where n_samples is the number of samples and n_features is the number of features. Returns
selfobject | |
doc_3399 |
A 1-D view of the scalar. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.