_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_23900 |
Set the Figure instance the artist belongs to. Parameters
figFigure | |
doc_23901 | Return the phase of x (also known as the argument of x), as a float. phase(x) is equivalent to math.atan2(x.imag,
x.real). The result lies in the range [-π, π], and the branch cut for this operation lies along the negative real axis, continuous from above. On systems with support for signed zeros (which includes most systems in current use), this means that the sign of the result is the same as the sign of x.imag, even when x.imag is zero: >>> phase(complex(-1.0, 0.0))
3.141592653589793
>>> phase(complex(-1.0, -0.0))
-3.141592653589793 | |
doc_23902 |
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter. | |
doc_23903 | PyHKEY.__exit__(*exc_info)
The HKEY object implements __enter__() and __exit__() and thus supports the context protocol for the with statement: with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
... # work with key
will automatically close key when control leaves the with block. | |
doc_23904 |
Draw samples from a chi-square distribution. When df independent random variables, each with standard normal distributions (mean 0, variance 1), are squared and summed, the resulting distribution is chi-square (see Notes). This distribution is often used in hypothesis testing. Note New code should use the chisquare method of a default_rng() instance instead; please see the Quick Start. Parameters
dffloat or array_like of floats
Number of degrees of freedom, must be > 0.
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 df is a scalar. Otherwise, np.array(df).size samples are drawn. Returns
outndarray or scalar
Drawn samples from the parameterized chi-square distribution. Raises
ValueError
When df <= 0 or when an inappropriate size (e.g. size=-1) is given. See also Generator.chisquare
which should be used for new code. Notes The variable obtained by summing the squares of df independent, standard normally distributed random variables: \[Q = \sum_{i=0}^{\mathtt{df}} X^2_i\] is chi-square distributed, denoted \[Q \sim \chi^2_k.\] The probability density function of the chi-squared distribution is \[p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)} x^{k/2 - 1} e^{-x/2},\] where \(\Gamma\) is the gamma function, \[\Gamma(x) = \int_0^{-\infty} t^{x - 1} e^{-t} dt.\] References 1
NIST “Engineering Statistics Handbook” https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm Examples >>> np.random.chisquare(2,4)
array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272]) # random | |
doc_23905 | returns a list with all sprites at that position. get_sprites_at(pos) -> colliding_sprites Bottom sprites first, top last. | |
doc_23906 | Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement. As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do. For example: from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
with suppress(FileNotFoundError):
os.remove('someotherfile.tmp')
This code is equivalent to: try:
os.remove('somefile.tmp')
except FileNotFoundError:
pass
try:
os.remove('someotherfile.tmp')
except FileNotFoundError:
pass
This context manager is reentrant. New in version 3.4. | |
doc_23907 |
Checks if the MPI backend is available. | |
doc_23908 | Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field’s default widget will be used. only_initial is used by Django internals and should not be set explicitly. | |
doc_23909 |
Fit Naive Bayes classifier according to X, y Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training vectors, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
Target values.
sample_weightarray-like of shape (n_samples,), default=None
Weights applied to individual samples (1. for unweighted). Returns
selfobject | |
doc_23910 | Remove history item specified by its position from the history. The position is zero-based. This calls remove_history() in the underlying library. | |
doc_23911 | class sklearn.ensemble.GradientBoostingClassifier(*, loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, criterion='friedman_mse', min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, min_impurity_decrease=0.0, min_impurity_split=None, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, validation_fraction=0.1, n_iter_no_change=None, tol=0.0001, ccp_alpha=0.0) [source]
Gradient Boosting for classification. GB builds an additive model in a forward stage-wise fashion; it allows for the optimization of arbitrary differentiable loss functions. In each stage n_classes_ regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced. Read more in the User Guide. Parameters
loss{‘deviance’, ‘exponential’}, default=’deviance’
The loss function to be optimized. ‘deviance’ refers to deviance (= logistic regression) for classification with probabilistic outputs. For loss ‘exponential’ gradient boosting recovers the AdaBoost algorithm.
learning_ratefloat, default=0.1
Learning rate shrinks the contribution of each tree by learning_rate. There is a trade-off between learning_rate and n_estimators.
n_estimatorsint, default=100
The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance.
subsamplefloat, default=1.0
The fraction of samples to be used for fitting the individual base learners. If smaller than 1.0 this results in Stochastic Gradient Boosting. subsample interacts with the parameter n_estimators. Choosing subsample < 1.0 leads to a reduction of variance and an increase in bias.
criterion{‘friedman_mse’, ‘mse’, ‘mae’}, default=’friedman_mse’
The function to measure the quality of a split. Supported criteria are ‘friedman_mse’ for the mean squared error with improvement score by Friedman, ‘mse’ for mean squared error, and ‘mae’ for the mean absolute error. The default value of ‘friedman_mse’ is generally the best as it can provide a better approximation in some cases. New in version 0.18. Deprecated since version 0.24: criterion='mae' is deprecated and will be removed in version 1.1 (renaming of 0.26). Use criterion='friedman_mse' or 'mse' instead, as trees should use a least-square criterion in Gradient Boosting.
min_samples_splitint or float, default=2
The minimum number of samples required to split an internal node: If int, then consider min_samples_split as the minimum number. If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split. Changed in version 0.18: Added float values for fractions.
min_samples_leafint or float, default=1
The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. If int, then consider min_samples_leaf as the minimum number. If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node. Changed in version 0.18: Added float values for fractions.
min_weight_fraction_leaffloat, default=0.0
The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.
max_depthint, default=3
The maximum depth of the individual regression estimators. The maximum depth limits the number of nodes in the tree. Tune this parameter for best performance; the best value depends on the interaction of the input variables.
min_impurity_decreasefloat, default=0.0
A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following: N_t / N * (impurity - N_t_R / N_t * right_impurity
- N_t_L / N_t * left_impurity)
where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child. N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed. New in version 0.19.
min_impurity_splitfloat, default=None
Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use min_impurity_decrease instead.
initestimator or ‘zero’, default=None
An estimator object that is used to compute the initial predictions. init has to provide fit and predict_proba. If ‘zero’, the initial raw predictions are set to zero. By default, a DummyEstimator predicting the classes priors is used.
random_stateint, RandomState instance or None, default=None
Controls the random seed given to each Tree estimator at each boosting iteration. In addition, it controls the random permutation of the features at each split (see Notes for more details). It also controls the random spliting of the training data to obtain a validation set if n_iter_no_change is not None. Pass an int for reproducible output across multiple function calls. See Glossary.
max_features{‘auto’, ‘sqrt’, ‘log2’}, int or float, default=None
The number of features to consider when looking for the best split: If int, then consider max_features features at each split. If float, then max_features is a fraction and int(max_features * n_features) features are considered at each split. If ‘auto’, then max_features=sqrt(n_features). If ‘sqrt’, then max_features=sqrt(n_features). If ‘log2’, then max_features=log2(n_features). If None, then max_features=n_features. Choosing max_features < n_features leads to a reduction of variance and an increase in bias. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.
verboseint, default=0
Enable verbose output. If 1 then it prints progress and performance once in a while (the more trees the lower the frequency). If greater than 1 then it prints progress and performance for every tree.
max_leaf_nodesint, default=None
Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just erase the previous solution. See the Glossary.
validation_fractionfloat, default=0.1
The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if n_iter_no_change is set to an integer. New in version 0.20.
n_iter_no_changeint, default=None
n_iter_no_change is used to decide if early stopping will be used to terminate training when validation score is not improving. By default it is set to None to disable early stopping. If set to a number, it will set aside validation_fraction size of the training data as validation and terminate training when validation score is not improving in all of the previous n_iter_no_change numbers of iterations. The split is stratified. New in version 0.20.
tolfloat, default=1e-4
Tolerance for the early stopping. When the loss is not improving by at least tol for n_iter_no_change iterations (if set to a number), the training stops. New in version 0.20.
ccp_alphanon-negative float, default=0.0
Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details. New in version 0.22. Attributes
n_estimators_int
The number of estimators as selected by early stopping (if n_iter_no_change is specified). Otherwise it is set to n_estimators. New in version 0.20.
feature_importances_ndarray of shape (n_features,)
The impurity-based feature importances.
oob_improvement_ndarray of shape (n_estimators,)
The improvement in loss (= deviance) on the out-of-bag samples relative to the previous iteration. oob_improvement_[0] is the improvement in loss of the first stage over the init estimator. Only available if subsample < 1.0
train_score_ndarray of shape (n_estimators,)
The i-th score train_score_[i] is the deviance (= loss) of the model at iteration i on the in-bag sample. If subsample == 1 this is the deviance on the training data.
loss_LossFunction
The concrete LossFunction object.
init_estimator
The estimator that provides the initial predictions. Set via the init argument or loss.init_estimator.
estimators_ndarray of DecisionTreeRegressor of shape (n_estimators, loss_.K)
The collection of fitted sub-estimators. loss_.K is 1 for binary classification, otherwise n_classes.
classes_ndarray of shape (n_classes,)
The classes labels.
n_features_int
The number of data features.
n_classes_int
The number of classes.
max_features_int
The inferred value of max_features. See also
HistGradientBoostingClassifier
Histogram-based Gradient Boosting Classification Tree.
sklearn.tree.DecisionTreeClassifier
A decision tree classifier.
RandomForestClassifier
A meta-estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting.
AdaBoostClassifier
A meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases. Notes The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data and max_features=n_features, if the improvement of the criterion is identical for several splits enumerated during the search of the best split. To obtain a deterministic behaviour during fitting, random_state has to be fixed. References J. Friedman, Greedy Function Approximation: A Gradient Boosting Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. Friedman, Stochastic Gradient Boosting, 1999 T. Hastie, R. Tibshirani and J. Friedman. Elements of Statistical Learning Ed. 2, Springer, 2009. Examples The following example shows how to fit a gradient boosting classifier with 100 decision stumps as weak learners. >>> from sklearn.datasets import make_hastie_10_2
>>> from sklearn.ensemble import GradientBoostingClassifier
>>> X, y = make_hastie_10_2(random_state=0)
>>> X_train, X_test = X[:2000], X[2000:]
>>> y_train, y_test = y[:2000], y[2000:]
>>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0,
... max_depth=1, random_state=0).fit(X_train, y_train)
>>> clf.score(X_test, y_test)
0.913...
Methods
apply(X) Apply trees in the ensemble to X, return leaf indices.
decision_function(X) Compute the decision function of X.
fit(X, y[, sample_weight, monitor]) Fit the gradient boosting model.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class for X.
predict_log_proba(X) Predict class log-probabilities for X.
predict_proba(X) Predict class probabilities for X.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
staged_decision_function(X) Compute decision function of X for each iteration.
staged_predict(X) Predict class at each stage for X.
staged_predict_proba(X) Predict class probabilities at each stage for X.
apply(X) [source]
Apply trees in the ensemble to X, return leaf indices. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted to a sparse csr_matrix. Returns
X_leavesarray-like of shape (n_samples, n_estimators, n_classes)
For each datapoint x in X and for each tree in the ensemble, return the index of the leaf x ends up in each estimator. In the case of binary classification n_classes is 1.
decision_function(X) [source]
Compute the decision function of X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
scorendarray of shape (n_samples, n_classes) or (n_samples,)
The decision function of the input samples, which corresponds to the raw values predicted from the trees of the ensemble . The order of the classes corresponds to that in the attribute classes_. Regression and binary classification produce an array of shape (n_samples,).
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros.
fit(X, y, sample_weight=None, monitor=None) [source]
Fit the gradient boosting model. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
yarray-like of shape (n_samples,)
Target values (strings or integers in classification, real numbers in regression) For classification, labels must correspond to classes.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node.
monitorcallable, default=None
The monitor is called after each iteration with the current iteration, a reference to the estimator and the local variables of _fit_stages as keyword arguments callable(i, self,
locals()). If the callable returns True the fitting procedure is stopped. The monitor can be used for various things such as computing held-out estimates, early stopping, model introspect, and snapshoting. Returns
selfobject
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X) [source]
Predict class for X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
yndarray of shape (n_samples,)
The predicted values.
predict_log_proba(X) [source]
Predict class log-probabilities for X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
pndarray of shape (n_samples, n_classes)
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. Raises
AttributeError
If the loss does not support probabilities.
predict_proba(X) [source]
Predict class probabilities for X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. Raises
AttributeError
If the loss does not support probabilities.
score(X, y, sample_weight=None) [source]
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
staged_decision_function(X) [source]
Compute decision function of X for each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
scoregenerator of ndarray of shape (n_samples, k)
The decision function of the input samples, which corresponds to the raw values predicted from the trees of the ensemble . The classes corresponds to that in the attribute classes_. Regression and binary classification are special cases with k == 1, otherwise k==n_classes.
staged_predict(X) [source]
Predict class at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
ygenerator of ndarray of shape (n_samples,)
The predicted value of the input samples.
staged_predict_proba(X) [source]
Predict class probabilities at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
ygenerator of ndarray of shape (n_samples,)
The predicted value of the input samples.
Examples using sklearn.ensemble.GradientBoostingClassifier
Gradient Boosting regularization
Early stopping of Gradient Boosting
Feature transformations with ensembles of trees
Gradient Boosting Out-of-Bag estimates
Feature discretization | |
doc_23912 | Exception raised if add_section() is called with the name of a section that is already present or in strict parsers when a section if found more than once in a single input file, string or dictionary. New in version 3.2: Optional source and lineno attributes and arguments to __init__() were added. | |
doc_23913 |
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. | |
doc_23914 | Stack tensors in sequence vertically (row wise). This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by torch.atleast_2d(). Parameters
tensors (sequence of Tensors) – sequence of tensors to concatenate Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.tensor([1, 2, 3])
>>> b = torch.tensor([4, 5, 6])
>>> torch.vstack((a,b))
tensor([[1, 2, 3],
[4, 5, 6]])
>>> a = torch.tensor([[1],[2],[3]])
>>> b = torch.tensor([[4],[5],[6]])
>>> torch.vstack((a,b))
tensor([[1],
[2],
[3],
[4],
[5],
[6]]) | |
doc_23915 | Boolean attribute that is set to True after the registry is fully populated and all AppConfig.ready() methods are called. | |
doc_23916 |
Combines an array of sliding local blocks into a large containing tensor. Warning Currently, only 3-D output tensors (unfolded batched image-like tensors) are supported. See torch.nn.Fold for details | |
doc_23917 | 'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}
You can also set the parsers used for an individual view, or viewset, using the APIView class-based views. from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
"""
A view that can accept POST requests with JSON content.
"""
parser_classes = [JSONParser]
def post(self, request, format=None):
return Response({'received data': request.data})
Or, if you're using the @api_view decorator with function based views. from rest_framework.decorators import api_view
from rest_framework.decorators import parser_classes
from rest_framework.parsers import JSONParser
@api_view(['POST'])
@parser_classes([JSONParser])
def example_view(request, format=None):
"""
A view that can accept POST requests with JSON content.
"""
return Response({'received data': request.data})
API Reference JSONParser Parses JSON request content. request.data will be populated with a dictionary of data. .media_type: application/json FormParser Parses HTML form content. request.data will be populated with a QueryDict of data. You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data. .media_type: application/x-www-form-urlencoded MultiPartParser Parses multipart HTML form content, which supports file uploads. Both request.data will be populated with a QueryDict. You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data. .media_type: multipart/form-data FileUploadParser Parses raw file upload content. The request.data property will be a dictionary with a single key 'file' containing the uploaded file. If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg. .media_type: */* Notes: The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser instead. Since this parser's media_type matches any content type, FileUploadParser should generally be the only parser set on an API view.
FileUploadParser respects Django's standard FILE_UPLOAD_HANDLERS setting, and the request.upload_handlers attribute. See the Django documentation for more details. Basic usage example: # views.py
class FileUploadView(views.APIView):
parser_classes = [FileUploadParser]
def put(self, request, filename, format=None):
file_obj = request.data['file']
# ...
# do some stuff with uploaded file
# ...
return Response(status=204)
# urls.py
urlpatterns = [
# ...
re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
]
Custom parsers To implement a custom parser, you should override BaseParser, set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method. The method should return the data that will be used to populate the request.data property. The arguments passed to .parse() are: stream A stream-like object representing the body of the request. media_type Optional. If provided, this is the media type of the incoming request content. Depending on the request's Content-Type: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example "text/plain; charset=utf-8". parser_context Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content. By default this will include the following keys: view, request, args, kwargs. Example The following is an example plaintext parser that will populate the request.data property with a string representing the body of the request. class PlainTextParser(BaseParser):
"""
Plain text parser.
"""
media_type = 'text/plain'
def parse(self, stream, media_type=None, parser_context=None):
"""
Simply return a string representing the body of the request.
"""
return stream.read()
Third party packages The following third party packages are also available. YAML REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Installation & configuration Install using pip. $ pip install djangorestframework-yaml
Modify your REST framework settings. REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework_yaml.parsers.YAMLParser',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework_yaml.renderers.YAMLRenderer',
],
}
XML REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Installation & configuration Install using pip. $ pip install djangorestframework-xml
Modify your REST framework settings. REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework_xml.parsers.XMLParser',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework_xml.renderers.XMLRenderer',
],
}
MessagePack MessagePack is a fast, efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework. CamelCase JSON djangorestframework-camel-case provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by Vitaly Babiy. parsers.py | |
doc_23918 |
Applies Batch Normalization over a 4D input (a mini-batch of 2D inputs with additional channel dimension) as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift . y=x−E[x]Var[x]+ϵ∗γ+βy = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
The mean and standard-deviation are calculated per-dimension over the mini-batches and γ\gamma and β\beta are learnable parameter vectors of size C (where C is the input size). By default, the elements of γ\gamma are set to 1 and the elements of β\beta are set to 0. The standard-deviation is calculated via the biased estimator, equivalent to torch.var(input, unbiased=False). Also by default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default momentum of 0.1. If track_running_stats is set to False, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. Note This momentum argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is x^new=(1−momentum)×x^+momentum×xt\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t , where x^\hat{x} is the estimated statistic and xtx_t is the new observed value. Because the Batch Normalization is done over the C dimension, computing statistics on (N, H, W) slices, it’s common terminology to call this Spatial Batch Normalization. Parameters
num_features – CC from an expected input of size (N,C,H,W)(N, C, H, W)
eps – a value added to the denominator for numerical stability. Default: 1e-5
momentum – the value used for the running_mean and running_var computation. Can be set to None for cumulative moving average (i.e. simple average). Default: 0.1
affine – a boolean value that when set to True, this module has learnable affine parameters. Default: True
track_running_stats – a boolean value that when set to True, this module tracks the running mean and variance, and when set to False, this module does not track such statistics, and initializes statistics buffers running_mean and running_var as None. When these buffers are None, this module always uses batch statistics. in both training and eval modes. Default: True
Shape:
Input: (N,C,H,W)(N, C, H, W)
Output: (N,C,H,W)(N, C, H, W) (same shape as input) Examples: >>> # With Learnable Parameters
>>> m = nn.BatchNorm2d(100)
>>> # Without Learnable Parameters
>>> m = nn.BatchNorm2d(100, affine=False)
>>> input = torch.randn(20, 100, 35, 45)
>>> output = m(input) | |
doc_23919 | Return True if the buffer is empty and feed_eof() was called. | |
doc_23920 | Returns either True or False, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to call set_test_cookie() on a previous, separate page request. See Setting test cookies below for more information. | |
doc_23921 | Raised when the import statement has troubles trying to load a module. Also raised when the “from list” in from ... import has a name that cannot be found. The name and path attributes can be set using keyword-only arguments to the constructor. When set they represent the name of the module that was attempted to be imported and the path to any file which triggered the exception, respectively. Changed in version 3.3: Added the name and path attributes. | |
doc_23922 | See Migration guide for more details. tf.compat.v1.keras.layers.Lambda
tf.keras.layers.Lambda(
function, output_shape=None, mask=None, arguments=None, **kwargs
)
The Lambda layer exists so that arbitrary TensorFlow functions can be used when constructing Sequential and Functional API models. Lambda layers are best suited for simple operations or quick experimentation. For more advanced use cases, follow this guide for subclassing tf.keras.layers.Layer. The main reason to subclass tf.keras.layers.Layer instead of using a Lambda layer is saving and inspecting a Model. Lambda layers are saved by serializing the Python bytecode, which is fundamentally non-portable. They should only be loaded in the same environment where they were saved. Subclassed layers can be saved in a more portable way by overriding their get_config method. Models that rely on subclassed Layers are also often easier to visualize and reason about. Examples: # add a x -> x^2 layer
model.add(Lambda(lambda x: x ** 2))
# add a layer that returns the concatenation
# of the positive part of the input and
# the opposite of the negative part
def antirectifier(x):
x -= K.mean(x, axis=1, keepdims=True)
x = K.l2_normalize(x, axis=1)
pos = K.relu(x)
neg = K.relu(-x)
return K.concatenate([pos, neg], axis=1)
model.add(Lambda(antirectifier))
Variables: While it is possible to use Variables with Lambda layers, this practice is discouraged as it can easily lead to bugs. For instance, consider the following layer: scale = tf.Variable(1.)
scale_layer = tf.keras.layers.Lambda(lambda x: x * scale)
Because scale_layer does not directly track the scale variable, it will not appear in scale_layer.trainable_weights and will therefore not be trained if scale_layer is used in a Model. A better pattern is to write a subclassed Layer: class ScaleLayer(tf.keras.layers.Layer):
def __init__(self):
super(ScaleLayer, self).__init__()
self.scale = tf.Variable(1.)
def call(self, inputs):
return inputs * self.scale
In general, Lambda layers can be convenient for simple stateless computation, but anything more complex should use a subclass Layer instead.
Arguments
function The function to be evaluated. Takes input tensor as first argument.
output_shape Expected output shape from function. This argument can be inferred if not explicitly provided. Can be a tuple or function. If a tuple, it only specifies the first dimension onward; sample dimension is assumed either the same as the input: output_shape = (input_shape[0], ) + output_shape or, the input is None and the sample dimension is also None: output_shape = (None, ) + output_shape If a function, it specifies the entire shape as a function of the input shape: output_shape = f(input_shape)
mask Either None (indicating no masking) or a callable with the same signature as the compute_mask layer method, or a tensor that will be returned as output mask regardless of what the input is.
arguments Optional dictionary of keyword arguments to be passed to the function. Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Specified by output_shape argument | |
doc_23923 | tf.compat.v1.user_ops.my_fact() | |
doc_23924 |
Return the first n rows ordered by columns in descending order. Return the first n rows with the largest values in columns, in descending order. The columns that are not specified are returned as well, but not used for ordering. This method is equivalent to df.sort_values(columns, ascending=False).head(n), but more performant. Parameters
n:int
Number of rows to return.
columns:label or list of labels
Column label(s) to order by.
keep:{‘first’, ‘last’, ‘all’}, default ‘first’
Where there are duplicate values: first : prioritize the first occurrence(s) last : prioritize the last occurrence(s) all : do not drop any duplicates, even it means selecting more than n items. Returns
DataFrame
The first n rows ordered by the given columns in descending order. See also DataFrame.nsmallest
Return the first n rows ordered by columns in ascending order. DataFrame.sort_values
Sort DataFrame by the values. DataFrame.head
Return the first n rows without re-ordering. Notes This function cannot be used with all column types. For example, when specifying columns with object or category dtypes, TypeError is raised. Examples
>>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,
... 434000, 434000, 337000, 11300,
... 11300, 11300],
... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,
... 17036, 182, 38, 311],
... 'alpha-2': ["IT", "FR", "MT", "MV", "BN",
... "IS", "NR", "TV", "AI"]},
... index=["Italy", "France", "Malta",
... "Maldives", "Brunei", "Iceland",
... "Nauru", "Tuvalu", "Anguilla"])
>>> df
population GDP alpha-2
Italy 59000000 1937894 IT
France 65000000 2583560 FR
Malta 434000 12011 MT
Maldives 434000 4520 MV
Brunei 434000 12128 BN
Iceland 337000 17036 IS
Nauru 11300 182 NR
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
In the following example, we will use nlargest to select the three rows having the largest values in column “population”.
>>> df.nlargest(3, 'population')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Malta 434000 12011 MT
When using keep='last', ties are resolved in reverse order:
>>> df.nlargest(3, 'population', keep='last')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Brunei 434000 12128 BN
When using keep='all', all duplicate items are maintained:
>>> df.nlargest(3, 'population', keep='all')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Malta 434000 12011 MT
Maldives 434000 4520 MV
Brunei 434000 12128 BN
To order by the largest values in column “population” and then “GDP”, we can specify multiple columns like in the next example.
>>> df.nlargest(3, ['population', 'GDP'])
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Brunei 434000 12128 BN | |
doc_23925 | Remove label from the list of labels on the message. | |
doc_23926 |
Bases: matplotlib.widgets.SliderBase A slider representing a floating point range. Create a slider from valmin to valmax in axes ax. For the slider to remain responsive you must maintain a reference to it. Call on_changed() to connect to the slider event. Attributes
valfloat
Slider value. Parameters
axAxes
The Axes to put the slider in.
labelstr
Slider label.
valminfloat
The minimum value of the slider.
valmaxfloat
The maximum value of the slider.
valinitfloat, default: 0.5
The slider initial position.
valfmtstr, default: None
%-format string used to format the slider value. If None, a ScalarFormatter is used instead.
closedminbool, default: True
Whether the slider interval is closed on the bottom.
closedmaxbool, default: True
Whether the slider interval is closed on the top.
sliderminSlider, default: None
Do not allow the current slider to have a value less than the value of the Slider slidermin.
slidermaxSlider, default: None
Do not allow the current slider to have a value greater than the value of the Slider slidermax.
draggingbool, default: True
If True the slider can be dragged by the mouse.
valstepfloat or array-like, default: None
If a float, the slider will snap to multiples of valstep. If an array the slider will snap to the values in the array.
orientation{'horizontal', 'vertical'}, default: 'horizontal'
The orientation of the slider.
initcolorcolor, default: 'r'
The color of the line at the valinit position. Set to 'none' for no line.
track_colorcolor, default: 'lightgrey'
The color of the background track. The track is accessible for further styling via the track attribute.
handle_styledict
Properties of the slider handle. Default values are
Key Value Default Description
facecolor color 'white' The facecolor of the slider handle.
edgecolor color '.75' The edgecolor of the slider handle.
size int 10 The size of the slider handle in points. Other values will be transformed as marker{foo} and passed to the Line2D constructor. e.g. handle_style = {'style'='x'} will result in markerstyle = 'x'. Notes Additional kwargs are passed on to self.poly which is the Polygon that draws the slider knob. See the Polygon documentation for valid property names (facecolor, edgecolor, alpha, etc.). propertycnt[source]
propertyobservers[source]
on_changed(func)[source]
Connect func as callback function to changes of the slider value. Parameters
funccallable
Function to call when slider is changed. The function must accept a single float as its arguments. Returns
int
Connection id (which can be used to disconnect func).
set_val(val)[source]
Set slider value to val. Parameters
valfloat | |
doc_23927 |
Computes the OPTICS reachability graph. Read more in the User Guide. Parameters
Xndarray of shape (n_samples, n_features), or (n_samples, n_samples) if metric=’precomputed’.
A feature array, or array of distances between samples if metric=’precomputed’
min_samplesint > 1 or float between 0 and 1
The number of samples in a neighborhood for a point to be considered as a core point. Expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2).
max_epsfloat, default=np.inf
The maximum distance between two samples for one to be considered as in the neighborhood of the other. Default value of np.inf will identify clusters across all scales; reducing max_eps will result in shorter run times.
metricstr or callable, default=’minkowski’
Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics.
pint, default=2
Parameter for the Minkowski metric from pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
metric_paramsdict, default=None
Additional keyword arguments for the metric function.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree
‘kd_tree’ will use KDTree
‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. (default) Note: fitting on sparse input will override the setting of this parameter, using brute force.
leaf_sizeint, default=30
Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
n_jobsint, default=None
The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Returns
ordering_array of shape (n_samples,)
The cluster ordered list of sample indices.
core_distances_array of shape (n_samples,)
Distance at which each sample becomes a core point, indexed by object order. Points which will never be core have a distance of inf. Use clust.core_distances_[clust.ordering_] to access in cluster order.
reachability_array of shape (n_samples,)
Reachability distances per sample, indexed by object order. Use clust.reachability_[clust.ordering_] to access in cluster order.
predecessor_array of shape (n_samples,)
Point that a sample was reached from, indexed by object order. Seed points have a predecessor of -1. References
1
Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander. “OPTICS: ordering points to identify the clustering structure.” ACM SIGMOD Record 28, no. 2 (1999): 49-60. | |
doc_23928 | Return True if the symbol is a parameter. | |
doc_23929 | This class can be used to generate plain text calendars. TextCalendar instances have the following methods:
formatmonth(theyear, themonth, w=0, l=0)
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.
prmonth(theyear, themonth, w=0, l=0)
Print a month’s calendar as returned by formatmonth().
formatyear(theyear, w=2, l=1, c=6, m=3)
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.
pryear(theyear, w=2, l=1, c=6, m=3)
Print the calendar for an entire year as returned by formatyear(). | |
doc_23930 | Locale category for formatting of monetary values. The available options are available from the localeconv() function. | |
doc_23931 |
Return the identity array. The identity array is a square array with ones on the main diagonal. Parameters
nint
Number of rows (and columns) in n x n output.
dtypedata-type, optional
Data-type of the output. Defaults to float.
likearray_like
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns
outndarray
n x n array with its main diagonal set to one, and all other elements 0. Examples >>> np.identity(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]) | |
doc_23932 | class sklearn.linear_model.PassiveAggressiveClassifier(*, C=1.0, fit_intercept=True, max_iter=1000, tol=0.001, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, shuffle=True, verbose=0, loss='hinge', n_jobs=None, random_state=None, warm_start=False, class_weight=None, average=False) [source]
Passive Aggressive Classifier Read more in the User Guide. Parameters
Cfloat, default=1.0
Maximum step size (regularization). Defaults to 1.0.
fit_interceptbool, default=True
Whether the intercept should be estimated or not. If False, the data is assumed to be already centered.
max_iterint, default=1000
The maximum number of passes over the training data (aka epochs). It only impacts the behavior in the fit method, and not the partial_fit method. New in version 0.19.
tolfloat or None, default=1e-3
The stopping criterion. If it is not None, the iterations will stop when (loss > previous_loss - tol). New in version 0.19.
early_stoppingbool, default=False
Whether to use early stopping to terminate training when validation. score is not improving. If set to True, it will automatically set aside a stratified fraction of training data as validation and terminate training when validation score is not improving by at least tol for n_iter_no_change consecutive epochs. New in version 0.20.
validation_fractionfloat, default=0.1
The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if early_stopping is True. New in version 0.20.
n_iter_no_changeint, default=5
Number of iterations with no improvement to wait before early stopping. New in version 0.20.
shufflebool, default=True
Whether or not the training data should be shuffled after each epoch.
verboseinteger, default=0
The verbosity level
lossstring, default=”hinge”
The loss function to be used: hinge: equivalent to PA-I in the reference paper. squared_hinge: equivalent to PA-II in the reference paper.
n_jobsint or None, default=None
The number of CPUs to use to do the OVA (One Versus All, for multi-class problems) computation. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance, default=None
Used to shuffle the training data, when shuffle is set to True. Pass an int for reproducible output across multiple function calls. See Glossary.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See the Glossary. Repeatedly calling fit or partial_fit when warm_start is True can result in a different solution than when calling fit a single time because of the way the data is shuffled.
class_weightdict, {class_label: weight} or “balanced” or None, default=None
Preset for the class_weight fit parameter. Weights associated with classes. If not given, all classes are supposed to have weight one. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)) New in version 0.17: parameter class_weight to automatically weight samples.
averagebool or int, default=False
When set to True, computes the averaged SGD weights and stores the result in the coef_ attribute. If set to an int greater than 1, averaging will begin once the total number of samples seen reaches average. So average=10 will begin averaging after seeing 10 samples. New in version 0.19: parameter average to use weights averaging in SGD Attributes
coef_array, shape = [1, n_features] if n_classes == 2 else [n_classes, n_features]
Weights assigned to the features.
intercept_array, shape = [1] if n_classes == 2 else [n_classes]
Constants in decision function.
n_iter_int
The actual number of iterations to reach the stopping criterion. For multiclass fits, it is the maximum over every binary fit.
classes_array of shape (n_classes,)
The unique classes labels.
t_int
Number of weight updates performed during training. Same as (n_iter_ * n_samples).
loss_function_callable
Loss function used by the algorithm. See also
SGDClassifier
Perceptron
References Online Passive-Aggressive Algorithms <http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf> K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006) Examples >>> from sklearn.linear_model import PassiveAggressiveClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_features=4, random_state=0)
>>> clf = PassiveAggressiveClassifier(max_iter=1000, random_state=0,
... tol=1e-3)
>>> clf.fit(X, y)
PassiveAggressiveClassifier(random_state=0)
>>> print(clf.coef_)
[[0.26642044 0.45070924 0.67251877 0.64185414]]
>>> print(clf.intercept_)
[1.84127814]
>>> print(clf.predict([[0, 0, 0, 0]]))
[1]
Methods
decision_function(X) Predict confidence scores for samples.
densify() Convert coefficient matrix to dense array format.
fit(X, y[, coef_init, intercept_init]) Fit linear model with Passive Aggressive algorithm.
get_params([deep]) Get parameters for this estimator.
partial_fit(X, y[, classes]) Fit linear model with Passive Aggressive algorithm.
predict(X) Predict class labels for samples in X.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**kwargs) Set and validate the parameters of estimator.
sparsify() Convert coefficient matrix to sparse format.
decision_function(X) [source]
Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)
Confidence scores per (sample, class) combination. In the binary case, confidence score for self.classes_[1] where >0 means this class would be predicted.
densify() [source]
Convert coefficient matrix to dense array format. Converts the coef_ member (back) to a numpy.ndarray. This is the default format of coef_ and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op. Returns
self
Fitted estimator.
fit(X, y, coef_init=None, intercept_init=None) [source]
Fit linear model with Passive Aggressive algorithm. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data
ynumpy array of shape [n_samples]
Target values
coef_initarray, shape = [n_classes,n_features]
The initial coefficients to warm-start the optimization.
intercept_initarray, shape = [n_classes]
The initial intercept to warm-start the optimization. Returns
selfreturns an instance of self.
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.
partial_fit(X, y, classes=None) [source]
Fit linear model with Passive Aggressive algorithm. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Subset of the training data
ynumpy array of shape [n_samples]
Subset of the target values
classesarray, shape = [n_classes]
Classes across all calls to partial_fit. Can be obtained by via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is required for the first call to partial_fit and can be omitted in the subsequent calls. Note that y doesn’t need to contain all labels in classes. Returns
selfreturns an instance of self.
predict(X) [source]
Predict class labels for samples in X. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape [n_samples]
Predicted class label per sample.
score(X, y, sample_weight=None) [source]
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y.
set_params(**kwargs) [source]
Set and validate the parameters of estimator. Parameters
**kwargsdict
Estimator parameters. Returns
selfobject
Estimator instance.
sparsify() [source]
Convert coefficient matrix to sparse format. Converts the coef_ member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation. The intercept_ member is not converted. Returns
self
Fitted estimator. Notes For non-sparse models, i.e. when there are not many zeros in coef_, this may actually increase memory usage, so use this method with care. A rule of thumb is that the number of zero elements, which can be computed with (coef_ == 0).sum(), must be more than 50% for this to provide significant benefits. After calling this method, further fitting with the partial_fit method (if any) will not work until you call densify.
Examples using sklearn.linear_model.PassiveAggressiveClassifier
Out-of-core classification of text documents
Comparing various online solvers
Classification of text documents using sparse features | |
doc_23933 | A boolean that is True if the barrier is in the broken state. | |
doc_23934 | Returns a cookie value for a signed cookie, or raises a django.core.signing.BadSignature exception if the signature is no longer valid. If you provide the default argument the exception will be suppressed and that default value will be returned instead. The optional salt argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, the max_age argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than max_age seconds. For example: >>> request.get_signed_cookie('name')
'Tony'
>>> request.get_signed_cookie('name', salt='name-salt')
'Tony' # assuming cookie was set using the same salt
>>> request.get_signed_cookie('nonexistent-cookie')
...
KeyError: 'nonexistent-cookie'
>>> request.get_signed_cookie('nonexistent-cookie', False)
False
>>> request.get_signed_cookie('cookie-that-was-tampered-with')
...
BadSignature: ...
>>> request.get_signed_cookie('name', max_age=60)
...
SignatureExpired: Signature age 1677.3839159 > 60 seconds
>>> request.get_signed_cookie('name', False, max_age=60)
False
See cryptographic signing for more information. | |
doc_23935 | Return the bytes object that would be written to a file by dump(value, file). The value must be a supported type. Raise a ValueError exception if value has (or contains an object that has) an unsupported type. The version argument indicates the data format that dumps should use (see below). | |
doc_23936 |
Decorator for building a Normalize subclass from a ScaleBase subclass. After @make_norm_from_scale(scale_cls)
class norm_cls(Normalize):
...
norm_cls is filled with methods so that normalization computations are forwarded to scale_cls (i.e., scale_cls is the scale that would be used for the colorbar of a mappable normalized with norm_cls). If init is not passed, then the constructor signature of norm_cls will be norm_cls(vmin=None, vmax=None, clip=False); these three parameters will be forwarded to the base class (Normalize.__init__), and a scale_cls object will be initialized with no arguments (other than a dummy axis). If the scale_cls constructor takes additional parameters, then init should be passed to make_norm_from_scale. It is a callable which is only used for its signature. First, this signature will become the signature of norm_cls. Second, the norm_cls constructor will bind the parameters passed to it using this signature, extract the bound vmin, vmax, and clip values, pass those to Normalize.__init__, and forward the remaining bound values (including any defaults defined by the signature) to the scale_cls constructor. | |
doc_23937 |
Encode the object as an enumerated type or categorical variable. This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. factorize is available as both a top-level function pandas.factorize(), and as a method Series.factorize() and Index.factorize(). Parameters
sort:bool, default False
Sort uniques and shuffle codes to maintain the relationship.
na_sentinel:int or None, default -1
Value to mark “not found”. If None, will not drop the NaN from the uniques of the values. Changed in version 1.1.2. Returns
codes:ndarray
An integer ndarray that’s an indexer into uniques. uniques.take(codes) will have the same values as values.
uniques:ndarray, Index, or Categorical
The unique valid values. When values is Categorical, uniques is a Categorical. When values is some other pandas object, an Index is returned. Otherwise, a 1-D ndarray is returned. Note Even if there’s a missing value in values, uniques will not contain an entry for it. See also cut
Discretize continuous-valued array. unique
Find the unique value in an array. Examples These examples all show factorize as a top-level method like pd.factorize(values). The results are identical for methods like Series.factorize().
>>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])
>>> codes
array([0, 0, 1, 2, 0]...)
>>> uniques
array(['b', 'a', 'c'], dtype=object)
With sort=True, the uniques will be sorted, and codes will be shuffled so that the relationship is the maintained.
>>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'], sort=True)
>>> codes
array([1, 1, 0, 2, 1]...)
>>> uniques
array(['a', 'b', 'c'], dtype=object)
Missing values are indicated in codes with na_sentinel (-1 by default). Note that missing values are never included in uniques.
>>> codes, uniques = pd.factorize(['b', None, 'a', 'c', 'b'])
>>> codes
array([ 0, -1, 1, 2, 0]...)
>>> uniques
array(['b', 'a', 'c'], dtype=object)
Thus far, we’ve only factorized lists (which are internally coerced to NumPy arrays). When factorizing pandas objects, the type of uniques will differ. For Categoricals, a Categorical is returned.
>>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c'])
>>> codes, uniques = pd.factorize(cat)
>>> codes
array([0, 0, 1]...)
>>> uniques
['a', 'c']
Categories (3, object): ['a', 'b', 'c']
Notice that 'b' is in uniques.categories, despite not being present in cat.values. For all other pandas objects, an Index of the appropriate type is returned.
>>> cat = pd.Series(['a', 'a', 'c'])
>>> codes, uniques = pd.factorize(cat)
>>> codes
array([0, 0, 1]...)
>>> uniques
Index(['a', 'c'], dtype='object')
If NaN is in the values, and we want to include NaN in the uniques of the values, it can be achieved by setting na_sentinel=None.
>>> values = np.array([1, 2, 1, np.nan])
>>> codes, uniques = pd.factorize(values) # default: na_sentinel=-1
>>> codes
array([ 0, 1, 0, -1])
>>> uniques
array([1., 2.])
>>> codes, uniques = pd.factorize(values, na_sentinel=None)
>>> codes
array([0, 1, 0, 2])
>>> uniques
array([ 1., 2., nan]) | |
doc_23938 |
Perform DBSCAN clustering from vector array or distance matrix. Read more in the User Guide. Parameters
X{array-like, sparse (CSR) matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
A feature array, or array of distances between samples if metric='precomputed'.
epsfloat, default=0.5
The maximum distance between two samples for one to be considered as in the neighborhood of the other. This is not a maximum bound on the distances of points within a cluster. This is the most important DBSCAN parameter to choose appropriately for your data set and distance function.
min_samplesint, default=5
The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself.
metricstr or callable, default=’minkowski’
The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by sklearn.metrics.pairwise_distances for its metric parameter. If metric is “precomputed”, X is assumed to be a distance matrix and must be square during fit. X may be a sparse graph, in which case only “nonzero” elements may be considered neighbors.
metric_paramsdict, default=None
Additional keyword arguments for the metric function. New in version 0.19.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details.
leaf_sizeint, default=30
Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
pfloat, default=2
The power of the Minkowski metric to be used to calculate distance between points.
sample_weightarray-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least min_samples is by itself a core sample; a sample with negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1.
n_jobsint, default=None
The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. If precomputed distance are used, parallel execution is not available and thus n_jobs will have no effect. Returns
core_samplesndarray of shape (n_core_samples,)
Indices of core samples.
labelsndarray of shape (n_samples,)
Cluster labels for each point. Noisy samples are given the label -1. See also
DBSCAN
An estimator interface for this clustering algorithm.
OPTICS
A similar estimator interface clustering at multiple values of eps. Our implementation is optimized for memory usage. Notes For an example, see examples/cluster/plot_dbscan.py. This implementation bulk-computes all neighborhood queries, which increases the memory complexity to O(n.d) where d is the average number of neighbors, while original DBSCAN had memory complexity O(n). It may attract a higher memory complexity when querying these nearest neighborhoods, depending on the algorithm. One way to avoid the query complexity is to pre-compute sparse neighborhoods in chunks using NearestNeighbors.radius_neighbors_graph with mode='distance', then using metric='precomputed' here. Another way to reduce memory and computation time is to remove (near-)duplicate points and use sample_weight instead. cluster.optics provides a similar clustering with lower memory usage. References Ester, M., H. P. Kriegel, J. Sander, and X. Xu, “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise”. In: Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). DBSCAN revisited, revisited: why and how you should (still) use DBSCAN. ACM Transactions on Database Systems (TODS), 42(3), 19. | |
doc_23939 |
Generic Python-exception-derived object raised by linalg functions. General purpose exception class, derived from Python’s exception.Exception class, programmatically raised in linalg functions when a Linear Algebra-related condition would prevent further correct execution of the function. Parameters
None
Examples >>> from numpy import linalg as LA
>>> LA.inv(np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "...linalg.py", line 350,
in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
File "...linalg.py", line 249,
in solve
raise LinAlgError('Singular matrix')
numpy.linalg.LinAlgError: Singular matrix | |
doc_23940 | winreg.CloseKey(hkey)
Closes a previously opened registry key. The hkey argument specifies a previously opened key. Note If hkey is not closed using this method (or via hkey.Close()), it is closed when the hkey object is destroyed by Python.
winreg.ConnectRegistry(computer_name, key)
Establishes a connection to a predefined registry handle on another computer, and returns a handle object. computer_name is the name of the remote computer, of the form r"\\computername". If None, the local computer is used. key is the predefined handle to connect to. The return value is the handle of the opened key. If the function fails, an OSError exception is raised. Raises an auditing event winreg.ConnectRegistry with arguments computer_name, key. Changed in version 3.3: See above.
winreg.CreateKey(key, sub_key)
Creates or opens the specified key, returning a handle object. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that names the key this method opens or creates. If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function. If the key already exists, this function opens the existing key. The return value is the handle of the opened key. If the function fails, an OSError exception is raised. Raises an auditing event winreg.CreateKey with arguments key, sub_key, access. Raises an auditing event winreg.OpenKey/result with argument key. Changed in version 3.3: See above.
winreg.CreateKeyEx(key, sub_key, reserved=0, access=KEY_WRITE)
Creates or opens the specified key, returning a handle object. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that names the key this method opens or creates. reserved is a reserved integer, and must be zero. The default is zero. access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WRITE. See Access Rights for other allowed values. If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function. If the key already exists, this function opens the existing key. The return value is the handle of the opened key. If the function fails, an OSError exception is raised. Raises an auditing event winreg.CreateKey with arguments key, sub_key, access. Raises an auditing event winreg.OpenKey/result with argument key. New in version 3.2. Changed in version 3.3: See above.
winreg.DeleteKey(key, sub_key)
Deletes the specified key. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys. This method can not delete keys with subkeys. If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised. Raises an auditing event winreg.DeleteKey with arguments key, sub_key, access. Changed in version 3.3: See above.
winreg.DeleteKeyEx(key, sub_key, access=KEY_WOW64_64KEY, reserved=0)
Deletes the specified key. Note The DeleteKeyEx() function is implemented with the RegDeleteKeyEx Windows API function, which is specific to 64-bit versions of Windows. See the RegDeleteKeyEx documentation. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys. reserved is a reserved integer, and must be zero. The default is zero. access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WOW64_64KEY. See Access Rights for other allowed values. This method can not delete keys with subkeys. If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised. On unsupported Windows versions, NotImplementedError is raised. Raises an auditing event winreg.DeleteKey with arguments key, sub_key, access. New in version 3.2. Changed in version 3.3: See above.
winreg.DeleteValue(key, value)
Removes a named value from a registry key. key is an already open key, or one of the predefined HKEY_* constants. value is a string that identifies the value to remove. Raises an auditing event winreg.DeleteValue with arguments key, value.
winreg.EnumKey(key, index)
Enumerates subkeys of an open registry key, returning a string. key is an already open key, or one of the predefined HKEY_* constants. index is an integer that identifies the index of the key to retrieve. The function retrieves the name of one subkey each time it is called. It is typically called repeatedly until an OSError exception is raised, indicating, no more values are available. Raises an auditing event winreg.EnumKey with arguments key, index. Changed in version 3.3: See above.
winreg.EnumValue(key, index)
Enumerates values of an open registry key, returning a tuple. key is an already open key, or one of the predefined HKEY_* constants. index is an integer that identifies the index of the value to retrieve. The function retrieves the name of one subkey each time it is called. It is typically called repeatedly, until an OSError exception is raised, indicating no more values. The result is a tuple of 3 items:
Index Meaning
0 A string that identifies the value name
1 An object that holds the value data, and whose type depends on the underlying registry type
2 An integer that identifies the type of the value data (see table in docs for SetValueEx()) Raises an auditing event winreg.EnumValue with arguments key, index. Changed in version 3.3: See above.
winreg.ExpandEnvironmentStrings(str)
Expands environment variable placeholders %NAME% in strings like REG_EXPAND_SZ: >>> ExpandEnvironmentStrings('%windir%')
'C:\\Windows'
Raises an auditing event winreg.ExpandEnvironmentStrings with argument str.
winreg.FlushKey(key)
Writes all the attributes of a key to the registry. key is an already open key, or one of the predefined HKEY_* constants. It is not necessary to call FlushKey() to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are also flushed to disk at system shutdown. Unlike CloseKey(), the FlushKey() method returns only when all the data has been written to the registry. An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk. Note If you don’t know whether a FlushKey() call is required, it probably isn’t.
winreg.LoadKey(key, sub_key, file_name)
Creates a subkey under the specified key and stores registration information from a specified file into that subkey. key is a handle returned by ConnectRegistry() or one of the constants HKEY_USERS or HKEY_LOCAL_MACHINE. sub_key is a string that identifies the subkey to load. file_name is the name of the file to load registry data from. This file must have been created with the SaveKey() function. Under the file allocation table (FAT) file system, the filename may not have an extension. A call to LoadKey() fails if the calling process does not have the SE_RESTORE_PRIVILEGE privilege. Note that privileges are different from permissions – see the RegLoadKey documentation for more details. If key is a handle returned by ConnectRegistry(), then the path specified in file_name is relative to the remote computer. Raises an auditing event winreg.LoadKey with arguments key, sub_key, file_name.
winreg.OpenKey(key, sub_key, reserved=0, access=KEY_READ)
winreg.OpenKeyEx(key, sub_key, reserved=0, access=KEY_READ)
Opens the specified key, returning a handle object. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that identifies the sub_key to open. reserved is a reserved integer, and must be zero. The default is zero. access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ. See Access Rights for other allowed values. The result is a new handle to the specified key. If the function fails, OSError is raised. Raises an auditing event winreg.OpenKey with arguments key, sub_key, access. Raises an auditing event winreg.OpenKey/result with argument key. Changed in version 3.2: Allow the use of named arguments. Changed in version 3.3: See above.
winreg.QueryInfoKey(key)
Returns information about a key, as a tuple. key is an already open key, or one of the predefined HKEY_* constants. The result is a tuple of 3 items:
Index Meaning
0 An integer giving the number of sub keys this key has.
1 An integer giving the number of values this key has.
2 An integer giving when the key was last modified (if available) as 100’s of nanoseconds since Jan 1, 1601. Raises an auditing event winreg.QueryInfoKey with argument key.
winreg.QueryValue(key, sub_key)
Retrieves the unnamed value for a key, as a string. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that holds the name of the subkey with which the value is associated. If this parameter is None or empty, the function retrieves the value set by the SetValue() method for the key identified by key. Values in the registry have name, type, and data components. This method retrieves the data for a key’s first value that has a NULL name. But the underlying API call doesn’t return the type, so always use QueryValueEx() if possible. Raises an auditing event winreg.QueryValue with arguments key, sub_key, value_name.
winreg.QueryValueEx(key, value_name)
Retrieves the type and data for a specified value name associated with an open registry key. key is an already open key, or one of the predefined HKEY_* constants. value_name is a string indicating the value to query. The result is a tuple of 2 items:
Index Meaning
0 The value of the registry item.
1 An integer giving the registry type for this value (see table in docs for SetValueEx()) Raises an auditing event winreg.QueryValue with arguments key, sub_key, value_name.
winreg.SaveKey(key, file_name)
Saves the specified key, and all its subkeys to the specified file. key is an already open key, or one of the predefined HKEY_* constants. file_name is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file allocation table (FAT) file systems by the LoadKey() method. If key represents a key on a remote computer, the path described by file_name is relative to the remote computer. The caller of this method must possess the SeBackupPrivilege security privilege. Note that privileges are different than permissions – see the Conflicts Between User Rights and Permissions documentation for more details. This function passes NULL for security_attributes to the API. Raises an auditing event winreg.SaveKey with arguments key, file_name.
winreg.SetValue(key, sub_key, type, value)
Associates a value with a specified key. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that names the subkey with which the value is associated. type is an integer that specifies the type of the data. Currently this must be REG_SZ, meaning only strings are supported. Use the SetValueEx() function for support for other data types. value is a string that specifies the new value. If the key specified by the sub_key parameter does not exist, the SetValue function creates it. Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently. The key identified by the key parameter must have been opened with KEY_SET_VALUE access. Raises an auditing event winreg.SetValue with arguments key, sub_key, type, value.
winreg.SetValueEx(key, value_name, reserved, type, value)
Stores data in the value field of an open registry key. key is an already open key, or one of the predefined HKEY_* constants. value_name is a string that names the subkey with which the value is associated. reserved can be anything – zero is always passed to the API. type is an integer that specifies the type of the data. See Value Types for the available types. value is a string that specifies the new value. This method can also set additional value and type information for the specified key. The key identified by the key parameter must have been opened with KEY_SET_VALUE access. To open the key, use the CreateKey() or OpenKey() methods. Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently. Raises an auditing event winreg.SetValue with arguments key, sub_key, type, value.
winreg.DisableReflectionKey(key)
Disables registry reflection for 32-bit processes running on a 64-bit operating system. key is an already open key, or one of the predefined HKEY_* constants. Will generally raise NotImplementedError if executed on a 32-bit operating system. If the key is not on the reflection list, the function succeeds but has no effect. Disabling reflection for a key does not affect reflection of any subkeys. Raises an auditing event winreg.DisableReflectionKey with argument key.
winreg.EnableReflectionKey(key)
Restores registry reflection for the specified disabled key. key is an already open key, or one of the predefined HKEY_* constants. Will generally raise NotImplementedError if executed on a 32-bit operating system. Restoring reflection for a key does not affect reflection of any subkeys. Raises an auditing event winreg.EnableReflectionKey with argument key.
winreg.QueryReflectionKey(key)
Determines the reflection state for the specified key. key is an already open key, or one of the predefined HKEY_* constants. Returns True if reflection is disabled. Will generally raise NotImplementedError if executed on a 32-bit operating system. Raises an auditing event winreg.QueryReflectionKey with argument key.
Constants The following constants are defined for use in many _winreg functions. HKEY_* Constants
winreg.HKEY_CLASSES_ROOT
Registry entries subordinate to this key define types (or classes) of documents and the properties associated with those types. Shell and COM applications use the information stored under this key.
winreg.HKEY_CURRENT_USER
Registry entries subordinate to this key define the preferences of the current user. These preferences include the settings of environment variables, data about program groups, colors, printers, network connections, and application preferences.
winreg.HKEY_LOCAL_MACHINE
Registry entries subordinate to this key define the physical state of the computer, including data about the bus type, system memory, and installed hardware and software.
winreg.HKEY_USERS
Registry entries subordinate to this key define the default user configuration for new users on the local computer and the user configuration for the current user.
winreg.HKEY_PERFORMANCE_DATA
Registry entries subordinate to this key allow you to access performance data. The data is not actually stored in the registry; the registry functions cause the system to collect the data from its source.
winreg.HKEY_CURRENT_CONFIG
Contains information about the current hardware profile of the local computer system.
winreg.HKEY_DYN_DATA
This key is not used in versions of Windows after 98.
Access Rights For more information, see Registry Key Security and Access.
winreg.KEY_ALL_ACCESS
Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK access rights.
winreg.KEY_WRITE
Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.
winreg.KEY_READ
Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.
winreg.KEY_EXECUTE
Equivalent to KEY_READ.
winreg.KEY_QUERY_VALUE
Required to query the values of a registry key.
winreg.KEY_SET_VALUE
Required to create, delete, or set a registry value.
winreg.KEY_CREATE_SUB_KEY
Required to create a subkey of a registry key.
winreg.KEY_ENUMERATE_SUB_KEYS
Required to enumerate the subkeys of a registry key.
winreg.KEY_NOTIFY
Required to request change notifications for a registry key or for subkeys of a registry key.
winreg.KEY_CREATE_LINK
Reserved for system use.
64-bit Specific For more information, see Accessing an Alternate Registry View.
winreg.KEY_WOW64_64KEY
Indicates that an application on 64-bit Windows should operate on the 64-bit registry view.
winreg.KEY_WOW64_32KEY
Indicates that an application on 64-bit Windows should operate on the 32-bit registry view.
Value Types For more information, see Registry Value Types.
winreg.REG_BINARY
Binary data in any form.
winreg.REG_DWORD
32-bit number.
winreg.REG_DWORD_LITTLE_ENDIAN
A 32-bit number in little-endian format. Equivalent to REG_DWORD.
winreg.REG_DWORD_BIG_ENDIAN
A 32-bit number in big-endian format.
winreg.REG_EXPAND_SZ
Null-terminated string containing references to environment variables (%PATH%).
winreg.REG_LINK
A Unicode symbolic link.
winreg.REG_MULTI_SZ
A sequence of null-terminated strings, terminated by two null characters. (Python handles this termination automatically.)
winreg.REG_NONE
No defined value type.
winreg.REG_QWORD
A 64-bit number. New in version 3.6.
winreg.REG_QWORD_LITTLE_ENDIAN
A 64-bit number in little-endian format. Equivalent to REG_QWORD. New in version 3.6.
winreg.REG_RESOURCE_LIST
A device-driver resource list.
winreg.REG_FULL_RESOURCE_DESCRIPTOR
A hardware setting.
winreg.REG_RESOURCE_REQUIREMENTS_LIST
A hardware resource list.
winreg.REG_SZ
A null-terminated string.
Registry Handle Objects This object wraps a Windows HKEY object, automatically closing it when the object is destroyed. To guarantee cleanup, you can call either the Close() method on the object, or the CloseKey() function. All registry functions in this module return one of these objects. All registry functions in this module which accept a handle object also accept an integer, however, use of the handle object is encouraged. Handle objects provide semantics for __bool__() – thus if handle:
print("Yes")
will print Yes if the handle is currently valid (has not been closed or detached). The object also support comparison semantics, so handle objects will compare true if they both reference the same underlying Windows handle value. Handle objects can be converted to an integer (e.g., using the built-in int() function), in which case the underlying Windows handle value is returned. You can also use the Detach() method to return the integer handle, and also disconnect the Windows handle from the handle object.
PyHKEY.Close()
Closes the underlying Windows handle. If the handle is already closed, no error is raised.
PyHKEY.Detach()
Detaches the Windows handle from the handle object. The result is an integer that holds the value of the handle before it is detached. If the handle is already detached or closed, this will return zero. After calling this function, the handle is effectively invalidated, but the handle is not closed. You would call this function when you need the underlying Win32 handle to exist beyond the lifetime of the handle object. Raises an auditing event winreg.PyHKEY.Detach with argument key.
PyHKEY.__enter__()
PyHKEY.__exit__(*exc_info)
The HKEY object implements __enter__() and __exit__() and thus supports the context protocol for the with statement: with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
... # work with key
will automatically close key when control leaves the with block. | |
doc_23941 |
Calculate the rolling sample covariance. Parameters
other:Series or DataFrame, optional
If not supplied then will default to self and produce pairwise output.
pairwise:bool, default None
If False then only matching columns between self and other will be used and the output will be a DataFrame. If True then all pairwise combinations will be calculated and the output will be a MultiIndexed DataFrame in the case of DataFrame inputs. In the case of missing elements, only complete pairwise observations will be used.
ddof:int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. **kwargs
For NumPy compatibility and will not have an effect on the result. Returns
Series or DataFrame
Return type is the same as the original object with np.float64 dtype. See also pandas.Series.rolling
Calling rolling with Series data. pandas.DataFrame.rolling
Calling rolling with DataFrames. pandas.Series.cov
Aggregating cov for Series. pandas.DataFrame.cov
Aggregating cov for DataFrame. | |
doc_23942 | Return the inverse hyperbolic sine of x. There are two branch cuts: One extends from 1j along the imaginary axis to ∞j, continuous from the right. The other extends from -1j along the imaginary axis to -∞j, continuous from the left. | |
doc_23943 | See Migration guide for more details. tf.compat.v1.config.experimental.disable_mlir_graph_optimization
tf.config.experimental.disable_mlir_graph_optimization() | |
doc_23944 | class sklearn.feature_selection.GenericUnivariateSelect(score_func=<function f_classif>, *, mode='percentile', param=1e-05) [source]
Univariate feature selector with configurable strategy. Read more in the User Guide. Parameters
score_funccallable, default=f_classif
Function taking two arrays X and y, and returning a pair of arrays (scores, pvalues). For modes ‘percentile’ or ‘kbest’ it can return a single array scores.
mode{‘percentile’, ‘k_best’, ‘fpr’, ‘fdr’, ‘fwe’}, default=’percentile’
Feature selection mode.
paramfloat or int depending on the feature selection mode, default=1e-5
Parameter of the corresponding mode. Attributes
scores_array-like of shape (n_features,)
Scores of features.
pvalues_array-like of shape (n_features,)
p-values of feature scores, None if score_func returned scores only. See also
f_classif
ANOVA F-value between label/feature for classification tasks.
mutual_info_classif
Mutual information for a discrete target.
chi2
Chi-squared stats of non-negative features for classification tasks.
f_regression
F-value between label/feature for regression tasks.
mutual_info_regression
Mutual information for a continuous target.
SelectPercentile
Select features based on percentile of the highest scores.
SelectKBest
Select features based on the k highest scores.
SelectFpr
Select features based on a false positive rate test.
SelectFdr
Select features based on an estimated false discovery rate.
SelectFwe
Select features based on family-wise error rate. Examples >>> from sklearn.datasets import load_breast_cancer
>>> from sklearn.feature_selection import GenericUnivariateSelect, chi2
>>> X, y = load_breast_cancer(return_X_y=True)
>>> X.shape
(569, 30)
>>> transformer = GenericUnivariateSelect(chi2, mode='k_best', param=20)
>>> X_new = transformer.fit_transform(X, y)
>>> X_new.shape
(569, 20)
Methods
fit(X, y) Run score function on (X, y) and get the appropriate features.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform.
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]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | |
doc_23945 | Puts values from the tensor values into the tensor self using the indices specified in indices (which is a tuple of Tensors). The expression tensor.index_put_(indices, values) is equivalent to tensor[indices] = values. Returns self. If accumulate is True, the elements in values are added to self. If accumulate is False, the behavior is undefined if indices contain duplicate elements. Parameters
indices (tuple of LongTensor) – tensors used to index into self.
values (Tensor) – tensor of same dtype as self.
accumulate (bool) – whether to accumulate into self | |
doc_23946 | Call func with the given arguments under control of the Trace object with the current tracing parameters. | |
doc_23947 |
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
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
figure Figure
gid str
height float
in_layout bool
label object
offset (float, float) or callable
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_23948 | See Migration guide for more details. tf.compat.v1.train.queue_runner.add_queue_runner
tf.compat.v1.train.add_queue_runner(
qr, collection=tf.GraphKeys.QUEUE_RUNNERS
)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: To construct input pipelines, use the tf.data module. When building a complex model that uses many queues it is often difficult to gather all the queue runners that need to be run. This convenience function allows you to add a queue runner to a well known collection in the graph. The companion method start_queue_runners() can be used to start threads for all the collected queue runners.
Args
qr A QueueRunner.
collection A GraphKey specifying the graph collection to add the queue runner to. Defaults to GraphKeys.QUEUE_RUNNERS. | |
doc_23949 |
Perform classification on an array of test vectors X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated for classification. Returns
Cndarray of shape (n_samples,)
Predicted target values for X, values are from classes_ | |
doc_23950 |
Get the text of the label. | |
doc_23951 | tf.compat.v1.metrics.false_negatives_at_thresholds(
labels, predictions, thresholds, weights=None, metrics_collections=None,
updates_collections=None, name=None
)
If weights is None, weights default to 1. Use weights of 0 to mask values.
Args
labels A Tensor whose shape matches predictions. Will be cast to bool.
predictions A floating point Tensor of arbitrary shape and whose values are in the range [0, 1].
thresholds A python list or tuple of float thresholds in [0, 1].
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 false_negatives 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
false_negatives A float Tensor of shape [len(thresholds)].
update_op An operation that updates the false_negatives variable and returns its current value.
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_23952 |
Draw an RGBA image. Parameters
gcGraphicsContextBase
A graphics context with clipping information.
xscalar
The distance in physical units (i.e., dots or pixels) from the left hand side of the canvas.
yscalar
The distance in physical units (i.e., dots or pixels) from the bottom side of the canvas.
im(N, M, 4) array-like of np.uint8
An array of RGBA pixels.
transformmatplotlib.transforms.Affine2DBase
If and only if the concrete backend is written such that option_scale_image() returns True, an affine transformation (i.e., an Affine2DBase) may be passed to draw_image(). The translation vector of the transformation is given in physical units (i.e., dots or pixels). Note that the transformation does not override x and y, and has to be applied before translating the result by x and y (this can be accomplished by adding x and y to the translation vector defined by transform). | |
doc_23953 |
Roll provided date backward to next offset only if not on offset. Returns
TimeStamp
Rolled timestamp if not on offset, otherwise unchanged timestamp. | |
doc_23954 |
Return (x1 >= x2) element-wise. Unlike numpy.greater_equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters
x1, x2array_like of str or unicode
Input arrays of the same shape. Returns
outndarray
Output array of bools. See also
equal, not_equal, less_equal, greater, less | |
doc_23955 | Extract the url from a wrapped URL (that is, a string formatted as <URL:scheme://host/path>, <scheme://host/path>, URL:scheme://host/path or scheme://host/path). If url is not a wrapped URL, it is returned without changes. | |
doc_23956 |
Initialize self. See help(type(self)) for accurate signature. | |
doc_23957 |
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). | |
doc_23958 |
Return the dot product of two arrays. This function is the equivalent of numpy.dot that takes masked values into account. Note that strict and out are in different position than in the method version. In order to maintain compatibility with the corresponding method, it is recommended that the optional arguments be treated as keyword only. At some point that may be mandatory. Note Works only with 2-D arrays at the moment. Parameters
a, bmasked_array_like
Inputs arrays.
strictbool, optional
Whether masked data are propagated (True) or set to 0 (False) for the computation. Default is False. Propagating the mask means that if a masked value appears in a row or column, the whole row or column is considered masked.
outmasked_array, optional
Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. New in version 1.10.2. See also numpy.dot
Equivalent function for ndarrays. Examples >>> a = np.ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]])
>>> b = np.ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]])
>>> np.ma.dot(a, b)
masked_array(
data=[[21, 26],
[45, 64]],
mask=[[False, False],
[False, False]],
fill_value=999999)
>>> np.ma.dot(a, b, strict=True)
masked_array(
data=[[--, --],
[--, 64]],
mask=[[ True, True],
[ True, False]],
fill_value=999999) | |
doc_23959 |
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. | |
doc_23960 | This method is called to handle the end tag of an element (e.g. </div>). The tag argument is the name of the tag converted to lower case. | |
doc_23961 |
Bases: matplotlib.projections.geo._GeoTransform Create a new geographical transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved space. has_inverse=True
True if this transform has a corresponding inverse transform.
inverted()[source]
Return the corresponding inverse transformation. It holds x == self.inverted().transform(self.transform(x)). The return value of this method should be treated as temporary. An update to self does not cause a corresponding update to its inverted copy.
transform_non_affine(xy)[source]
Apply only the non-affine part of this transformation. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). In non-affine transformations, this is generally equivalent to transform(values). In affine transformations, this is always a no-op. Parameters
valuesarray
The input values as NumPy array of length input_dims or shape (N x input_dims). Returns
array
The output values as NumPy array of length input_dims or shape (N x output_dims), depending on the input. | |
doc_23962 | Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel’s hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns
thetandarray of shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel | |
doc_23963 | Handle an XML-RPC request. If request_text is given, it should be the POST data provided by the HTTP server, otherwise the contents of stdin will be used. | |
doc_23964 | Alias for Area class. | |
doc_23965 | Return a BytesGenerator object that will write any message provided to the flatten() method, or any surrogateescape encoded text provided to the write() method, to the file-like object outfp. outfp must support a write method that accepts binary data. If optional mangle_from_ is True, put a > character in front of any line in the body that starts with the exact string "From ", that is From followed by a space at the beginning of a line. mangle_from_ defaults to the value of the mangle_from_ setting of the policy (which is True for the compat32 policy and False for all others). mangle_from_ is intended for use when messages are stored in unix mbox format (see mailbox and WHY THE CONTENT-LENGTH FORMAT IS BAD). If maxheaderlen is not None, refold any header lines that are longer than maxheaderlen, or if 0, do not rewrap any headers. If manheaderlen is None (the default), wrap headers and other message lines according to the policy settings. If policy is specified, use that policy to control message generation. If policy is None (the default), use the policy associated with the Message or EmailMessage object passed to flatten to control the message generation. See email.policy for details on what policy controls. New in version 3.2. Changed in version 3.3: Added the policy keyword. Changed in version 3.6: The default behavior of the mangle_from_ and maxheaderlen parameters is to follow the policy.
flatten(msg, unixfrom=False, linesep=None)
Print the textual representation of the message object structure rooted at msg to the output file specified when the BytesGenerator instance was created. If the policy option cte_type is 8bit (the default), copy any headers in the original parsed message that have not been modified to the output with any bytes with the high bit set reproduced as in the original, and preserve the non-ASCII Content-Transfer-Encoding of any body parts that have them. If cte_type is 7bit, convert the bytes with the high bit set as needed using an ASCII-compatible Content-Transfer-Encoding. That is, transform parts with non-ASCII Content-Transfer-Encoding (Content-Transfer-Encoding: 8bit) to an ASCII compatible Content-Transfer-Encoding, and encode RFC-invalid non-ASCII bytes in headers using the MIME unknown-8bit character set, thus rendering them RFC-compliant. If unixfrom is True, print the envelope header delimiter used by the Unix mailbox format (see mailbox) before the first of the RFC 5322 headers of the root message object. If the root object has no envelope header, craft a standard one. The default is False. Note that for subparts, no envelope header is ever printed. If linesep is not None, use it as the separator character between all the lines of the flattened message. If linesep is None (the default), use the value specified in the policy.
clone(fp)
Return an independent clone of this BytesGenerator instance with the exact same option settings, and fp as the new outfp.
write(s)
Encode s using the ASCII codec and the surrogateescape error handler, and pass it to the write method of the outfp passed to the BytesGenerator’s constructor. | |
doc_23966 | True if cookie should only be returned over a secure connection. | |
doc_23967 | bytearray.upper()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart. For example: >>> b'Hello World'.upper()
b'HELLO WORLD'
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. 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_23968 |
Other Members
QUANTIZED_DTYPES
bfloat16 tf.dtypes.DType
bool tf.dtypes.DType
complex128 tf.dtypes.DType
complex64 tf.dtypes.DType
double tf.dtypes.DType
float16 tf.dtypes.DType
float32 tf.dtypes.DType
float64 tf.dtypes.DType
half tf.dtypes.DType
int16 tf.dtypes.DType
int32 tf.dtypes.DType
int64 tf.dtypes.DType
int8 tf.dtypes.DType
qint16 tf.dtypes.DType
qint32 tf.dtypes.DType
qint8 tf.dtypes.DType
quint16 tf.dtypes.DType
quint8 tf.dtypes.DType
resource tf.dtypes.DType
string tf.dtypes.DType
uint16 tf.dtypes.DType
uint32 tf.dtypes.DType
uint64 tf.dtypes.DType
uint8 tf.dtypes.DType
variant tf.dtypes.DType | |
doc_23969 |
Return the Transform associated with this scale. | |
doc_23970 |
Repeat elements of an array. Refer to numpy.repeat for full documentation. See also numpy.repeat
equivalent function | |
doc_23971 | Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way. | |
doc_23972 |
Update the view limits and position for each axes from the current stack position. If any axes are present in the figure that aren't in the current stack position, use the home view limits for those axes and don't update any positions. | |
doc_23973 | Returns a list of the help texts of all validators. These explain the password requirements to the user. | |
doc_23974 |
Computes and returns a mask for the input tensor t. Starting from a base default_mask (which should be a mask of ones if the tensor has not been pruned yet), generate a mask to apply on top of the default_mask by zeroing out the channels along the specified dim with the lowest Ln-norm. Parameters
t (torch.Tensor) – tensor representing the parameter to prune
default_mask (torch.Tensor) – Base mask from previous pruning iterations, that need to be respected after the new mask is applied. Same dims as t. Returns
mask to apply to t, of same dims as t Return type
mask (torch.Tensor) Raises
IndexError – if self.dim >= len(t.shape) | |
doc_23975 |
Get or set the PRNG state Returns
statedict
Dictionary containing the information required to describe the state of the PRNG | |
doc_23976 |
Trigonometric inverse cosine, element-wise. The inverse of cos so that, if y = cos(x), then x = arccos(y). Parameters
xarray_like
x-coordinate on the unit circle. For real arguments, the domain is [-1, 1].
outndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs
For other keyword-only arguments, see the ufunc docs. Returns
anglendarray
The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar. See also
cos, arctan, arcsin, emath.arccos
Notes arccos is a multivalued function: for each x there are infinitely many numbers z such that cos(z) = x. The convention is to return the angle z whose real part lies in [0, pi]. For real-valued input data types, arccos always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arccos is a complex analytic function that has branch cuts [-inf, -1] and [1, inf] and is continuous from above on the former and from below on the latter. The inverse cos is also known as acos or cos^-1. References M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 79. https://personal.math.ubc.ca/~cbm/aands/page_79.htm Examples We expect the arccos of 1 to be 0, and of -1 to be pi: >>> np.arccos([1, -1])
array([ 0. , 3.14159265])
Plot arccos: >>> import matplotlib.pyplot as plt
>>> x = np.linspace(-1, 1, num=100)
>>> plt.plot(x, np.arccos(x))
>>> plt.axis('tight')
>>> plt.show() | |
doc_23977 |
Compute the log-likelihood of each sample Parameters
Xndarray of shape (n_samples, n_features)
The data Returns
llndarray of shape (n_samples,)
Log-likelihood of each sample under the current model | |
doc_23978 |
The number of output dimensions of this transform. Must be overridden (with integers) in the subclass. | |
doc_23979 |
Computes the inverse cumulative distribution function using transform(s) and computing the score of the base distribution. | |
doc_23980 | tf.experimental.numpy.conjugate(
x
)
Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.conjugate. | |
doc_23981 | See Migration guide for more details. tf.compat.v1.raw_ops.QuantizedMaxPool
tf.raw_ops.QuantizedMaxPool(
input, min_input, max_input, ksize, strides, padding, name=None
)
Args
input A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. The 4D (batch x rows x cols x depth) Tensor to MaxReduce over.
min_input A Tensor of type float32. The float value that the lowest quantized input value represents.
max_input A Tensor of type float32. The float value that the highest quantized input value represents.
ksize A list of ints. The size of the window for each dimension of the input tensor. The length must be 4 to match the number of dimensions of the input.
strides A list of ints. The stride of the sliding window for each dimension of the input tensor. The length must be 4 to match the number of dimensions of the input.
padding A string from: "SAME", "VALID". The type of padding algorithm to use.
name A name for the operation (optional).
Returns A tuple of Tensor objects (output, min_output, max_output). output A Tensor. Has the same type as input.
min_output A Tensor of type float32.
max_output A Tensor of type float32. | |
doc_23982 |
Change the sign of x1 to that of x2, element-wise. If x2 is a scalar, its sign will be copied to all elements of x1. Parameters
x1array_like
Values to change the sign of.
x2array_like
The sign of x2 is copied to x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs
For other keyword-only arguments, see the ufunc docs. Returns
outndarray or scalar
The values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars. Examples >>> np.copysign(1.3, -1)
-1.3
>>> 1/np.copysign(0, 1)
inf
>>> 1/np.copysign(0, -1)
-inf
>>> np.copysign([-1, 0, 1], -1.1)
array([-1., -0., -1.])
>>> np.copysign([-1, 0, 1], np.arange(3)-1)
array([-1., 0., 1.]) | |
doc_23983 |
A character indicating the byte-order of this data-type object. One of:
‘=’ native
‘<’ little-endian
‘>’ big-endian
‘|’ not applicable All built-in data-type objects have byteorder either ‘=’ or ‘|’. Examples >>> dt = np.dtype('i2')
>>> dt.byteorder
'='
>>> # endian is not relevant for 8 bit numbers
>>> np.dtype('i1').byteorder
'|'
>>> # or ASCII strings
>>> np.dtype('S2').byteorder
'|'
>>> # Even if specific code is given, and it is native
>>> # '=' is the byteorder
>>> import sys
>>> sys_is_le = sys.byteorder == 'little'
>>> native_code = sys_is_le and '<' or '>'
>>> swapped_code = sys_is_le and '>' or '<'
>>> dt = np.dtype(native_code + 'i2')
>>> dt.byteorder
'='
>>> # Swapped code shows up as itself
>>> dt = np.dtype(swapped_code + 'i2')
>>> dt.byteorder == swapped_code
True | |
doc_23984 | class sklearn.feature_selection.SequentialFeatureSelector(estimator, *, n_features_to_select=None, direction='forward', scoring=None, cv=5, n_jobs=None) [source]
Transformer that performs Sequential Feature Selection. This Sequential Feature Selector adds (forward selection) or removes (backward selection) features to form a feature subset in a greedy fashion. At each stage, this estimator chooses the best feature to add or remove based on the cross-validation score of an estimator. Read more in the User Guide. New in version 0.24. Parameters
estimatorestimator instance
An unfitted estimator.
n_features_to_selectint or float, default=None
The number of features to select. If None, half of the features are selected. If integer, the parameter is the absolute number of features to select. If float between 0 and 1, it is the fraction of features to select. direction: {‘forward’, ‘backward’}, default=’forward’
Whether to perform forward selection or backward selection.
scoringstr, callable, list/tuple or dict, default=None
A single str (see The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions) to evaluate the predictions on the test set. NOTE that when using custom scorers, each scorer should return a single value. Metric functions returning a list/array of values can be wrapped into multiple scorers that return one value each. If None, the estimator’s score method is used.
cvint, cross-validation generator or an iterable, default=None
Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross validation, integer, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.
n_jobsint, default=None
Number of jobs to run in parallel. When evaluating a new feature to add or remove, the cross-validation procedure is parallel over the folds. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
n_features_to_select_int
The number of features that were selected.
support_ndarray of shape (n_features,), dtype=bool
The mask of selected features. See also
RFE
Recursive feature elimination based on importance weights.
RFECV
Recursive feature elimination based on importance weights, with automatic selection of the number of features.
SelectFromModel
Feature selection based on thresholds of importance weights. Examples >>> from sklearn.feature_selection import SequentialFeatureSelector
>>> from sklearn.neighbors import KNeighborsClassifier
>>> from sklearn.datasets import load_iris
>>> X, y = load_iris(return_X_y=True)
>>> knn = KNeighborsClassifier(n_neighbors=3)
>>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3)
>>> sfs.fit(X, y)
SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3),
n_features_to_select=3)
>>> sfs.get_support()
array([ True, False, True, True])
>>> sfs.transform(X).shape
(150, 3)
Methods
fit(X, y) Learn the features to select.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Learn the features to select. Parameters
Xarray-like of shape (n_samples, n_features)
Training vectors.
yarray-like of shape (n_samples,)
Target values. Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform.
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]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features.
Examples using sklearn.feature_selection.SequentialFeatureSelector
Release Highlights for scikit-learn 0.24
Model-based and sequential feature selection | |
doc_23985 | operator.__neg__(obj)
Return obj negated (-obj). | |
doc_23986 |
Unsigned integer type, compatible with C unsigned long. Character code
'L' Alias on this platform (Linux x86_64)
numpy.uint64: 64-bit unsigned integer (0 to 18_446_744_073_709_551_615). Alias on this platform (Linux x86_64)
numpy.uintp: Unsigned integer large enough to fit pointer, compatible with C uintptr_t. | |
doc_23987 |
Applies the element-wise function: Tanhshrink(x)=x−tanh(x)\text{Tanhshrink}(x) = x - \tanh(x)
Shape:
Input: (N,∗)(N, *) where * means, any number of additional dimensions Output: (N,∗)(N, *) , same shape as the input Examples: >>> m = nn.Tanhshrink()
>>> input = torch.randn(2)
>>> output = m(input) | |
doc_23988 |
Bases: mpl_toolkits.axisartist.axis_artist.AttributeCopier, matplotlib.lines.Line2D Ticks are derived from Line2D, and note that ticks themselves are markers. Thus, you should use set_mec, set_mew, etc. To change the tick size (length), you need to use set_ticksize. To change the direction of the ticks (ticks are in opposite direction of ticklabels by default), use set_tick_out(False). draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
get_color()[source]
Return the line color. See also set_color.
get_markeredgecolor()[source]
Return the marker edge color. See also set_markeredgecolor.
get_markeredgewidth()[source]
Return the marker edge width in points. See also set_markeredgewidth.
get_ref_artist()[source]
Return the underlying artist that actually defines some properties (e.g., color) of this artist.
get_tick_out()[source]
Return whether ticks are drawn inside or outside the axes.
get_ticksize()[source]
Return length of the ticks in points.
set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, dash_capstyle=<UNSET>, dash_joinstyle=<UNSET>, dashes=<UNSET>, data=<UNSET>, drawstyle=<UNSET>, fillstyle=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, locs_angles=<UNSET>, marker=<UNSET>, markeredgecolor=<UNSET>, markeredgewidth=<UNSET>, markerfacecolor=<UNSET>, markerfacecoloralt=<UNSET>, markersize=<UNSET>, markevery=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, solid_capstyle=<UNSET>, solid_joinstyle=<UNSET>, tick_out=<UNSET>, ticksize=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, xdata=<UNSET>, ydata=<UNSET>, zorder=<UNSET>)[source]
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
animated bool
antialiased or aa bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
color or c unknown
dash_capstyle CapStyle or {'butt', 'projecting', 'round'}
dash_joinstyle JoinStyle or {'miter', 'round', 'bevel'}
dashes sequence of floats (on/off ink in points) or (None, None)
data (2, N) array or two 1D arrays
drawstyle or ds {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
figure Figure
fillstyle {'full', 'left', 'right', 'bottom', 'top', 'none'}
gid str
in_layout bool
label object
linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw float
locs_angles unknown
marker marker style string, Path or MarkerStyle
markeredgecolor or mec color
markeredgewidth or mew float
markerfacecolor or mfc color
markerfacecoloralt or mfcalt color
markersize or ms float
markevery None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
path_effects AbstractPathEffect
picker float or callable[[Artist, Event], tuple[bool, dict]]
pickradius float
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
solid_capstyle CapStyle or {'butt', 'projecting', 'round'}
solid_joinstyle JoinStyle or {'miter', 'round', 'bevel'}
tick_out unknown
ticksize unknown
transform Transform
url str
visible bool
xdata 1D array
ydata 1D array
zorder float
set_color(color)[source]
Set the color of the line. Parameters
colorcolor
set_locs_angles(locs_angles)[source]
set_tick_out(b)[source]
Set whether ticks are drawn inside or outside the axes.
set_ticksize(ticksize)[source]
Set length of the ticks in points. | |
doc_23989 |
Trigonometric sine, element-wise. Parameters
xarray_like
Angle, in radians (\(2 \pi\) rad equals 360 degrees).
outndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs
For other keyword-only arguments, see the ufunc docs. Returns
yarray_like
The sine of each element of x. This is a scalar if x is a scalar. See also
arcsin, sinh, cos
Notes The sine is one of the fundamental functions of trigonometry (the mathematical study of triangles). Consider a circle of radius 1 centered on the origin. A ray comes in from the \(+x\) axis, makes an angle at the origin (measured counter-clockwise from that axis), and departs from the origin. The \(y\) coordinate of the outgoing ray’s intersection with the unit circle is the sine of that angle. It ranges from -1 for \(x=3\pi / 2\) to +1 for \(\pi / 2.\) The function has zeroes where the angle is a multiple of \(\pi\). Sines of angles between \(\pi\) and \(2\pi\) are negative. The numerous properties of the sine and related functions are included in any standard trigonometry text. Examples Print sine of one angle: >>> np.sin(np.pi/2.)
1.0
Print sines of an array of angles given in degrees: >>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ])
Plot the sine function: >>> import matplotlib.pylab as plt
>>> x = np.linspace(-np.pi, np.pi, 201)
>>> plt.plot(x, np.sin(x))
>>> plt.xlabel('Angle [rad]')
>>> plt.ylabel('sin(x)')
>>> plt.axis('tight')
>>> plt.show() | |
doc_23990 | number of cd drives on the system get_count() -> count Return the number of cd drives on the system. When you create CD objects you need to pass an integer id that must be lower than this count. The count will be 0 if there are no drives on the system. | |
doc_23991 | The type of action logged: ADDITION, CHANGE, DELETION. For example, to get a list of all additions done through the admin: from django.contrib.admin.models import ADDITION, LogEntry
LogEntry.objects.filter(action_flag=ADDITION) | |
doc_23992 | See Migration guide for more details. tf.compat.v1.saved_model.signature_def_utils.build_signature_def
tf.compat.v1.saved_model.build_signature_def(
inputs=None, outputs=None, method_name=None
)
Args
inputs Inputs of the SignatureDef defined as a proto map of string to tensor info.
outputs Outputs of the SignatureDef defined as a proto map of string to tensor info.
method_name Method name of the SignatureDef as a string.
Returns A SignatureDef protocol buffer constructed based on the supplied arguments. | |
doc_23993 |
Attributes
base Returns a copy of the calling offset object with n=1 and all other attributes equal.
cbday_roll Define default roll function to be called in apply method.
month_roll Define default roll function to be called in apply method.
offset Alias for self._offset.
calendar
freqstr
holidays
kwds
m_offset
n
name
nanos
normalize
rule_code
weekmask Methods
__call__(*args, **kwargs) Call self as a function.
rollback Roll provided date backward to next offset only if not on offset.
rollforward Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset | |
doc_23994 | Data found after the end of the compressed stream. Before the end of the stream is reached, this will be b"". | |
doc_23995 |
Handler for StepPatch instances. create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)[source] | |
doc_23996 | Copy count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst. If offset_src is None, then src is read from the current position; respectively for offset_dst. The files pointed by src and dst must reside in the same filesystem, otherwise an OSError is raised with errno set to errno.EXDEV. This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations. The copy is done as if both files are opened as binary. The return value is the amount of bytes copied. This could be less than the amount requested. Availability: Linux kernel >= 4.5 or glibc >= 2.27. New in version 3.8. | |
doc_23997 |
Initialize self. See help(type(self)) for accurate signature. | |
doc_23998 | start index of operation within bytecode sequence | |
doc_23999 | tf.divide Compat aliases for migration See Migration guide for more details. tf.compat.v1.divide, tf.compat.v1.math.divide
tf.math.divide(
x, y, name=None
)
For example:
x = tf.constant([16, 12, 11])
y = tf.constant([4, 6, 2])
tf.divide(x,y)
<tf.Tensor: shape=(3,), dtype=float64,
numpy=array([4. , 2. , 5.5])>
Args
x A Tensor
y A Tensor
name A name for the operation (optional).
Returns A Tensor with same shape as input |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.