_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_29300
Split an array into multiple sub-arrays vertically (row-wise). Please refer to the split documentation. vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension. See also split Split an array into multiple sub-arrays of equal size. Examples >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]) >>> np.vsplit(x, 2) [array([[0., 1., 2., 3.], [4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.], [12., 13., 14., 15.]])] >>> np.vsplit(x, np.array([3, 6])) [array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]]), array([[12., 13., 14., 15.]]), array([], shape=(0, 4), dtype=float64)] With a higher dimensional array the split is still along the first axis. >>> x = np.arange(8.0).reshape(2, 2, 2) >>> x array([[[0., 1.], [2., 3.]], [[4., 5.], [6., 7.]]]) >>> np.vsplit(x, 2) [array([[[0., 1.], [2., 3.]]]), array([[[4., 5.], [6., 7.]]])]
doc_29301
Concatenate strings in the Series/Index with given separator. If others is specified, this function concatenates the Series/Index and elements of others element-wise. If others is not passed, then all values in the Series/Index are concatenated into a single string with a given sep. Parameters others:Series, Index, DataFrame, np.ndarray or list-like Series, Index, DataFrame, np.ndarray (one- or two-dimensional) and other list-likes of strings must have the same length as the calling Series/Index, with the exception of indexed objects (i.e. Series/Index/DataFrame) if join is not None. If others is a list-like that contains a combination of Series, Index or np.ndarray (1-dim), then all elements will be unpacked and must satisfy the above criteria individually. If others is None, the method returns the concatenation of all strings in the calling Series/Index. sep:str, default ‘’ The separator between the different elements/columns. By default the empty string ‘’ is used. na_rep:str or None, default None Representation that is inserted for all missing values: If na_rep is None, and others is None, missing values in the Series/Index are omitted from the result. If na_rep is None, and others is not None, a row containing a missing value in any of the columns (before concatenation) will have a missing value in the result. join:{‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘left’ Determines the join-style between the calling Series/Index and any Series/Index/DataFrame in others (objects without an index need to match the length of the calling Series/Index). To disable alignment, use .values on any Series/Index/DataFrame in others. New in version 0.23.0. Changed in version 1.0.0: Changed default of join from None to ‘left’. Returns str, Series or Index If others is None, str is returned, otherwise a Series/Index (same type as caller) of objects is returned. See also split Split each string in the Series/Index. join Join lists contained as elements in the Series/Index. Examples When not passing others, all values are concatenated into a single string: >>> s = pd.Series(['a', 'b', np.nan, 'd']) >>> s.str.cat(sep=' ') 'a b d' By default, NA values in the Series are ignored. Using na_rep, they can be given a representation: >>> s.str.cat(sep=' ', na_rep='?') 'a b ? d' If others is specified, corresponding values are concatenated with the separator. Result will be a Series of strings. >>> s.str.cat(['A', 'B', 'C', 'D'], sep=',') 0 a,A 1 b,B 2 NaN 3 d,D dtype: object Missing values will remain missing in the result, but can again be represented using na_rep >>> s.str.cat(['A', 'B', 'C', 'D'], sep=',', na_rep='-') 0 a,A 1 b,B 2 -,C 3 d,D dtype: object If sep is not specified, the values are concatenated without separation. >>> s.str.cat(['A', 'B', 'C', 'D'], na_rep='-') 0 aA 1 bB 2 -C 3 dD dtype: object Series with different indexes can be aligned before concatenation. The join-keyword works as in other methods. >>> t = pd.Series(['d', 'a', 'e', 'c'], index=[3, 0, 4, 2]) >>> s.str.cat(t, join='left', na_rep='-') 0 aa 1 b- 2 -c 3 dd dtype: object >>> >>> s.str.cat(t, join='outer', na_rep='-') 0 aa 1 b- 2 -c 3 dd 4 -e dtype: object >>> >>> s.str.cat(t, join='inner', na_rep='-') 0 aa 2 -c 3 dd dtype: object >>> >>> s.str.cat(t, join='right', na_rep='-') 3 dd 0 aa 4 -e 2 -c dtype: object For more examples, see here.
doc_29302
Set the url for the artist. Parameters urlstr
doc_29303
Fit the random regressor. Parameters Xarray-like of shape (n_samples, n_features) Training data. yarray-like of shape (n_samples,) or (n_samples, n_outputs) Target values. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns selfobject
doc_29304
A thread-safe variant of call_soon(). Must be used to schedule callbacks from another thread. See the concurrency and multithreading section of the documentation.
doc_29305
Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. The default argument is used for groups that did not participate in the match; it defaults to None. For example: >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") >>> m.groupdict() {'first_name': 'Malcolm', 'last_name': 'Reynolds'}
doc_29306
Roll provided date forward to next offset only if not on offset. Returns TimeStamp Rolled timestamp if not on offset, otherwise unchanged timestamp.
doc_29307
See Migration guide for more details. tf.compat.v1.raw_ops.RFFT tf.raw_ops.RFFT( input, fft_length, Tcomplex=tf.dtypes.complex64, name=None ) Computes the 1-dimensional discrete Fourier transform of a real-valued signal over the inner-most dimension of input. Since the DFT of a real signal is Hermitian-symmetric, RFFT only returns the fft_length / 2 + 1 unique components of the FFT: the zero-frequency term, followed by the fft_length / 2 positive-frequency terms. Along the axis RFFT is computed on, if fft_length is smaller than the corresponding dimension of input, the dimension is cropped. If it is larger, the dimension is padded with zeros. Args input A Tensor. Must be one of the following types: float32, float64. A float32 tensor. fft_length A Tensor of type int32. An int32 tensor of shape [1]. The FFT length. Tcomplex An optional tf.DType from: tf.complex64, tf.complex128. Defaults to tf.complex64. name A name for the operation (optional). Returns A Tensor of type Tcomplex.
doc_29308
Return the Figure instance the artist belongs to.
doc_29309
Set the parameters of this estimator. Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in steps. Returns self
doc_29310
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.
doc_29311
This attribute contains the actual value of the instance. For integer and pointer types, it is an integer, for character types, it is a single character bytes object or string, for character pointer types it is a Python bytes object or string. When the value attribute is retrieved from a ctypes instance, usually a new object is returned each time. ctypes does not implement original object return, always a new object is constructed. The same is true for all other ctypes object instances.
doc_29312
tf.compat.v1.profiler.advise( graph=None, run_meta=None, options=_DEFAULT_ADVISE_OPTIONS ) Builds profiles and automatically check anomalies of various aspects. For more details: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/README.md Args graph tf.Graph. If None and eager execution is not enabled, use default graph. run_meta optional tensorflow.RunMetadata proto. It is necessary to to support run time information profiling, such as time and memory. options see ALL_ADVICE example above. Default checks everything. Returns Returns AdviceProto proto
doc_29313
Default widget: TextInput Empty value: Whatever you’ve given as empty_value. Normalizes to: A string. Uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid. Error message keys: required, max_length, min_length Has four optional arguments for validation: max_length min_length If provided, these arguments ensure that the string is at most or at least the given length. strip If True (default), the value will be stripped of leading and trailing whitespace. empty_value The value to use to represent “empty”. Defaults to an empty string.
doc_29314
Run the plot directive.
doc_29315
register a function to be called when pygame quits register_quit(callable) -> None When pygame.quit() is called, all registered quit functions are called. Pygame modules do this automatically when they are initializing, so this function will rarely be needed.
doc_29316
Return the snap setting. See set_snap for details.
doc_29317
Roll provided date backward to next offset only if not on offset. Returns TimeStamp Rolled timestamp if not on offset, otherwise unchanged timestamp.
doc_29318
Return whether the y-axis is autoscaled.
doc_29319
Set the value array from array-like A. Parameters Aarray-like or None The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
doc_29320
Subclass of OSError that is the base exception class for all the other exceptions provided by this module. Changed in version 3.4: SMTPException became subclass of OSError
doc_29321
Compares two operands using their abstract representation, ignoring sign.
doc_29322
Generate a Laguerre series with given roots. The function returns the coefficients of the polynomial \[p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\] in Laguerre form, where the r_n are the roots specified in roots. If a zero has multiplicity n, then it must appear in roots n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then roots looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are c, then \[p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x)\] The coefficient of the last term is not generally 1 for monic polynomials in Laguerre form. Parameters rootsarray_like Sequence containing the roots. Returns outndarray 1-D array of coefficients. If all roots are real then out is a real array, if some of the roots are complex, then out is complex even if all the coefficients in the result are real (see Examples below). See also numpy.polynomial.polynomial.polyfromroots numpy.polynomial.legendre.legfromroots numpy.polynomial.chebyshev.chebfromroots numpy.polynomial.hermite.hermfromroots numpy.polynomial.hermite_e.hermefromroots Examples >>> from numpy.polynomial.laguerre import lagfromroots, lagval >>> coef = lagfromroots((-1, 0, 1)) >>> lagval((-1, 0, 1), coef) array([0., 0., 0.]) >>> coef = lagfromroots((-1j, 1j)) >>> lagval((-1j, 1j), coef) array([0.+0.j, 0.+0.j])
doc_29323
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters rasterizedbool
doc_29324
Erases a Node from the Graph. Throws an exception if there are still users of that node in the Graph. Parameters to_erase (Node) – The Node to erase from the Graph.
doc_29325
Propagate qconfig through the module hierarchy and assign qconfig attribute on each leaf module Parameters module – input module qconfig_dict – dictionary that maps from name or type of submodule to quantization configuration, qconfig applies to all submodules of a given module unless qconfig for the submodules are specified (when the submodule already has qconfig attribute) Returns None, module is modified inplace with qconfig attached
doc_29326
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_29327
A random forest classifier. A random forest is 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. The sub-sample size is controlled with the max_samples parameter if bootstrap=True (default), otherwise the whole dataset is used to build each tree. Read more in the User Guide. Parameters n_estimatorsint, default=100 The number of trees in the forest. Changed in version 0.22: The default value of n_estimators changed from 10 to 100 in 0.22. criterion{“gini”, “entropy”}, default=”gini” The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain. Note: this parameter is tree-specific. max_depthint, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. 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_features{“auto”, “sqrt”, “log2”}, int or float, default=”auto” 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 round(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) (same as “auto”). If “log2”, then max_features=log2(n_features). If None, then max_features=n_features. 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. 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. 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. bootstrapbool, default=True Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_scorebool, default=False Whether to use out-of-bag samples to estimate the generalization accuracy. n_jobsint, default=None The number of jobs to run in parallel. fit, predict, decision_path and apply are all parallelized over the trees. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. random_stateint, RandomState instance or None, default=None Controls both the randomness of the bootstrapping of the samples used when building trees (if bootstrap=True) and the sampling of the features to consider when looking for the best split at each node (if max_features < n_features). See Glossary for details. verboseint, default=0 Controls the verbosity when fitting and predicting. 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 fit a whole new forest. See the Glossary. class_weight{“balanced”, “balanced_subsample”}, dict or list of dicts, default=None Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. 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)) The “balanced_subsample” mode is the same as “balanced” except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. 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. max_samplesint or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. If None (default), then draw X.shape[0] samples. If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples. Thus, max_samples should be in the interval (0, 1). New in version 0.22. Attributes base_estimator_DecisionTreeClassifier The child estimator template used to create the collection of fitted sub-estimators. estimators_list of DecisionTreeClassifier The collection of fitted sub-estimators. classes_ndarray of shape (n_classes,) or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). n_classes_int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). n_features_int The number of features when fit is performed. n_outputs_int The number of outputs when fit is performed. feature_importances_ndarray of shape (n_features,) The impurity-based feature importances. oob_score_float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True. oob_decision_function_ndarray of shape (n_samples, n_classes) Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_decision_function_ might contain NaN. This attribute exists only when oob_score is True. See also DecisionTreeClassifier, ExtraTreesClassifier Notes The default values for the parameters controlling the size of the trees (e.g. max_depth, min_samples_leaf, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data, max_features=n_features and bootstrap=False, 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 1 Breiman, “Random Forests”, Machine Learning, 45(1), 5-32, 2001. Examples >>> from sklearn.ensemble import RandomForestClassifier >>> from sklearn.datasets import make_classification >>> X, y = make_classification(n_samples=1000, n_features=4, ... n_informative=2, n_redundant=0, ... random_state=0, shuffle=False) >>> clf = RandomForestClassifier(max_depth=2, random_state=0) >>> clf.fit(X, y) RandomForestClassifier(...) >>> print(clf.predict([[0, 0, 0, 0]])) [1] Methods apply(X) Apply trees in the forest to X, return leaf indices. decision_path(X) Return the decision path in the forest. fit(X, y[, sample_weight]) Build a forest of trees from the training set (X, y). 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. apply(X) [source] Apply trees in the forest to X, return leaf indices. 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 into a sparse csr_matrix. Returns X_leavesndarray of shape (n_samples, n_estimators) For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in. decision_path(X) [source] Return the decision path in the forest. New in version 0.18. 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 into a sparse csr_matrix. Returns indicatorsparse matrix of shape (n_samples, n_nodes) Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. The matrix is of CSR format. n_nodes_ptrndarray of shape (n_estimators + 1,) The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator. 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) [source] Build a forest of trees from the training set (X, y). Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csc_matrix. yarray-like of shape (n_samples,) or (n_samples, n_outputs) The target values (class labels in classification, real numbers in regression). 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. 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. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. 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 into a sparse csr_matrix. Returns yndarray of shape (n_samples,) or (n_samples, n_outputs) The predicted classes. predict_log_proba(X) [source] Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the trees in the forest. 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 into a sparse csr_matrix. Returns pndarray of shape (n_samples, n_classes), or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. predict_proba(X) [source] Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. 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 into a sparse csr_matrix. Returns pndarray of shape (n_samples, n_classes), or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. score(X, y, sample_weight=None) [source] Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_29328
Run awaitable objects in the aws iterable concurrently. Return an iterator of coroutines. Each coroutine returned can be awaited to get the earliest next result from the iterable of the remaining awaitables. Raises asyncio.TimeoutError if the timeout occurs before all Futures are done. Deprecated since version 3.8, will be removed in version 3.10: The loop parameter. Example: for coro in as_completed(aws): earliest_result = await coro # ...
doc_29329
write an image file that is smoothscaled copy of an input file headless_no_windows_needed.main(fin, fout, w, h) -> None arguments: fin - name of an input image file fout - name of the output file to create/overwrite w, h - size of the rescaled image, as integer width and height How to use pygame with no windowing system, like on headless servers. Thumbnail generation with scaling is an example of what you can do with pygame. NOTE: the pygame scale function uses MMX/SSE if available, and can be run in multiple threads. If headless_no_windows_needed.py is run as a program it takes the following command line arguments: -scale inputimage outputimage new_width new_height eg. -scale in.png outpng 50 50
doc_29330
Return a duplicate of the context.
doc_29331
Integrate. Return a series instance that is the definite integral of the current series. Parameters mnon-negative int The number of integrations to perform. karray_like Integration constants. The first constant is applied to the first integration, the second to the second, and so on. The list of values must less than or equal to m in length and any missing values are set to zero. lbndScalar The lower bound of the definite integral. Returns new_seriesseries A new series representing the integral. The domain is the same as the domain of the integrated series.
doc_29332
Returns the number of non-fixed hyperparameters of the kernel.
doc_29333
Fit the clustering from features, or affinity matrix. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples) Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix. yIgnored Not used, present here for API consistency by convention. Returns self
doc_29334
See Migration guide for more details. tf.compat.v1.math.count_nonzero tf.compat.v1.count_nonzero( input_tensor=None, axis=None, keepdims=None, dtype=tf.dtypes.int64, name=None, reduction_indices=None, keep_dims=None, input=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (keep_dims). They will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims insteadWarning: SOME ARGUMENTS ARE DEPRECATED: (reduction_indices). They will be removed in a future version. Instructions for updating: reduction_indices is deprecated, use axis instead Reduces input_tensor along the dimensions given in axis. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis has no entries, all dimensions are reduced, and a tensor with a single element is returned. Note: Floating point comparison to zero is done by exact floating point equality check. Small values are not rounded to zero for purposes of the nonzero check. For example: x = tf.constant([[0, 1, 0], [1, 1, 0]]) tf.math.count_nonzero(x) # 3 tf.math.count_nonzero(x, 0) # [1, 2, 0] tf.math.count_nonzero(x, 1) # [1, 2] tf.math.count_nonzero(x, 1, keepdims=True) # [[1], [2]] tf.math.count_nonzero(x, [0, 1]) # 3 Note: Strings are compared against zero-length empty string "". Any string with a size greater than zero is already considered as nonzero. For example: x = tf.constant(["", "a", " ", "b", ""]) tf.math.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings. Args input_tensor The tensor to reduce. Should be of numeric type, bool, or string. axis The dimensions to reduce. If None (the default), reduces all dimensions. Must be in the range [-rank(input_tensor), rank(input_tensor)). keepdims If true, retains reduced dimensions with length 1. dtype The output dtype; defaults to tf.int64. name A name for the operation (optional). reduction_indices The old (deprecated) name for axis. keep_dims Deprecated alias for keepdims. input Overrides input_tensor. For compatibility. Returns The reduced tensor (number of nonzero values).
doc_29335
Return str(self).
doc_29336
Returns the list of dates of type date_type for which queryset contains entries. For example, get_date_list(qs, 'year') will return the list of years for which qs has entries. If date_type isn’t provided, the result of get_date_list_period() is used. date_type and ordering are passed to QuerySet.dates().
doc_29337
tf.random.experimental.Algorithm Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.Algorithm, tf.compat.v1.random.experimental.Algorithm Class Variables PHILOX tf.random.Algorithm THREEFRY tf.random.Algorithm
doc_29338
sklearn.datasets.load_sample_image(image_name) [source] Load the numpy array of a single sample image Read more in the User Guide. Parameters image_name{china.jpg, flower.jpg} The name of the sample image loaded Returns img3D array The image as a numpy array: height x width x color Examples >>> from sklearn.datasets import load_sample_image >>> china = load_sample_image('china.jpg') >>> china.dtype dtype('uint8') >>> china.shape (427, 640, 3) >>> flower = load_sample_image('flower.jpg') >>> flower.dtype dtype('uint8') >>> flower.shape (427, 640, 3) Examples using sklearn.datasets.load_sample_image Color Quantization using K-Means
doc_29339
Perform the SSL setup handshake. Changed in version 3.4: The handshake method also performs match_hostname() when the check_hostname attribute of the socket’s context is true. Changed in version 3.5: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration of the handshake. Changed in version 3.7: Hostname or IP address is matched by OpenSSL during handshake. The function match_hostname() is no longer used. In case OpenSSL refuses a hostname or IP address, the handshake is aborted early and a TLS alert message is send to the peer.
doc_29340
Uninitialize the display module quit() -> None This will shut down the entire display module. This means any active displays will be closed. This will also be handled automatically when the program exits. It is harmless to call this more than once, repeated calls have no effect.
doc_29341
See Migration guide for more details. tf.compat.v1.io.parse_tensor, tf.compat.v1.parse_tensor tf.io.parse_tensor( serialized, out_type, name=None ) Args serialized A Tensor of type string. A scalar string containing a serialized TensorProto proto. out_type A tf.DType. The type of the serialized tensor. The provided type must match the type of the serialized tensor and no implicit conversion will take place. name A name for the operation (optional). Returns A Tensor of type out_type.
doc_29342
See Migration guide for more details. tf.compat.v1.data.experimental.parallel_interleave tf.data.experimental.parallel_interleave( map_func, cycle_length, block_length=1, sloppy=False, buffer_output_elements=None, prefetch_input_elements=None ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.data.Dataset.interleave(map_func, cycle_length, block_length, num_parallel_calls=tf.data.AUTOTUNE) instead. If sloppy execution is desired, use tf.data.Options.experimental_deterministic. parallel_interleave() maps map_func across its input to produce nested datasets, and outputs their elements interleaved. Unlike tf.data.Dataset.interleave, it gets elements from cycle_length nested datasets in parallel, which increases the throughput, especially in the presence of stragglers. Furthermore, the sloppy argument can be used to improve performance, by relaxing the requirement that the outputs are produced in a deterministic order, and allowing the implementation to skip over nested datasets whose elements are not readily available when requested. Example usage: # Preprocess 4 files concurrently. filenames = tf.data.Dataset.list_files("/path/to/data/train*.tfrecords") dataset = filenames.apply( tf.data.experimental.parallel_interleave( lambda filename: tf.data.TFRecordDataset(filename), cycle_length=4)) Warning: If sloppy is True, the order of produced elements is not deterministic. Args map_func A function mapping a nested structure of tensors to a Dataset. cycle_length The number of input Datasets to interleave from in parallel. block_length The number of consecutive elements to pull from an input Dataset before advancing to the next input Dataset. sloppy A boolean controlling whether determinism should be traded for performance by allowing elements to be produced out of order. If sloppy is None, the tf.data.Options.experimental_deterministic dataset option (True by default) is used to decide whether to enforce a deterministic order. buffer_output_elements The number of elements each iterator being interleaved should buffer (similar to the .prefetch() transformation for each interleaved iterator). prefetch_input_elements The number of input elements to transform to iterators before they are needed for interleaving. Returns A Dataset transformation function, which can be passed to tf.data.Dataset.apply.
doc_29343
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
doc_29344
A generic version of collections.abc.Set. Deprecated since version 3.9: collections.abc.Set now supports []. See PEP 585 and Generic Alias Type.
doc_29345
Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end]. See also char.count
doc_29346
Add paths to configuration include directories. Add the given sequence of paths to the beginning of the include_dirs list. This list will be visible to all extension modules of the current package.
doc_29347
Returns the matrix norm or vector norm of a given tensor. This function can calculate one of eight different types of matrix norms, or one of an infinite number of vector norms, depending on both the number of reduction dimensions and the value of the ord parameter. Parameters input (Tensor) – The input tensor. If dim is None, x must be 1-D or 2-D, unless ord is None. If both dim and ord are None, the 2-norm of the input flattened to 1-D will be returned. Its data type must be either a floating point or complex type. For complex inputs, the norm is calculated on of the absolute values of each element. If the input is complex and neither dtype nor out is specified, the result’s data type will be the corresponding floating point type (e.g. float if input is complexfloat). ord (int, float, inf, -inf, 'fro', 'nuc', optional) – The order of norm. inf refers to float('inf'), numpy’s inf object, or any equivalent object. The following norms can be calculated: ord norm for matrices norm for vectors None Frobenius norm 2-norm ’fro’ Frobenius norm – not supported – ‘nuc’ nuclear norm – not supported – inf max(sum(abs(x), dim=1)) max(abs(x)) -inf min(sum(abs(x), dim=1)) min(abs(x)) 0 – not supported – sum(x != 0) 1 max(sum(abs(x), dim=0)) as below -1 min(sum(abs(x), dim=0)) as below 2 2-norm (largest sing. value) as below -2 smallest singular value as below other – not supported – sum(abs(x)**ord)**(1./ord) Default: None dim (int, 2-tuple of python:ints, 2-list of python:ints, optional) – If dim is an int, vector norm will be calculated over the specified dimension. If dim is a 2-tuple of ints, matrix norm will be calculated over the specified dimensions. If dim is None, matrix norm will be calculated when the input tensor has two dimensions, and vector norm will be calculated when the input tensor has one dimension. Default: None keepdim (bool, optional) – If set to True, the reduced dimensions are retained in the result as dimensions with size one. Default: False Keyword Arguments out (Tensor, optional) – The output tensor. Ignored if None. Default: None dtype (torch.dtype, optional) – If specified, the input tensor is cast to dtype before performing the operation, and the returned tensor’s type will be dtype. If this argument is used in conjunction with the out argument, the output tensor’s type must match this argument or a RuntimeError will be raised. Default: None Examples: >>> import torch >>> from torch import linalg as LA >>> a = torch.arange(9, dtype=torch.float) - 4 >>> a tensor([-4., -3., -2., -1., 0., 1., 2., 3., 4.]) >>> b = a.reshape((3, 3)) >>> b tensor([[-4., -3., -2.], [-1., 0., 1.], [ 2., 3., 4.]]) >>> LA.norm(a) tensor(7.7460) >>> LA.norm(b) tensor(7.7460) >>> LA.norm(b, 'fro') tensor(7.7460) >>> LA.norm(a, float('inf')) tensor(4.) >>> LA.norm(b, float('inf')) tensor(9.) >>> LA.norm(a, -float('inf')) tensor(0.) >>> LA.norm(b, -float('inf')) tensor(2.) >>> LA.norm(a, 1) tensor(20.) >>> LA.norm(b, 1) tensor(7.) >>> LA.norm(a, -1) tensor(0.) >>> LA.norm(b, -1) tensor(6.) >>> LA.norm(a, 2) tensor(7.7460) >>> LA.norm(b, 2) tensor(7.3485) >>> LA.norm(a, -2) tensor(0.) >>> LA.norm(b.double(), -2) tensor(1.8570e-16, dtype=torch.float64) >>> LA.norm(a, 3) tensor(5.8480) >>> LA.norm(a, -3) tensor(0.) Using the dim argument to compute vector norms: >>> c = torch.tensor([[1., 2., 3.], ... [-1, 1, 4]]) >>> LA.norm(c, dim=0) tensor([1.4142, 2.2361, 5.0000]) >>> LA.norm(c, dim=1) tensor([3.7417, 4.2426]) >>> LA.norm(c, ord=1, dim=1) tensor([6., 6.]) Using the dim argument to compute matrix norms: >>> m = torch.arange(8, dtype=torch.float).reshape(2, 2, 2) >>> LA.norm(m, dim=(1,2)) tensor([ 3.7417, 11.2250]) >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :]) (tensor(3.7417), tensor(11.2250))
doc_29348
Parses an XML section from a string constant. Same as XML(). text is a string containing XML data. parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns an Element instance.
doc_29349
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used. Changed in version 3.3: changed from a factory function to a class. cancel() Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.
doc_29350
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters t (torch.Tensor) – tensor to prune (of same dimensions as default_mask). importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place. default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns pruned version of tensor t.
doc_29351
Build or fetch the effective stop words list. Returns stop_words: list or None A list of stop words.
doc_29352
The FileSelectBox is similar to the standard Motif(TM) file-selection box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly selected again.
doc_29353
Series basis polynomial of degree deg. Returns the series representing the basis polynomial of degree deg. New in version 1.7.0. Parameters degint Degree of the basis polynomial for the series. Must be >= 0. domain{None, array_like}, optional If given, the array must be of the form [beg, end], where beg and end are the endpoints of the domain. If None is given then the class domain is used. The default is None. window{None, array_like}, optional If given, the resulting array must be if the form [beg, end], where beg and end are the endpoints of the window. If None is given then the class window is used. The default is None. Returns new_seriesseries A series with the coefficient of the deg term set to one and all others zero.
doc_29354
Return offset of the container.
doc_29355
Add a centered suptitle to the figure. Parameters tstr The suptitle text. xfloat, default: 0.5 The x location of the text in figure coordinates. yfloat, default: 0.98 The y location of the text in figure coordinates. horizontalalignment, ha{'center', 'left', 'right'}, default: center The horizontal alignment of the text relative to (x, y). verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: top The vertical alignment of the text relative to (x, y). fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large') The font size of the text. See Text.set_size for possible values. fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal') The font weight of the text. See Text.set_weight for possible values. Returns text The Text instance of the suptitle. Other Parameters fontpropertiesNone or dict, optional A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs Additional kwargs are matplotlib.text.Text properties.
doc_29356
See torch.chunk()
doc_29357
An unstructured triangular grid consisting of npoints points and ntri triangles. The triangles can either be specified by the user or automatically generated using a Delaunay triangulation. Parameters x, y(npoints,) array-like Coordinates of grid points. triangles(ntri, 3) array-like of int, optional For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. If not specified, the Delaunay triangulation is calculated. mask(ntri,) array-like of bool, optional Which triangles are masked out. Notes For a Triangulation to be valid it must not have duplicate points, triangles formed from colinear points, or overlapping triangles. Attributes triangles(ntri, 3) array of int For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. If you want to take the mask into account, use get_masked_triangles instead. mask(ntri, 3) array of bool Masked out triangles. is_delaunaybool Whether the Triangulation is a calculated Delaunay triangulation (where triangles was not specified) or not. calculate_plane_coefficients(z)[source] Calculate plane equation coefficients for all unmasked triangles from the point (x, y) coordinates and specified z-array of shape (npoints). The returned array has shape (npoints, 3) and allows z-value at (x, y) position in triangle tri to be calculated using z = array[tri, 0] * x  + array[tri, 1] * y + array[tri, 2]. propertyedges Return integer array of shape (nedges, 2) containing all edges of non-masked triangles. Each row defines an edge by it's start point index and end point index. Each edge appears only once, i.e. for an edge between points i and j, there will only be either (i, j) or (j, i). get_cpp_triangulation()[source] Return the underlying C++ Triangulation object, creating it if necessary. staticget_from_args_and_kwargs(*args, **kwargs)[source] Return a Triangulation object from the args and kwargs, and the remaining args and kwargs with the consumed values removed. There are two alternatives: either the first argument is a Triangulation object, in which case it is returned, or the args and kwargs are sufficient to create a new Triangulation to return. In the latter case, see Triangulation.__init__ for the possible args and kwargs. get_masked_triangles()[source] Return an array of triangles that are not masked. get_trifinder()[source] Return the default matplotlib.tri.TriFinder of this triangulation, creating it if necessary. This allows the same TriFinder object to be easily shared. propertyneighbors Return integer array of shape (ntri, 3) containing neighbor triangles. For each triangle, the indices of the three triangles that share the same edges, or -1 if there is no such neighboring triangle. neighbors[i, j] is the triangle that is the neighbor to the edge from point index triangles[i, j] to point index triangles[i, (j+1)%3]. set_mask(mask)[source] Set or clear the mask array. Parameters maskNone or bool array of length ntri
doc_29358
See Migration guide for more details. tf.compat.v1.train.checkpoints_iterator tf.train.checkpoints_iterator( checkpoint_dir, min_interval_secs=0, timeout=None, timeout_fn=None ) The iterator only checks for new checkpoints when control flow has been reverted to it. This means it can miss checkpoints if your code takes longer to run between iterations than min_interval_secs or the interval at which new checkpoints are written. The timeout argument is the maximum number of seconds to block waiting for a new checkpoint. It is used in combination with the timeout_fn as follows: If the timeout expires and no timeout_fn was specified, the iterator stops yielding. If a timeout_fn was specified, that function is called and if it returns a true boolean value the iterator stops yielding. If the function returns a false boolean value then the iterator resumes the wait for new checkpoints. At this point the timeout logic applies again. This behavior gives control to callers on what to do if checkpoints do not come fast enough or stop being generated. For example, if callers have a way to detect that the training has stopped and know that no new checkpoints will be generated, they can provide a timeout_fn that returns True when the training has stopped. If they know that the training is still going on they return False instead. Args checkpoint_dir The directory in which checkpoints are saved. min_interval_secs The minimum number of seconds between yielding checkpoints. timeout The maximum number of seconds to wait between checkpoints. If left as None, then the process will wait indefinitely. timeout_fn Optional function to call after a timeout. If the function returns True, then it means that no new checkpoints will be generated and the iterator will exit. The function is called with no arguments. Yields String paths to latest checkpoint files as they arrive.
doc_29359
Nu Support Vector Regression. Similar to NuSVC, for regression, uses a parameter nu to control the number of support vectors. However, unlike NuSVC, where nu replaces C, here nu replaces the parameter epsilon of epsilon-SVR. The implementation is based on libsvm. Read more in the User Guide. Parameters nufloat, default=0.5 An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By default 0.5 will be taken. Cfloat, default=1.0 Penalty parameter C of the error term. kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’ Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to precompute the kernel matrix. degreeint, default=3 Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels. gamma{‘scale’, ‘auto’} or float, default=’scale’ Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma, if ‘auto’, uses 1 / n_features. Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’. coef0float, default=0.0 Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’. shrinkingbool, default=True Whether to use the shrinking heuristic. See the User Guide. tolfloat, default=1e-3 Tolerance for stopping criterion. cache_sizefloat, default=200 Specify the size of the kernel cache (in MB). verbosebool, default=False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iterint, default=-1 Hard limit on iterations within solver, or -1 for no limit. Attributes class_weight_ndarray of shape (n_classes,) Multipliers of parameter C for each class. Computed based on the class_weight parameter. coef_ndarray of shape (1, n_features) Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel. coef_ is readonly property derived from dual_coef_ and support_vectors_. dual_coef_ndarray of shape (1, n_SV) Coefficients of the support vector in the decision function. fit_status_int 0 if correctly fitted, 1 otherwise (will raise warning) intercept_ndarray of shape (1,) Constants in decision function. n_support_ndarray of shape (n_classes,), dtype=int32 Number of support vectors for each class. shape_fit_tuple of int of shape (n_dimensions_of_X,) Array dimensions of training vector X. support_ndarray of shape (n_SV,) Indices of support vectors. support_vectors_ndarray of shape (n_SV, n_features) Support vectors. See also NuSVC Support Vector Machine for classification implemented with libsvm with a parameter to control the number of support vectors. SVR Epsilon Support Vector Machine for regression implemented with libsvm. References 1 LIBSVM: A Library for Support Vector Machines 2 Platt, John (1999). “Probabilistic outputs for support vector machines and comparison to regularizedlikelihood methods.” Examples >>> from sklearn.svm import NuSVR >>> from sklearn.pipeline import make_pipeline >>> from sklearn.preprocessing import StandardScaler >>> import numpy as np >>> n_samples, n_features = 10, 5 >>> np.random.seed(0) >>> y = np.random.randn(n_samples) >>> X = np.random.randn(n_samples, n_features) >>> regr = make_pipeline(StandardScaler(), NuSVR(C=1.0, nu=0.1)) >>> regr.fit(X, y) Pipeline(steps=[('standardscaler', StandardScaler()), ('nusvr', NuSVR(nu=0.1))]) Methods fit(X, y[, sample_weight]) Fit the SVM model according to the given training data. get_params([deep]) Get parameters for this estimator. predict(X) Perform regression on samples in X. score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction. set_params(**params) Set the parameters of this estimator. fit(X, y, sample_weight=None) [source] Fit the SVM model according to the given training data. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) Training vectors, where n_samples is the number of samples and n_features is the number of features. For kernel=”precomputed”, the expected shape of X is (n_samples, n_samples). yarray-like of shape (n_samples,) Target values (class labels in classification, real numbers in regression). sample_weightarray-like of shape (n_samples,), default=None Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns selfobject Notes If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied. If X is a dense array, then the other methods will not support sparse matrices as input. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. predict(X) [source] Perform regression on samples in X. For an one-class model, +1 (inlier) or -1 (outlier) is returned. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns y_predndarray of shape (n_samples,) score(X, y, sample_weight=None) [source] Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred) ** 2).sum() and \(v\) is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters Xarray-like of shape (n_samples, n_features) Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True values for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat \(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor). set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_29360
Geometry information that gets passed to callback functions.
doc_29361
One-vs-the-rest (OvR) multiclass strategy. Also known as one-vs-all, this strategy consists in fitting one classifier per class. For each classifier, the class is fitted against all the other classes. In addition to its computational efficiency (only n_classes classifiers are needed), one advantage of this approach is its interpretability. Since each class is represented by one and one classifier only, it is possible to gain knowledge about the class by inspecting its corresponding classifier. This is the most commonly used strategy for multiclass classification and is a fair default choice. OneVsRestClassifier can also be used for multilabel classification. To use this feature, provide an indicator matrix for the target y when calling .fit. In other words, the target labels should be formatted as a 2D binary (0/1) matrix, where [i, j] == 1 indicates the presence of label j in sample i. This estimator uses the binary relevance method to perform multilabel classification, which involves training one binary classifier independently for each label. Read more in the User Guide. Parameters estimatorestimator object An estimator object implementing fit and one of decision_function or predict_proba. n_jobsint, default=None The number of jobs to use for the computation: the n_classes one-vs-rest problems are computed in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Changed in version v0.20: n_jobs default changed from 1 to None Attributes estimators_list of n_classes estimators Estimators used for predictions. coef_ndarray of shape (1, n_features) or (n_classes, n_features) Coefficient of the features in the decision function. This attribute exists only if the estimators_ defines coef_. Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). If you use this attribute in RFE or SelectFromModel, you may pass a callable to the importance_getter parameter that extracts feature the importances from estimators_. intercept_ndarray of shape (1, 1) or (n_classes, 1) If y is binary, the shape is (1, 1) else (n_classes, 1) This attribute exists only if the estimators_ defines intercept_. Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). If you use this attribute in RFE or SelectFromModel, you may pass a callable to the importance_getter parameter that extracts feature the importances from estimators_. classes_array, shape = [n_classes] Class labels. n_classes_int Number of classes. label_binarizer_LabelBinarizer object Object used to transform multiclass labels to binary labels and vice-versa. multilabel_boolean Whether this is a multilabel classifier See also sklearn.multioutput.MultiOutputClassifier Alternate way of extending an estimator for multilabel classification. sklearn.preprocessing.MultiLabelBinarizer Transform iterable of iterables to binary indicator matrix. Examples >>> import numpy as np >>> from sklearn.multiclass import OneVsRestClassifier >>> from sklearn.svm import SVC >>> X = np.array([ ... [10, 10], ... [8, 10], ... [-5, 5.5], ... [-5.4, 5.5], ... [-20, -20], ... [-15, -20] ... ]) >>> y = np.array([0, 0, 1, 1, 2, 2]) >>> clf = OneVsRestClassifier(SVC()).fit(X, y) >>> clf.predict([[-19, -20], [9, 9], [-5, 5]]) array([2, 0, 1]) Methods decision_function(X) Returns the distance of each sample from the decision boundary for each class. fit(X, y) Fit underlying estimators. get_params([deep]) Get parameters for this estimator. partial_fit(X, y[, classes]) Partially fit underlying estimators predict(X) Predict multi-class targets using underlying estimators. predict_proba(X) Probability estimates. 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. decision_function(X) [source] Returns the distance of each sample from the decision boundary for each class. This can only be used with estimators which implement the decision_function method. Parameters Xarray-like of shape (n_samples, n_features) Returns Tarray-like of shape (n_samples, n_classes) or (n_samples,) for binary classification. Changed in version 0.19: output shape changed to (n_samples,) to conform to scikit-learn conventions for binary classification. fit(X, y) [source] Fit underlying estimators. Parameters X(sparse) array-like of shape (n_samples, n_features) Data. y(sparse) array-like of shape (n_samples,) or (n_samples, n_classes) Multi-class targets. An indicator matrix turns on multilabel classification. Returns 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. property multilabel_ Whether this is a multilabel classifier partial_fit(X, y, classes=None) [source] Partially fit underlying estimators Should be used when memory is inefficient to train all data. Chunks of data can be passed in several iteration. Parameters X(sparse) array-like of shape (n_samples, n_features) Data. y(sparse) array-like of shape (n_samples,) or (n_samples, n_classes) Multi-class targets. An indicator matrix turns on multilabel classification. classesarray, shape (n_classes, ) Classes across all calls to partial_fit. Can be obtained via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is only required in the first call of partial_fit and can be omitted in the subsequent calls. Returns self predict(X) [source] Predict multi-class targets using underlying estimators. Parameters X(sparse) array-like of shape (n_samples, n_features) Data. Returns y(sparse) array-like of shape (n_samples,) or (n_samples, n_classes) Predicted multi-class targets. predict_proba(X) [source] Probability estimates. The returned estimates for all classes are ordered by label of classes. Note that in the multilabel case, each sample can have any number of labels. This returns the marginal probability that the given sample has the label in question. For example, it is entirely consistent that two labels both have a 90% probability of applying to a given sample. In the single label multiclass case, the rows of the returned matrix sum to 1. Parameters Xarray-like of shape (n_samples, n_features) Returns T(sparse) array-like of shape (n_samples, n_classes) Returns the probability of the sample for each class in the model, where classes are ordered as they are in self.classes_. score(X, y, sample_weight=None) [source] Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_29362
Like sigwaitinfo(), but takes an additional timeout argument specifying a timeout. If timeout is specified as 0, a poll is performed. Returns None if a timeout occurs. Availability: Unix. See the man page sigtimedwait(2) for further information. See also pause(), sigwait() and sigwaitinfo(). New in version 3.3. Changed in version 3.5: The function is now retried with the recomputed timeout if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 for the rationale).
doc_29363
Return a os.stat_result object containing information about this path, like os.stat(). The result is looked up at each call to this method. >>> p = Path('setup.py') >>> p.stat().st_size 956 >>> p.stat().st_mtime 1327883547.852554
doc_29364
Applies the soft shrinkage function elementwise: SoftShrinkage(x)={x−λ, if x>λx+λ, if x<−λ0, otherwise \text{SoftShrinkage}(x) = \begin{cases} x - \lambda, & \text{ if } x > \lambda \\ x + \lambda, & \text{ if } x < -\lambda \\ 0, & \text{ otherwise } \end{cases} Parameters lambd – the λ\lambda (must be no less than zero) value for the Softshrink formulation. Default: 0.5 Shape: Input: (N,∗)(N, *) where * means, any number of additional dimensions Output: (N,∗)(N, *) , same shape as the input Examples: >>> m = nn.Softshrink() >>> input = torch.randn(2) >>> output = m(input)
doc_29365
See Migration guide for more details. tf.compat.v1.raw_ops.DestroyTemporaryVariable tf.raw_ops.DestroyTemporaryVariable( ref, var_name, name=None ) Sets output to the value of the Tensor pointed to by 'ref', then destroys the temporary variable called 'var_name'. All other uses of 'ref' must have executed before this op. This is typically achieved by chaining the ref through each assign op, or by using control dependencies. Outputs the final value of the tensor pointed to by 'ref'. Args ref A mutable Tensor. A reference to the temporary variable tensor. var_name A string. Name of the temporary variable, usually the name of the matching 'TemporaryVariable' op. name A name for the operation (optional). Returns A Tensor. Has the same type as ref.
doc_29366
tf.compat.v1.layers.AveragePooling3D( pool_size, strides, padding='valid', data_format='channels_last', name=None, **kwargs ) Arguments pool_size An integer or tuple/list of 3 integers: (pool_depth, pool_height, pool_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. padding A string. The padding method, either 'valid' or 'same'. Case-insensitive. data_format A string. The ordering of the dimensions in the inputs. channels_last (default) and channels_first are supported. channels_last corresponds to inputs with shape (batch, depth, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, depth, height, width). name A string, the name of the layer. Attributes graph scope_name
doc_29367
turtle.addshape(name, shape=None) There are three different ways to call this function: name is the name of a gif-file and shape is None: Install the corresponding image shape. >>> screen.register_shape("turtle.gif") Note Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle! name is an arbitrary string and shape is a tuple of pairs of coordinates: Install the corresponding polygon shape. >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3))) name is an arbitrary string and shape is a (compound) Shape object: Install the corresponding compound shape. Add a turtle shape to TurtleScreen’s shapelist. Only thusly registered shapes can be used by issuing the command shape(shapename).
doc_29368
If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.
doc_29369
sklearn.config_context(**new_config) [source] Context manager for global scikit-learn configuration Parameters assume_finitebool, default=False If True, validation for finiteness will be skipped, saving time, but leading to potential crashes. If False, validation for finiteness will be performed, avoiding error. Global default: False. working_memoryint, default=1024 If set, scikit-learn will attempt to limit the size of temporary arrays to this number of MiB (per job when parallelised), often saving both computation time and memory on expensive operations that can be performed in chunks. Global default: 1024. print_changed_onlybool, default=True If True, only the parameters that were set to non-default values will be printed when printing an estimator. For example, print(SVC()) while True will only print ‘SVC()’, but would print ‘SVC(C=1.0, cache_size=200, …)’ with all the non-changed parameters when False. Default is True. Changed in version 0.23: Default changed from False to True. display{‘text’, ‘diagram’}, default=’text’ If ‘diagram’, estimators will be displayed as a diagram in a Jupyter lab or notebook context. If ‘text’, estimators will be displayed as text. Default is ‘text’. New in version 0.23. See also set_config Set global scikit-learn configuration. get_config Retrieve current values of the global configuration. Notes All settings, not just those presently modified, will be returned to their previous values when the context manager is exited. This is not thread-safe. Examples >>> import sklearn >>> from sklearn.utils.validation import assert_all_finite >>> with sklearn.config_context(assume_finite=True): ... assert_all_finite([float('nan')]) >>> with sklearn.config_context(assume_finite=True): ... with sklearn.config_context(assume_finite=False): ... assert_all_finite([float('nan')]) Traceback (most recent call last): ... ValueError: Input contains NaN, ...
doc_29370
Represents the C wchar_t datatype, and interprets the value as a single character unicode string. The constructor accepts an optional string initializer, the length of the string must be exactly one character.
doc_29371
Base class for text streams. This class provides a character and line based interface to stream I/O. It inherits IOBase. There is no public constructor. TextIOBase provides or overrides these data attributes and methods in addition to those from IOBase: encoding The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes. errors The error setting of the decoder or encoder. newlines A string, a tuple of strings, or None, indicating the newlines translated so far. Depending on the implementation and the initial constructor flags, this may not be available. buffer The underlying binary buffer (a BufferedIOBase instance) that TextIOBase deals with. This is not part of the TextIOBase API and may not exist in some implementations. detach() Separate the underlying binary buffer from the TextIOBase and return it. After the underlying buffer has been detached, the TextIOBase is in an unusable state. Some TextIOBase implementations, like StringIO, may not have the concept of an underlying buffer and calling this method will raise UnsupportedOperation. New in version 3.1. read(size=-1) Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF. readline(size=-1) Read until newline or EOF and return a single str. If the stream is already at EOF, an empty string is returned. If size is specified, at most size characters will be read. seek(offset, whence=SEEK_SET) Change the stream position to the given offset. Behaviour depends on the whence parameter. The default value for whence is SEEK_SET. SEEK_SET or 0: seek from the start of the stream (the default); offset must either be a number returned by TextIOBase.tell(), or zero. Any other offset value produces undefined behaviour. SEEK_CUR or 1: “seek” to the current position; offset must be zero, which is a no-operation (all other values are unsupported). SEEK_END or 2: seek to the end of the stream; offset must be zero (all other values are unsupported). Return the new absolute position as an opaque number. New in version 3.1: The SEEK_* constants. tell() Return the current stream position as an opaque number. The number does not usually represent a number of bytes in the underlying binary storage. write(s) Write the string s to the stream and return the number of characters written.
doc_29372
Parse a query in the environment or from a file (the file defaults to sys.stdin). The keep_blank_values, strict_parsing and separator parameters are passed to urllib.parse.parse_qs() unchanged.
doc_29373
Returns a new tensor with the inverse hyperbolic sine of the elements of input. outi=sinh⁡−1(inputi)\text{out}_{i} = \sinh^{-1}(\text{input}_{i}) Parameters input (Tensor) – the input tensor. Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4) >>> a tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ]) >>> torch.asinh(a) tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ])
doc_29374
Return the mask of a masked array, or full boolean array of False. Return the mask of arr as an ndarray if arr is a MaskedArray and the mask is not nomask, else return a full boolean array of False of the same shape as arr. Parameters arrarray_like Input MaskedArray for which the mask is required. See also getmask Return the mask of a masked array, or nomask. getdata Return the data of a masked array as an ndarray. Examples >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array( data=[[1, --], [3, 4]], mask=[[False, True], [False, False]], fill_value=2) >>> ma.getmaskarray(a) array([[False, True], [False, False]]) Result when mask == nomask >>> b = ma.masked_array([[1,2],[3,4]]) >>> b masked_array( data=[[1, 2], [3, 4]], mask=False, fill_value=999999) >>> ma.getmaskarray(b) array([[False, False], [False, False]])
doc_29375
tf.keras.layers.DenseFeatures( feature_columns, trainable=True, name=None, **kwargs ) Generally a single example in training data is described with FeatureColumns. At the first layer of the model, this column oriented data should be converted to a single Tensor. This layer can be called multiple times with different features. This is the V2 version of this layer that uses name_scopes to create variables instead of variable_scopes. But this approach currently lacks support for partitioned variables. In that case, use the V1 version instead. Example: price = tf.feature_column.numeric_column('price') keywords_embedded = tf.feature_column.embedding_column( tf.feature_column.categorical_column_with_hash_bucket("keywords", 10K), dimensions=16) columns = [price, keywords_embedded, ...] feature_layer = tf.keras.layers.DenseFeatures(columns) features = tf.io.parse_example( ..., features=tf.feature_column.make_parse_example_spec(columns)) dense_tensor = feature_layer(features) for units in [128, 64, 32]: dense_tensor = tf.keras.layers.Dense(units, activation='relu')(dense_tensor) prediction = tf.keras.layers.Dense(1)(dense_tensor) Args feature_columns An iterable containing the FeatureColumns to use as inputs to your model. All items should be instances of classes derived from DenseColumn such as numeric_column, embedding_column, bucketized_column, indicator_column. If you have categorical features, you can wrap them with an embedding_column or indicator_column. trainable Boolean, whether the layer's variables will be updated via gradient descent during training. name Name to give to the DenseFeatures. **kwargs Keyword arguments to construct a layer. Raises ValueError if an item in feature_columns is not a DenseColumn.
doc_29376
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_29377
Return the roots of the series polynomial. Compute the roots for the series. Note that the accuracy of the roots decrease the further outside the domain they lie. Returns rootsndarray Array containing the roots of the series.
doc_29378
If the whole string matches the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match. New in version 3.4.
doc_29379
Convert a file’s mode to a string of the form ‘-rwxrwxrwx’. New in version 3.3. Changed in version 3.4: The function supports S_IFDOOR, S_IFPORT and S_IFWHT.
doc_29380
Return the xdata. If orig is True, return the original data, else the processed data.
doc_29381
Function that takes the mean element-wise absolute value difference. See L1Loss for details.
doc_29382
Get list of available fullscreen modes list_modes(depth=0, flags=pygame.FULLSCREEN, display=0) -> list This function returns a list of possible sizes for a specified color depth. The return value will be an empty list if no display modes are available with the given arguments. A return value of -1 means that any requested size should work (this is likely the case for windowed modes). Mode sizes are sorted from biggest to smallest. If depth is 0, the current/best color depth for the display is used. The flags defaults to pygame.FULLSCREEN, but you may need to add additional flags for specific fullscreen modes. The display index 0 means the default display is used. Changed in pygame 1.9.5: display argument added
doc_29383
Create a Stats object based on the current profile and print the results to stdout.
doc_29384
Transcode CGI variables from os.environ to PEP 3333 “bytes in unicode” strings, returning a new dictionary. This function is used by CGIHandler and IISCGIHandler in place of directly using os.environ, which is not necessarily WSGI-compliant on all platforms and web servers using Python 3 – specifically, ones where the OS’s actual environment is Unicode (i.e. Windows), or ones where the environment is bytes, but the system encoding used by Python to decode it is anything other than ISO-8859-1 (e.g. Unix systems using UTF-8). If you are implementing a CGI-based handler of your own, you probably want to use this routine instead of just copying values out of os.environ directly. New in version 3.2.
doc_29385
Constructs a tensor by repeating the elements of input. The reps argument specifies the number of repetitions in each dimension. If reps specifies fewer dimensions than input has, then ones are prepended to reps until all dimensions are specified. For example, if input has shape (8, 6, 4, 2) and reps is (2, 2), then reps is treated as (1, 1, 2, 2). Analogously, if input has fewer dimensions than reps specifies, then input is treated as if it were unsqueezed at dimension zero until it has as many dimensions as reps specifies. For example, if input has shape (4, 2) and reps is (3, 3, 2, 2), then input is treated as if it had the shape (1, 1, 4, 2). Note This function is similar to NumPy’s tile function. Parameters input (Tensor) – the tensor whose elements to repeat. reps (tuple) – the number of repetitions per dimension. Example: >>> x = torch.tensor([1, 2, 3]) >>> x.tile((2,)) tensor([1, 2, 3, 1, 2, 3]) >>> y = torch.tensor([[1, 2], [3, 4]]) >>> torch.tile(y, (2, 2)) tensor([[1, 2, 1, 2], [3, 4, 3, 4], [1, 2, 1, 2], [3, 4, 3, 4]])
doc_29386
See Migration guide for more details. tf.compat.v1.raw_ops.ListDiff tf.raw_ops.ListDiff( x, y, out_idx=tf.dtypes.int32, name=None ) Given a list x and a list y, this operation returns a list out that represents all values that are in x but not in y. The returned list out is sorted in the same order that the numbers appear in x (duplicates are preserved). This operation also returns a list idx that represents the position of each out element in x. In other words: out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1] For example, given this input: x = [1, 2, 3, 4, 5, 6] y = [1, 3, 5] This operation would return: out ==> [2, 4, 6] idx ==> [1, 3, 5] Args x A Tensor. 1-D. Values to keep. y A Tensor. Must have the same type as x. 1-D. Values to remove. out_idx An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int32. name A name for the operation (optional). Returns A tuple of Tensor objects (out, idx). out A Tensor. Has the same type as x. idx A Tensor of type out_idx.
doc_29387
Aggregate using one or more operations over the specified axis. Parameters func:function, str, list or dict Function to use for aggregating the data. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply. Accepted combinations are: function string function name list of functions and/or function names, e.g. [np.sum, 'mean'] dict of axis labels -> functions, function names or list of such. axis:{0 or ‘index’, 1 or ‘columns’}, default 0 If 0 or ‘index’: apply function to each column. If 1 or ‘columns’: apply function to each row. *args Positional arguments to pass to func. **kwargs Keyword arguments to pass to func. Returns scalar, Series or DataFrame The return can be: scalar : when Series.agg is called with single function Series : when DataFrame.agg is called with a single function DataFrame : when DataFrame.agg is called with several functions Return scalar, Series or DataFrame. The aggregation operations are always performed over an axis, either the index (default) or the column axis. This behavior is different from numpy aggregation functions (mean, median, prod, sum, std, var), where the default is to compute the aggregation of the flattened array, e.g., numpy.mean(arr_2d) as opposed to numpy.mean(arr_2d, axis=0). agg is an alias for aggregate. Use the alias. See also DataFrame.apply Perform any type of operations. DataFrame.transform Perform transformation type operations. core.groupby.GroupBy Perform operations over groups. core.resample.Resampler Perform operations over resampled bins. core.window.Rolling Perform operations over rolling window. core.window.Expanding Perform operations over expanding window. core.window.ExponentialMovingWindow Perform operation over exponential weighted window. Notes agg is an alias for aggregate. Use the alias. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See Mutating with User Defined Function (UDF) methods for more details. A passed user-defined-function will be passed a Series for evaluation. Examples >>> df = pd.DataFrame([[1, 2, 3], ... [4, 5, 6], ... [7, 8, 9], ... [np.nan, np.nan, np.nan]], ... columns=['A', 'B', 'C']) Aggregate these functions over the rows. >>> df.agg(['sum', 'min']) A B C sum 12.0 15.0 18.0 min 1.0 2.0 3.0 Different aggregations per column. >>> df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']}) A B sum 12.0 NaN min 1.0 2.0 max NaN 8.0 Aggregate different functions over the columns and rename the index of the resulting DataFrame. >>> df.agg(x=('A', max), y=('B', 'min'), z=('C', np.mean)) A B C x 7.0 NaN NaN y NaN 2.0 NaN z NaN NaN 6.0 Aggregate over the columns. >>> df.agg("mean", axis="columns") 0 2.0 1 5.0 2 8.0 3 NaN dtype: float64
doc_29388
All changes to MH mailboxes are immediately applied, so this method does nothing.
doc_29389
See Migration guide for more details. tf.compat.v1.raw_ops.SparseAdd tf.raw_ops.SparseAdd( a_indices, a_values, a_shape, b_indices, b_values, b_shape, thresh, name=None ) The input SparseTensor objects' indices are assumed ordered in standard lexicographic order. If this is not the case, before this step run SparseReorder to restore index ordering. By default, if two values sum to zero at some index, the output SparseTensor would still include that particular location in its index, storing a zero in the corresponding value slot. To override this, callers can specify thresh, indicating that if the sum has a magnitude strictly smaller than thresh, its corresponding value and index would then not be included. In particular, thresh == 0 (default) means everything is kept and actual thresholding happens only for a positive value. In the following shapes, nnz is the count after taking thresh into account. Args a_indices A Tensor of type int64. 2-D. The indices of the first SparseTensor, size [nnz, ndims] Matrix. a_values A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. 1-D. The values of the first SparseTensor, size [nnz] Vector. a_shape A Tensor of type int64. 1-D. The shape of the first SparseTensor, size [ndims] Vector. b_indices A Tensor of type int64. 2-D. The indices of the second SparseTensor, size [nnz, ndims] Matrix. b_values A Tensor. Must have the same type as a_values. 1-D. The values of the second SparseTensor, size [nnz] Vector. b_shape A Tensor of type int64. 1-D. The shape of the second SparseTensor, size [ndims] Vector. thresh A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. 0-D. The magnitude threshold that determines if an output value/index pair takes space. name A name for the operation (optional). Returns A tuple of Tensor objects (sum_indices, sum_values, sum_shape). sum_indices A Tensor of type int64. sum_values A Tensor. Has the same type as a_values. sum_shape A Tensor of type int64.
doc_29390
See Migration guide for more details. tf.compat.v1.raw_ops.AccumulatorNumAccumulated tf.raw_ops.AccumulatorNumAccumulated( handle, name=None ) Args handle A Tensor of type mutable string. The handle to an accumulator. name A name for the operation (optional). Returns A Tensor of type int32.
doc_29391
Set multiple properties at once. Supported properties are Property Description adjustable {'box', 'datalim'} 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 anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} animated bool aspect {'auto', 'equal'} or float autoscale_on bool autoscalex_on bool autoscaley_on bool axes_locator Callable[[Axes, Renderer], Bbox] axisbelow bool or 'line' box_aspect float or None clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None facecolor or fc color figure Figure frame_on bool gid str in_layout bool label object navigate bool navigate_mode unknown path_effects AbstractPathEffect picker None or bool or float or callable position [left, bottom, width, height] or Bbox prop_cycle unknown rasterization_zorder float or None rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None title str transform Transform url str visible bool xbound unknown xlabel str xlim (bottom: float, top: float) xmargin float greater than -0.5 xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase xticklabels unknown xticks unknown ybound unknown ylabel str ylim (bottom: float, top: float) ymargin float greater than -0.5 yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase yticklabels unknown yticks unknown zorder float
doc_29392
YIQ to RGB color space conversion. Parameters yiq(…, 3) array_like The image in YIQ format. Final dimension denotes channels. Returns out(…, 3) ndarray The image in RGB format. Same dimensions as input. Raises ValueError If yiq is not at least 2-D with shape (…, 3).
doc_29393
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.
doc_29394
Day of the week the period lies in, with Monday=0 and Sunday=6. If the period frequency is lower than daily (e.g. hourly), and the period spans over multiple days, the day at the start of the period is used. If the frequency is higher than daily (e.g. monthly), the last day of the period is used. Returns int Day of the week. See also Period.day_of_week Day of the week the period lies in. Period.weekday Alias of Period.day_of_week. Period.day Day of the month. Period.dayofyear Day of the year. Examples >>> per = pd.Period('2017-12-31 22:00', 'H') >>> per.day_of_week 6 For periods that span over multiple days, the day at the beginning of the period is returned. >>> per = pd.Period('2017-12-31 22:00', '4H') >>> per.day_of_week 6 >>> per.start_time.day_of_week 6 For periods with a frequency higher than days, the last day of the period is returned. >>> per = pd.Period('2018-01', 'M') >>> per.day_of_week 2 >>> per.end_time.day_of_week 2
doc_29395
New in Django 3.2. A case insensitive, dict-like object that provides an interface to all HTTP headers on the response. See Setting header fields.
doc_29396
Set the face color of the Figure rectangle. Parameters colorcolor
doc_29397
class sklearn.neighbors.NearestNeighbors(*, n_neighbors=5, radius=1.0, algorithm='auto', leaf_size=30, metric='minkowski', p=2, metric_params=None, n_jobs=None) [source] Unsupervised learner for implementing neighbor searches. Read more in the User Guide. New in version 0.9. Parameters n_neighborsint, default=5 Number of neighbors to use by default for kneighbors queries. radiusfloat, default=1.0 Range of parameter space to use by default for radius_neighbors queries. 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. 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. metricstr or callable, default=’minkowski’ the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of DistanceMetric for a list of available metrics. 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. pint, default=2 Parameter for the Minkowski metric from sklearn.metrics.pairwise.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. 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. Attributes effective_metric_str Metric used to compute distances to neighbors. effective_metric_params_dict Parameters for the metric used to compute distances to neighbors. n_samples_fit_int Number of samples in the fitted data. See also KNeighborsClassifier RadiusNeighborsClassifier KNeighborsRegressor RadiusNeighborsRegressor BallTree Notes See Nearest Neighbors in the online documentation for a discussion of the choice of algorithm and leaf_size. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples >>> import numpy as np >>> from sklearn.neighbors import NearestNeighbors >>> samples = [[0, 0, 2], [1, 0, 0], [0, 0, 1]] >>> neigh = NearestNeighbors(n_neighbors=2, radius=0.4) >>> neigh.fit(samples) NearestNeighbors(...) >>> neigh.kneighbors([[0, 0, 1.3]], 2, return_distance=False) array([[2, 0]]...) >>> nbrs = neigh.radius_neighbors( ... [[0, 0, 1.3]], 0.4, return_distance=False ... ) >>> np.asarray(nbrs[0][0]) array(2) Methods fit(X[, y]) Fit the nearest neighbors estimator from the training dataset. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X radius_neighbors([X, radius, …]) Finds the neighbors within a given radius of a point or points. radius_neighbors_graph([X, radius, mode, …]) Computes the (weighted) graph of Neighbors for points in X set_params(**params) Set the parameters of this estimator. fit(X, y=None) [source] Fit the nearest neighbors estimator from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. yIgnored Not used, present for API consistency by convention. Returns selfNearestNeighbors The fitted nearest neighbors estimator. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) radius_neighbors(X=None, radius=None, return_distance=True, sort_results=False) [source] Finds the neighbors within a given radius of a point or points. Return the indices and distances of each point from the dataset lying in a ball with size radius around the points of the query array. Points lying on the boundary are included in the results. The result points are not necessarily sorted by distance to their query point. Parameters Xarray-like of (n_samples, n_features), default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. radiusfloat, default=None Limiting distance of neighbors to return. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. sort_resultsbool, default=False If True, the distances and indices will be sorted by increasing distances before being returned. If False, the results may not be sorted. If return_distance=False, setting sort_results=True will result in an error. New in version 0.22. Returns neigh_distndarray of shape (n_samples,) of arrays Array representing the distances to each point, only present if return_distance=True. The distance values are computed according to the metric constructor parameter. neigh_indndarray of shape (n_samples,) of arrays An array of arrays of indices of the approximate nearest points from the population matrix that lie within a ball of size radius around the query points. Notes Because the number of neighbors of each point is not necessarily equal, the results for multiple query points cannot be fit in a standard data array. For efficiency, radius_neighbors returns arrays of objects, where each object is a 1D array of indices or distances. Examples In the following example, we construct a NeighborsClassifier class from an array representing our data set and ask who’s the closest point to [1, 1, 1]: >>> import numpy as np >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(radius=1.6) >>> neigh.fit(samples) NearestNeighbors(radius=1.6) >>> rng = neigh.radius_neighbors([[1., 1., 1.]]) >>> print(np.asarray(rng[0][0])) [1.5 0.5] >>> print(np.asarray(rng[1][0])) [1 2] The first array returned contains the distances to all points which are closer than 1.6, while the second array returned contains their indices. In general, multiple points can be queried at the same time. radius_neighbors_graph(X=None, radius=None, mode='connectivity', sort_results=False) [source] Computes the (weighted) graph of Neighbors for points in X Neighborhoods are restricted the points at a distance lower than radius. Parameters Xarray-like of shape (n_samples, n_features), default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. radiusfloat, default=None Radius of neighborhoods. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. sort_resultsbool, default=False If True, in each row of the result, the non-zero entries will be sorted by increasing distances. If False, the non-zero entries may not be sorted. Only used with mode=’distance’. New in version 0.22. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix if of format CSR. See also kneighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(radius=1.5) >>> neigh.fit(X) NearestNeighbors(radius=1.5) >>> A = neigh.radius_neighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 0.], [1., 0., 1.]]) set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_29398
Create a new pure proxy server. Arguments are as per SMTPServer. Everything will be relayed to remoteaddr. Note that running this has a good chance to make you into an open relay, so please be careful.
doc_29399
Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which write events can occur. The default method simply returns True, indicating that by default, all channels will be interested in write events.