_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_4000 | Return True if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. | |
doc_4001 | Get information about the current windowing system get_wm_info() -> dict Creates a dictionary filled with string keys. The strings and values are arbitrarily created by the system. Some systems may have no information and an empty dictionary will be returned. Most platforms will return a "window" key with the value set to the system id for the current display. New in pygame 1.7.1. | |
doc_4002 |
Check whether the provided array or dtype is of a boolean dtype. Parameters
arr_or_dtype:array-like or dtype
The array or dtype to check. Returns
boolean
Whether or not the array or dtype is of a boolean dtype. Notes An ExtensionArray is considered boolean when the _is_boolean attribute is set to True. Examples
>>> is_bool_dtype(str)
False
>>> is_bool_dtype(int)
False
>>> is_bool_dtype(bool)
True
>>> is_bool_dtype(np.bool_)
True
>>> is_bool_dtype(np.array(['a', 'b']))
False
>>> is_bool_dtype(pd.Series([1, 2]))
False
>>> is_bool_dtype(np.array([True, False]))
True
>>> is_bool_dtype(pd.Categorical([True, False]))
True
>>> is_bool_dtype(pd.arrays.SparseArray([True, False]))
True | |
doc_4003 |
Update null elements with value in the same location in other. Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. The row and column indexes of the resulting DataFrame will be the union of the two. Parameters
other:DataFrame
Provided DataFrame to use to fill null values. Returns
DataFrame
The result of combining the provided DataFrame with the other object. See also DataFrame.combine
Perform series-wise operation on two DataFrames using a given function. Examples
>>> df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine_first(df2)
A B
0 1.0 3.0
1 0.0 4.0
Null values still persist if the location of that null value does not exist in other
>>> df1 = pd.DataFrame({'A': [None, 0], 'B': [4, None]})
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1]}, index=[1, 2])
>>> df1.combine_first(df2)
A B C
0 NaN 4.0 NaN
1 0.0 3.0 1.0
2 NaN 3.0 1.0 | |
doc_4004 | tf.compat.v1.tpu.experimental.AdagradParameters(
learning_rate: float,
initial_accumulator: float = 0.1,
use_gradient_accumulation: bool = True,
clip_weight_min: Optional[float] = None,
clip_weight_max: Optional[float] = None,
weight_decay_factor: Optional[float] = None,
multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None,
clip_gradient_min: Optional[float] = None,
clip_gradient_max: Optional[float] = None
)
Pass this to tf.estimator.tpu.experimental.EmbeddingConfigSpec via the optimization_parameters argument to set the optimizer and its parameters. See the documentation for tf.estimator.tpu.experimental.EmbeddingConfigSpec for more details. estimator = tf.estimator.tpu.TPUEstimator(
...
embedding_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec(
...
optimization_parameters=tf.tpu.experimental.AdagradParameters(0.1),
...))
Args
learning_rate used for updating embedding table.
initial_accumulator initial accumulator for Adagrad.
use_gradient_accumulation setting this to False makes embedding gradients calculation less accurate but faster. Please see optimization_parameters.proto for details. for details.
clip_weight_min the minimum value to clip by; None means -infinity.
clip_weight_max the maximum value to clip by; None means +infinity.
weight_decay_factor amount of weight decay to apply; None means that the weights are not decayed.
multiply_weight_decay_factor_by_learning_rate if true, weight_decay_factor is multiplied by the current learning rate.
clip_gradient_min the minimum value to clip by; None means -infinity.
clip_gradient_max the maximum value to clip by; None means +infinity. | |
doc_4005 | A constant that is likely larger than the underlying OS pipe buffer size, to make writes blocking. | |
doc_4006 | Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value. | |
doc_4007 |
Alias for set_linestyle. | |
doc_4008 | Default widget: SelectMultiple
Empty value: [] (an empty list) Normalizes to: A list of strings. Validates that every value in the given list of values exists in the list of choices. Error message keys: required, invalid_choice, invalid_list
The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice. Takes one extra required argument, choices, as for ChoiceField. | |
doc_4009 |
Returns a clone of self with given hyperparameters theta. Parameters
thetandarray of shape (n_dims,)
The hyperparameters | |
doc_4010 | test if event types are waiting on the queue peek(eventtype=None) -> bool peek(eventtype=None, pump=True) -> bool Returns True if there are any events of the given type waiting on the queue. If a sequence of event types is passed, this will return True if any of those events are on the queue. If pump is True (the default), then pygame.event.pump() will be called. Changed in pygame 1.9.5: Added pump argument | |
doc_4011 | operator.__add__(a, b)
Return a + b, for a and b numbers. | |
doc_4012 | See Migration guide for more details. tf.compat.v1.raw_ops.Conv2D
tf.raw_ops.Conv2D(
input, filter, strides, padding, use_cudnn_on_gpu=True, explicit_paddings=[],
data_format='NHWC', dilations=[1, 1, 1, 1], name=None
)
Given an input tensor of shape [batch, in_height, in_width, in_channels] and a filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels], this op performs the following: Flattens the filter to a 2-D matrix with shape [filter_height * filter_width * in_channels, output_channels]. Extracts image patches from the input tensor to form a virtual tensor of shape [batch, out_height, out_width, filter_height * filter_width * in_channels]. For each patch, right-multiplies the filter matrix and the image patch vector. In detail, with the default NHWC format, output[b, i, j, k] =
sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *
filter[di, dj, q, k]
Must have strides[0] = strides[3] = 1. For the most common case of the same horizontal and vertices strides, strides = [1, stride, stride, 1].
Args
input A Tensor. Must be one of the following types: half, bfloat16, float32, float64, int32. A 4-D tensor. The dimension order is interpreted according to the value of data_format, see below for details.
filter A Tensor. Must have the same type as input. A 4-D tensor of shape [filter_height, filter_width, in_channels, out_channels]
strides A list of ints. 1-D tensor of length 4. The stride of the sliding window for each dimension of input. The dimension order is determined by the value of data_format, see below for details.
padding A string from: "SAME", "VALID", "EXPLICIT". The type of padding algorithm to use.
use_cudnn_on_gpu An optional bool. Defaults to True.
explicit_paddings An optional list of ints. Defaults to []. If padding is "EXPLICIT", the list of explicit padding amounts. For the ith dimension, the amount of padding inserted before and after the dimension is explicit_paddings[2 * i] and explicit_paddings[2 * i + 1], respectively. If padding is not "EXPLICIT", explicit_paddings must be empty.
data_format An optional string from: "NHWC", "NCHW". Defaults to "NHWC". Specify the data format of the input and output data. With the default format "NHWC", the data is stored in the order of: [batch, height, width, channels]. Alternatively, the format could be "NCHW", the data storage order of: [batch, channels, height, width].
dilations An optional list of ints. Defaults to [1, 1, 1, 1]. 1-D tensor of length 4. The dilation factor for each dimension of input. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of data_format, see above for details. Dilations in the batch and depth dimensions must be 1.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_4013 |
Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used.
PEP 273 - Import Modules from Zip Archives
Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in PEP 273, but uses an implementation written by Just van Rossum that uses the import hooks described in PEP 302.
PEP 302 - New Import Hooks
The PEP to add the import hooks that help this module work. This module defines an exception:
exception zipimport.ZipImportError
Exception raised by zipimporter objects. It’s a subclass of ImportError, so it can be caught as ImportError, too.
zipimporter Objects zipimporter is the class for importing ZIP files.
class zipimport.zipimporter(archivepath)
Create a new zipimporter instance. archivepath must be a path to a ZIP file, or to a specific path within a ZIP file. For example, an archivepath of foo/bar.zip/lib will look for modules in the lib directory inside the ZIP file foo/bar.zip (provided that it exists). ZipImportError is raised if archivepath doesn’t point to a valid ZIP archive.
find_module(fullname[, path])
Search for a module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the zipimporter instance itself if the module was found, or None if it wasn’t. The optional path argument is ignored—it’s there for compatibility with the importer protocol.
get_code(fullname)
Return the code object for the specified module. Raise ZipImportError if the module couldn’t be found.
get_data(pathname)
Return the data associated with pathname. Raise OSError if the file wasn’t found. Changed in version 3.3: IOError used to be raised instead of OSError.
get_filename(fullname)
Return the value __file__ would be set to if the specified module was imported. Raise ZipImportError if the module couldn’t be found. New in version 3.1.
get_source(fullname)
Return the source code for the specified module. Raise ZipImportError if the module couldn’t be found, return None if the archive does contain the module, but has no source for it.
is_package(fullname)
Return True if the module specified by fullname is a package. Raise ZipImportError if the module couldn’t be found.
load_module(fullname)
Load the module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the imported module, or raises ZipImportError if it wasn’t found.
archive
The file name of the importer’s associated ZIP file, without a possible subpath.
prefix
The subpath within the ZIP file where modules are searched. This is the empty string for zipimporter objects which point to the root of the ZIP file.
The archive and prefix attributes, when combined with a slash, equal the original archivepath argument given to the zipimporter constructor.
Examples Here is an example that imports a module from a ZIP archive - note that the zipimport module is not explicitly used. $ unzip -l example.zip
Archive: example.zip
Length Date Time Name
-------- ---- ---- ----
8467 11-26-02 22:30 jwzthreading.py
-------- -------
8467 1 file
$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, 'example.zip') # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'example.zip/jwzthreading.py' | |
doc_4014 | Return a suite of all test cases contained in the given module. This method searches module for classes derived from TestCase and creates an instance of the class for each test method defined for the class. Note While using a hierarchy of TestCase-derived classes can be convenient in sharing fixtures and helper functions, defining test methods on base classes that are not intended to be instantiated directly does not play well with this method. Doing so, however, can be useful when the fixtures are different and defined in subclasses. If a module provides a load_tests function it will be called to load the tests. This allows modules to customize test loading. This is the load_tests protocol. The pattern argument is passed as the third argument to load_tests. Changed in version 3.2: Support for load_tests added. Changed in version 3.5: The undocumented and unofficial use_load_tests default argument is deprecated and ignored, although it is still accepted for backward compatibility. The method also now accepts a keyword-only argument pattern which is passed to load_tests as the third argument. | |
doc_4015 | The maximum age in seconds the access control settings can be cached for. | |
doc_4016 | Sets x, y and z from a spherical coordinates 3-tuple. from_spherical((r, theta, phi)) -> None Sets x, y and z from a tuple (r, theta, phi) where r is the radial distance, theta is the inclination angle and phi is the azimuthal angle. | |
doc_4017 | Convert a 32-bit packed IPv4 address (a bytes-like object four bytes in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument. If the byte sequence passed to this function is not exactly 4 bytes in length, OSError will be raised. inet_ntoa() does not support IPv6, and inet_ntop() should be used instead for IPv4/v6 dual stack support. Changed in version 3.5: Writable bytes-like object is now accepted. | |
doc_4018 | class sklearn.linear_model.LogisticRegression(penalty='l2', *, dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=None) [source]
Logistic Regression (aka logit, MaxEnt) classifier. In the multiclass case, the training algorithm uses the one-vs-rest (OvR) scheme if the ‘multi_class’ option is set to ‘ovr’, and uses the cross-entropy loss if the ‘multi_class’ option is set to ‘multinomial’. (Currently the ‘multinomial’ option is supported only by the ‘lbfgs’, ‘sag’, ‘saga’ and ‘newton-cg’ solvers.) This class implements regularized logistic regression using the ‘liblinear’ library, ‘newton-cg’, ‘sag’, ‘saga’ and ‘lbfgs’ solvers. Note that regularization is applied by default. It can handle both dense and sparse input. Use C-ordered arrays or CSR matrices containing 64-bit floats for optimal performance; any other input format will be converted (and copied). The ‘newton-cg’, ‘sag’, and ‘lbfgs’ solvers support only L2 regularization with primal formulation, or no regularization. The ‘liblinear’ solver supports both L1 and L2 regularization, with a dual formulation only for the L2 penalty. The Elastic-Net regularization is only supported by the ‘saga’ solver. Read more in the User Guide. Parameters
penalty{‘l1’, ‘l2’, ‘elasticnet’, ‘none’}, default=’l2’
Used to specify the norm used in the penalization. The ‘newton-cg’, ‘sag’ and ‘lbfgs’ solvers support only l2 penalties. ‘elasticnet’ is only supported by the ‘saga’ solver. If ‘none’ (not supported by the liblinear solver), no regularization is applied. New in version 0.19: l1 penalty with SAGA solver (allowing ‘multinomial’ + L1)
dualbool, default=False
Dual or primal formulation. Dual formulation is only implemented for l2 penalty with liblinear solver. Prefer dual=False when n_samples > n_features.
tolfloat, default=1e-4
Tolerance for stopping criteria.
Cfloat, default=1.0
Inverse of regularization strength; must be a positive float. Like in support vector machines, smaller values specify stronger regularization.
fit_interceptbool, default=True
Specifies if a constant (a.k.a. bias or intercept) should be added to the decision function.
intercept_scalingfloat, default=1
Useful only when the solver ‘liblinear’ is used and self.fit_intercept is set to True. In this case, x becomes [x, self.intercept_scaling], i.e. a “synthetic” feature with constant value equal to intercept_scaling is appended to the instance vector. The intercept becomes intercept_scaling * synthetic_feature_weight. Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased.
class_weightdict or ‘balanced’, default=None
Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)). Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. New in version 0.17: class_weight=’balanced’
random_stateint, RandomState instance, default=None
Used when solver == ‘sag’, ‘saga’ or ‘liblinear’ to shuffle the data. See Glossary for details.
solver{‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’}, default=’lbfgs’
Algorithm to use in the optimization problem. For small datasets, ‘liblinear’ is a good choice, whereas ‘sag’ and ‘saga’ are faster for large ones. For multiclass problems, only ‘newton-cg’, ‘sag’, ‘saga’ and ‘lbfgs’ handle multinomial loss; ‘liblinear’ is limited to one-versus-rest schemes. ‘newton-cg’, ‘lbfgs’, ‘sag’ and ‘saga’ handle L2 or no penalty ‘liblinear’ and ‘saga’ also handle L1 penalty ‘saga’ also supports ‘elasticnet’ penalty ‘liblinear’ does not support setting penalty='none'
Note that ‘sag’ and ‘saga’ fast convergence is only guaranteed on features with approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing. New in version 0.17: Stochastic Average Gradient descent solver. New in version 0.19: SAGA solver. Changed in version 0.22: The default solver changed from ‘liblinear’ to ‘lbfgs’ in 0.22.
max_iterint, default=100
Maximum number of iterations taken for the solvers to converge.
multi_class{‘auto’, ‘ovr’, ‘multinomial’}, default=’auto’
If the option chosen is ‘ovr’, then a binary problem is fit for each label. For ‘multinomial’ the loss minimised is the multinomial loss fit across the entire probability distribution, even when the data is binary. ‘multinomial’ is unavailable when solver=’liblinear’. ‘auto’ selects ‘ovr’ if the data is binary, or if solver=’liblinear’, and otherwise selects ‘multinomial’. New in version 0.18: Stochastic Average Gradient descent solver for ‘multinomial’ case. Changed in version 0.22: Default changed from ‘ovr’ to ‘auto’ in 0.22.
verboseint, default=0
For the liblinear and lbfgs solvers set verbose to any positive number for verbosity.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. Useless for liblinear solver. See the Glossary. New in version 0.17: warm_start to support lbfgs, newton-cg, sag, saga solvers.
n_jobsint, default=None
Number of CPU cores used when parallelizing over classes if multi_class=’ovr’”. This parameter is ignored when the solver is set to ‘liblinear’ regardless of whether ‘multi_class’ is specified or not. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
l1_ratiofloat, default=None
The Elastic-Net mixing parameter, with 0 <= l1_ratio <= 1. Only used if penalty='elasticnet'. Setting l1_ratio=0 is equivalent to using penalty='l2', while setting l1_ratio=1 is equivalent to using penalty='l1'. For 0 < l1_ratio <1, the penalty is a combination of L1 and L2. Attributes
classes_ndarray of shape (n_classes, )
A list of class labels known to the classifier.
coef_ndarray of shape (1, n_features) or (n_classes, n_features)
Coefficient of the features in the decision function. coef_ is of shape (1, n_features) when the given problem is binary. In particular, when multi_class='multinomial', coef_ corresponds to outcome 1 (True) and -coef_ corresponds to outcome 0 (False).
intercept_ndarray of shape (1,) or (n_classes,)
Intercept (a.k.a. bias) added to the decision function. If fit_intercept is set to False, the intercept is set to zero. intercept_ is of shape (1,) when the given problem is binary. In particular, when multi_class='multinomial', intercept_ corresponds to outcome 1 (True) and -intercept_ corresponds to outcome 0 (False).
n_iter_ndarray of shape (n_classes,) or (1, )
Actual number of iterations for all classes. If binary or multinomial, it returns only 1 element. For liblinear solver, only the maximum number of iteration across all classes is given. Changed in version 0.20: In SciPy <= 1.0.0 the number of lbfgs iterations may exceed max_iter. n_iter_ will now report at most max_iter. See also
SGDClassifier
Incrementally trained logistic regression (when given the parameter loss="log").
LogisticRegressionCV
Logistic regression with built-in cross validation. Notes The underlying C implementation uses a random number generator to select features when fitting the model. It is thus not uncommon, to have slightly different results for the same input data. If that happens, try with a smaller tol parameter. Predict output may not match that of standalone liblinear in certain cases. See differences from liblinear in the narrative documentation. References L-BFGS-B – Software for Large-scale Bound-constrained Optimization
Ciyou Zhu, Richard Byrd, Jorge Nocedal and Jose Luis Morales. http://users.iems.northwestern.edu/~nocedal/lbfgsb.html LIBLINEAR – A Library for Large Linear Classification
https://www.csie.ntu.edu.tw/~cjlin/liblinear/ SAG – Mark Schmidt, Nicolas Le Roux, and Francis Bach
Minimizing Finite Sums with the Stochastic Average Gradient https://hal.inria.fr/hal-00860051/document SAGA – Defazio, A., Bach F. & Lacoste-Julien S. (2014).
SAGA: A Fast Incremental Gradient Method With Support for Non-Strongly Convex Composite Objectives https://arxiv.org/abs/1407.0202 Hsiang-Fu Yu, Fang-Lan Huang, Chih-Jen Lin (2011). Dual coordinate descent
methods for logistic regression and maximum entropy models. Machine Learning 85(1-2):41-75. https://www.csie.ntu.edu.tw/~cjlin/papers/maxent_dual.pdf Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.linear_model import LogisticRegression
>>> X, y = load_iris(return_X_y=True)
>>> clf = LogisticRegression(random_state=0).fit(X, y)
>>> clf.predict(X[:2, :])
array([0, 0])
>>> clf.predict_proba(X[:2, :])
array([[9.8...e-01, 1.8...e-02, 1.4...e-08],
[9.7...e-01, 2.8...e-02, ...e-08]])
>>> clf.score(X, y)
0.97...
Methods
decision_function(X) Predict confidence scores for samples.
densify() Convert coefficient matrix to dense array format.
fit(X, y[, sample_weight]) Fit the model according to the given training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class labels for samples in X.
predict_log_proba(X) Predict logarithm of probability estimates.
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.
sparsify() Convert coefficient matrix to sparse format.
decision_function(X) [source]
Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)
Confidence scores per (sample, class) combination. In the binary case, confidence score for self.classes_[1] where >0 means this class would be predicted.
densify() [source]
Convert coefficient matrix to dense array format. Converts the coef_ member (back) to a numpy.ndarray. This is the default format of coef_ and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op. Returns
self
Fitted estimator.
fit(X, y, sample_weight=None) [source]
Fit the model according to the given training data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
Target vector relative to X.
sample_weightarray-like of shape (n_samples,) default=None
Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. New in version 0.17: sample_weight support to LogisticRegression. Returns
self
Fitted estimator. Notes The SAGA solver supports both float64 and float32 bit arrays.
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 labels for samples in X. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape [n_samples]
Predicted class label per sample.
predict_log_proba(X) [source]
Predict logarithm of probability estimates. The returned estimates for all classes are ordered by the label of classes. Parameters
Xarray-like of shape (n_samples, n_features)
Vector to be scored, where n_samples is the number of samples and n_features is the number of features. Returns
Tarray-like of shape (n_samples, n_classes)
Returns the log-probability of the sample for each class in the model, where classes are ordered as they are in self.classes_.
predict_proba(X) [source]
Probability estimates. The returned estimates for all classes are ordered by the label of classes. For a multi_class problem, if multi_class is set to be “multinomial” the softmax function is used to find the predicted probability of each class. Else use a one-vs-rest approach, i.e calculate the probability of each class assuming it to be positive using the logistic function. and normalize these values across all the classes. Parameters
Xarray-like of shape (n_samples, n_features)
Vector to be scored, where n_samples is the number of samples and n_features is the number of features. Returns
Tarray-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.
sparsify() [source]
Convert coefficient matrix to sparse format. Converts the coef_ member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation. The intercept_ member is not converted. Returns
self
Fitted estimator. Notes For non-sparse models, i.e. when there are not many zeros in coef_, this may actually increase memory usage, so use this method with care. A rule of thumb is that the number of zero elements, which can be computed with (coef_ == 0).sum(), must be more than 50% for this to provide significant benefits. After calling this method, further fitting with the partial_fit method (if any) will not work until you call densify.
Examples using sklearn.linear_model.LogisticRegression
Release Highlights for scikit-learn 0.23
Release Highlights for scikit-learn 0.24
Release Highlights for scikit-learn 0.22
Comparison of Calibration of Classifiers
Probability Calibration curves
Plot classification probability
Plot class probabilities calculated by the VotingClassifier
Feature transformations with ensembles of trees
Logistic function
Regularization path of L1- Logistic Regression
Logistic Regression 3-class Classifier
Comparing various online solvers
MNIST classification using multinomial logistic + L1
Plot multinomial and One-vs-Rest Logistic Regression
L1 Penalty and Sparsity in Logistic Regression
Multiclass sparse logistic regression on 20newgroups
Compact estimator representations
Visualizations with Display Objects
Classifier Chain
Restricted Boltzmann Machine features for digit classification
Pipelining: chaining a PCA and a logistic regression
Column Transformer with Mixed Types
Feature discretization
Digits Classification Exercise | |
doc_4019 | The net mask, as an IPv4Address object. | |
doc_4020 | Assume authentication as user. Allows an authorised administrator to proxy into any user’s mailbox. | |
doc_4021 | operator.le(a, b)
operator.eq(a, b)
operator.ne(a, b)
operator.ge(a, b)
operator.gt(a, b)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)
Perform “rich comparisons” between a and b. Specifically, lt(a, b) is equivalent to a < b, le(a, b) is equivalent to a <= b, eq(a,
b) is equivalent to a == b, ne(a, b) is equivalent to a != b, gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a
>= b. Note that these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons. | |
doc_4022 | tf.experimental.numpy.lcm(
x1, x2
)
Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.lcm. | |
doc_4023 |
Return a string representation of a number in the given base system. Parameters
numberint
The value to convert. Positive and negative values are handled.
baseint, optional
Convert number to the base number system. The valid range is 2-36, the default value is 2.
paddingint, optional
Number of zeros padded on the left. Default is 0 (no padding). Returns
outstr
String representation of number in base system. See also binary_repr
Faster version of base_repr for base 2. Examples >>> np.base_repr(5)
'101'
>>> np.base_repr(6, 5)
'11'
>>> np.base_repr(7, base=5, padding=3)
'00012'
>>> np.base_repr(10, base=16)
'A'
>>> np.base_repr(32, base=16)
'20' | |
doc_4024 |
Return log-probability estimates for the test vector X. Parameters
Xarray-like of shape (n_samples, n_features)
Returns
Carray-like of shape (n_samples, n_classes)
Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. | |
doc_4025 | This function implements the standard .mo file search algorithm. It takes a domain, identical to what textdomain() takes. Optional localedir is as in bindtextdomain(). Optional languages is a list of strings, where each string is a language code. If localedir is not given, then the default system locale directory is used. 2 If languages is not given, then the following environment variables are searched: LANGUAGE, LC_ALL, LC_MESSAGES, and LANG. The first one returning a non-empty value is used for the languages variable. The environment variables should contain a colon separated list of languages, which will be split on the colon to produce the expected list of language code strings. find() then expands and normalizes the languages, and then iterates through them, searching for an existing file built of these components: localedir/language/LC_MESSAGES/domain.mo The first such file name that exists is returned by find(). If no such file is found, then None is returned. If all is given, it returns a list of all file names, in the order in which they appear in the languages list or the environment variables. | |
doc_4026 |
Run the pandas test suite using pytest. | |
doc_4027 | Return a new instance of the named tuple replacing specified fields with new values: >>> p = Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)
>>> for partnum, record in inventory.items():
... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now()) | |
doc_4028 |
Alias for get_edgecolor. | |
doc_4029 | alias of werkzeug.datastructures.ImmutableList | |
doc_4030 |
Construct from two arrays defining the left and right bounds. Parameters
left:array-like (1-dimensional)
Left bounds for each interval.
right:array-like (1-dimensional)
Right bounds for each interval.
closed:{‘left’, ‘right’, ‘both’, ‘neither’}, default ‘right’
Whether the intervals are closed on the left-side, right-side, both or neither.
copy:bool, default False
Copy the data.
dtype:dtype, optional
If None, dtype will be inferred. Returns
IntervalArray
Raises
ValueError
When a value is missing in only one of left or right. When a value in left is greater than the corresponding value in right. See also interval_range
Function to create a fixed frequency IntervalIndex. IntervalArray.from_breaks
Construct an IntervalArray from an array of splits. IntervalArray.from_tuples
Construct an IntervalArray from an array-like of tuples. Notes Each element of left must be less than or equal to the right element at the same position. If an element is missing, it must be missing in both left and right. A TypeError is raised when using an unsupported type for left or right. At the moment, ‘category’, ‘object’, and ‘string’ subtypes are not supported.
>>> pd.arrays.IntervalArray.from_arrays([0, 1, 2], [1, 2, 3])
<IntervalArray>
[(0, 1], (1, 2], (2, 3]]
Length: 3, dtype: interval[int64, right] | |
doc_4031 | See Migration guide for more details. tf.compat.v1.raw_ops.PreventGradient
tf.raw_ops.PreventGradient(
input, message='', name=None
)
When executed in a graph, this op outputs its input tensor as-is. When building ops to compute gradients, the TensorFlow gradient system will return an error when trying to lookup the gradient of this op, because no gradient must ever be registered for this function. This op exists to prevent subtle bugs from silently returning unimplemented gradients in some corner cases.
Args
input A Tensor. any tensor.
message An optional string. Defaults to "". Will be printed in the error when anyone tries to differentiate this operation.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_4032 |
Draw samples from a binomial distribution. Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval [0,1]. (n may be input as a float, but it is truncated to an integer in use) Parameters
nint or array_like of ints
Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.
pfloat or array_like of floats
Parameter of the distribution, >= 0 and <=1.
sizeint or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if n and p are both scalars. Otherwise, np.broadcast(n, p).size samples are drawn. Returns
outndarray or scalar
Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials. See also scipy.stats.binom
probability density function, distribution or cumulative density function, etc. Notes The probability density for the binomial distribution is \[P(N) = \binom{n}{N}p^N(1-p)^{n-N},\] where \(n\) is the number of trials, \(p\) is the probability of success, and \(N\) is the number of successes. When estimating the standard error of a proportion in a population by using a random sample, the normal distribution works well unless the product p*n <=5, where p = population proportion estimate, and n = number of samples, in which case the binomial distribution is used instead. For example, a sample of 15 people shows 4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so the binomial distribution should be used in this case. References 1
Dalgaard, Peter, “Introductory Statistics with R”, Springer-Verlag, 2002. 2
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002. 3
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972. 4
Weisstein, Eric W. “Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html 5
Wikipedia, “Binomial distribution”, https://en.wikipedia.org/wiki/Binomial_distribution Examples Draw samples from the distribution: >>> rng = np.random.default_rng()
>>> n, p = 10, .5 # number of trials, probability of each trial
>>> s = rng.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.
A real world example. A company drills 9 wild-cat oil exploration wells, each with an estimated probability of success of 0.1. All nine wells fail. What is the probability of that happening? Let’s do 20,000 trials of the model, and count the number that generate zero positive results. >>> sum(rng.binomial(9, 0.1, 20000) == 0)/20000.
# answer = 0.38885, or 39%. | |
doc_4033 | Perform a TurtleScreen update. To be used when tracer is turned off. | |
doc_4034 |
[Deprecated] Notes Deprecated since version 3.4: | |
doc_4035 |
Bases: object A backend-independent abstraction of a figure container and controller. The figure manager is used by pyplot to interact with the window in a backend-independent way. It's an adapter for the real (GUI) framework that represents the visual figure on screen. GUI backends define from this class to translate common operations such as show or resize to the GUI-specific code. Non-GUI backends do not support these operations an can just use the base class. This following basic operations are accessible: Window operations show destroy full_screen_toggle resize get_window_title set_window_title Key and mouse button press handling The figure manager sets up default key and mouse button press handling by hooking up the key_press_handler to the matplotlib event system. This ensures the same shortcuts and mouse actions across backends. Other operations Subclasses will have additional attributes and functions to access additional functionality. This is of course backend-specific. For example, most GUI backends have window and toolbar attributes that give access to the native GUI widgets of the respective framework. Attributes
canvasFigureCanvasBase
The backend-specific canvas instance.
numint or str
The figure number.
key_press_handler_idint
The default key handler cid, when using the toolmanager. To disable the default key press handling use: figure.canvas.mpl_disconnect(
figure.canvas.manager.key_press_handler_id)
button_press_handler_idint
The default mouse button handler cid, when using the toolmanager. To disable the default button press handling use: figure.canvas.mpl_disconnect(
figure.canvas.manager.button_press_handler_id)
button_press(event)[source]
[Deprecated] The default Matplotlib button actions for extra mouse buttons. Notes Deprecated since version 3.4.
destroy()[source]
full_screen_toggle()[source]
get_window_title()[source]
Return the title text of the window containing the figure, or None if there is no window (e.g., a PS backend).
key_press(event)[source]
[Deprecated] Implement the default Matplotlib key bindings defined at Navigation keyboard shortcuts. Notes Deprecated since version 3.4.
resize(w, h)[source]
For GUI backends, resize the window (in physical pixels).
set_window_title(title)[source]
Set the title text of the window containing the figure. This has no effect for non-GUI (e.g., PS) backends.
show()[source]
For GUI backends, show the figure window and redraw. For non-GUI backends, raise an exception, unless running headless (i.e. on Linux with an unset DISPLAY); this exception is converted to a warning in Figure.show. | |
doc_4036 |
tick_loc, tick_angle, tick_label | |
doc_4037 |
Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs. Parameters
aarray_like
Input data.
axisint, optional
Axis along which to operate. By default flattened input is used.
outarray, optional
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. New in version 1.22.0.
keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. New in version 1.22.0. Returns
index_arrayndarray
An array of indices or a single index value. See also
argmin, nanargmax
Examples >>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0]) | |
doc_4038 |
Combine list-like of Categorical-like, unioning categories. All categories must have the same dtype. Parameters
to_union:list-like
Categorical, CategoricalIndex, or Series with dtype=’category’.
sort_categories:bool, default False
If true, resulting categories will be lexsorted, otherwise they will be ordered as they appear in the data.
ignore_order:bool, default False
If true, the ordered attribute of the Categoricals will be ignored. Results in an unordered categorical. Returns
Categorical
Raises
TypeError
all inputs do not have the same dtype all inputs do not have the same ordered property all inputs are ordered and their categories are not identical sort_categories=True and Categoricals are ordered ValueError
Empty list of categoricals passed Notes To learn more about categories, see link Examples
>>> from pandas.api.types import union_categoricals
If you want to combine categoricals that do not necessarily have the same categories, union_categoricals will combine a list-like of categoricals. The new categories will be the union of the categories being combined.
>>> a = pd.Categorical(["b", "c"])
>>> b = pd.Categorical(["a", "b"])
>>> union_categoricals([a, b])
['b', 'c', 'a', 'b']
Categories (3, object): ['b', 'c', 'a']
By default, the resulting categories will be ordered as they appear in the categories of the data. If you want the categories to be lexsorted, use sort_categories=True argument.
>>> union_categoricals([a, b], sort_categories=True)
['b', 'c', 'a', 'b']
Categories (3, object): ['a', 'b', 'c']
union_categoricals also works with the case of combining two categoricals of the same categories and order information (e.g. what you could also append for).
>>> a = pd.Categorical(["a", "b"], ordered=True)
>>> b = pd.Categorical(["a", "b", "a"], ordered=True)
>>> union_categoricals([a, b])
['a', 'b', 'a', 'b', 'a']
Categories (2, object): ['a' < 'b']
Raises TypeError because the categories are ordered and not identical.
>>> a = pd.Categorical(["a", "b"], ordered=True)
>>> b = pd.Categorical(["a", "b", "c"], ordered=True)
>>> union_categoricals([a, b])
Traceback (most recent call last):
...
TypeError: to union ordered Categoricals, all categories must be the same
New in version 0.20.0 Ordered categoricals with different categories or orderings can be combined by using the ignore_ordered=True argument.
>>> a = pd.Categorical(["a", "b", "c"], ordered=True)
>>> b = pd.Categorical(["c", "b", "a"], ordered=True)
>>> union_categoricals([a, b], ignore_order=True)
['a', 'b', 'c', 'c', 'b', 'a']
Categories (3, object): ['a', 'b', 'c']
union_categoricals also works with a CategoricalIndex, or Series containing categorical data, but note that the resulting array will always be a plain Categorical
>>> a = pd.Series(["b", "c"], dtype='category')
>>> b = pd.Series(["a", "b"], dtype='category')
>>> union_categoricals([a, b])
['b', 'c', 'a', 'b']
Categories (3, object): ['b', 'c', 'a'] | |
doc_4039 | See Migration guide for more details. tf.compat.v1.train.FeatureList
Attributes
feature repeated Feature feature | |
doc_4040 |
Opens an nvprof trace file and parses autograd annotations. Parameters
path (str) – path to nvprof trace | |
doc_4041 | Add and return a CheckBox control. | |
doc_4042 | Return True if the object is a member descriptor. CPython implementation detail: Member descriptors are attributes defined in extension modules via PyMemberDef structures. For Python implementations without such types, this method will always return False. | |
doc_4043 |
Draw mathtext using matplotlib.mathtext. | |
doc_4044 |
Attributes
accelerator_exec_micros int64 accelerator_exec_micros
children repeated MultiGraphNodeProto children
cpu_exec_micros int64 cpu_exec_micros
exec_micros int64 exec_micros
float_ops int64 float_ops
graph_nodes repeated GraphNodeProto graph_nodes
name string name
output_bytes int64 output_bytes
parameters int64 parameters
peak_bytes int64 peak_bytes
requested_bytes int64 requested_bytes
residual_bytes int64 residual_bytes
total_accelerator_exec_micros int64 total_accelerator_exec_micros
total_cpu_exec_micros int64 total_cpu_exec_micros
total_exec_micros int64 total_exec_micros
total_float_ops int64 total_float_ops
total_output_bytes int64 total_output_bytes
total_parameters int64 total_parameters
total_peak_bytes int64 total_peak_bytes
total_requested_bytes int64 total_requested_bytes
total_residual_bytes int64 total_residual_bytes | |
doc_4045 | Implement checking for unused arguments if desired. The arguments to this function is the set of all argument keys that were actually referred to in the format string (integers for positional arguments, and strings for named arguments), and a reference to the args and kwargs that was passed to vformat. The set of unused args can be calculated from these parameters. check_unused_args() is assumed to raise an exception if the check fails. | |
doc_4046 |
Calculate the illumination intensity for a surface using the defined azimuth and elevation for the light source. This computes the normal vectors for the surface, and then passes them on to shade_normals Parameters
elevation2D array-like
The height values used to generate an illumination map
vert_exagnumber, optional
The amount to exaggerate the elevation values by when calculating illumination. This can be used either to correct for differences in units between the x-y coordinate system and the elevation coordinate system (e.g. decimal degrees vs. meters) or to exaggerate or de-emphasize topographic effects.
dxnumber, optional
The x-spacing (columns) of the input elevation grid.
dynumber, optional
The y-spacing (rows) of the input elevation grid.
fractionnumber, optional
Increases or decreases the contrast of the hillshade. Values greater than one will cause intermediate values to move closer to full illumination or shadow (and clipping any values that move beyond 0 or 1). Note that this is not visually or mathematically the same as vertical exaggeration. Returns
ndarray
A 2D array of illumination values between 0-1, where 0 is completely in shadow and 1 is completely illuminated. | |
doc_4047 | Stop recording the vertices of a polygon. Current turtle position is last vertex of polygon. This will be connected with the first vertex. | |
doc_4048 |
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal. | |
doc_4049 |
[Deprecated] Return (N, 2) array of (x, y) coordinate of the boundary. Notes Deprecated since version 3.5. | |
doc_4050 | tf.keras.layers.Convolution1D Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.Conv1D, tf.compat.v1.keras.layers.Convolution1D
tf.keras.layers.Conv1D(
filters, kernel_size, strides=1, padding='valid',
data_format='channels_last', dilation_rate=1, groups=1,
activation=None, use_bias=True, kernel_initializer='glorot_uniform',
bias_initializer='zeros', kernel_regularizer=None,
bias_regularizer=None, activity_regularizer=None, kernel_constraint=None,
bias_constraint=None, **kwargs
)
This layer creates a convolution kernel that is convolved with the layer input over a single spatial (or temporal) dimension to produce a tensor of outputs. If use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well. When using this layer as the first layer in a model, provide an input_shape argument (tuple of integers or None, e.g. (10, 128) for sequences of 10 vectors of 128-dimensional vectors, or (None, 128) for variable-length sequences of 128-dimensional vectors. Examples:
# The inputs are 128-length vectors with 10 timesteps, and the batch size
# is 4.
input_shape = (4, 10, 128)
x = tf.random.normal(input_shape)
y = tf.keras.layers.Conv1D(
32, 3, activation='relu',input_shape=input_shape[1:])(x)
print(y.shape)
(4, 8, 32)
# With extended batch shape [4, 7] (e.g. weather data where batch
# dimensions correspond to spatial location and the third dimension
# corresponds to time.)
input_shape = (4, 7, 10, 128)
x = tf.random.normal(input_shape)
y = tf.keras.layers.Conv1D(
32, 3, activation='relu', input_shape=input_shape[2:])(x)
print(y.shape)
(4, 7, 8, 32)
Arguments
filters Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution).
kernel_size An integer or tuple/list of a single integer, specifying the length of the 1D convolution window.
strides An integer or tuple/list of a single integer, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1.
padding One of "valid", "same" or "causal" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. "causal" results in causal (dilated) convolutions, e.g. output[t] does not depend on input[t+1:]. Useful when modeling temporal data where the model should not violate the temporal order. See WaveNet: A Generative Model for Raw Audio, section 2.1.
data_format A string, one of channels_last (default) or channels_first.
dilation_rate an integer or tuple/list of a single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any strides value != 1.
groups A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with filters / groups filters. The output is the concatenation of all the groups results along the channel axis. Input channels and filters must both be divisible by groups.
activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations).
use_bias Boolean, whether the layer uses a bias vector.
kernel_initializer Initializer for the kernel weights matrix ( see keras.initializers).
bias_initializer Initializer for the bias vector ( see keras.initializers).
kernel_regularizer Regularizer function applied to the kernel weights matrix (see keras.regularizers).
bias_regularizer Regularizer function applied to the bias vector ( see keras.regularizers).
activity_regularizer Regularizer function applied to the output of the layer (its "activation") ( see keras.regularizers).
kernel_constraint Constraint function applied to the kernel matrix ( see keras.constraints).
bias_constraint Constraint function applied to the bias vector ( see keras.constraints). Input shape: 3+D tensor with shape: batch_shape + (steps, input_dim) Output shape: 3+D tensor with shape: batch_shape + (new_steps, filters) steps value might have changed due to padding or strides.
Returns A tensor of rank 3 representing activation(conv1d(inputs, kernel) + bias).
Raises
ValueError when both strides > 1 and dilation_rate > 1. | |
doc_4051 |
Return greyscale local autolevel of an image. This filter locally stretches the histogram of greyvalues to cover the entire range of values from “white” to “black”. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters
image2-D array (uint8, uint16)
Input image.
selem2-D array
The neighborhood expressed as a 2-D array of 1’s and 0’s.
out2-D array (same dtype as input)
If None, a new array is allocated.
maskndarray
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
shift_x, shift_yint
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
p0, p1float in [0, …, 1]
Define the [p0, p1] percentile interval to be considered for computing the value. Returns
out2-D array (same dtype as input image)
Output image. | |
doc_4052 | operator.__ior__(a, b)
a = ior(a, b) is equivalent to a |= b. | |
doc_4053 |
Bases: matplotlib.offsetbox.AnchoredOffsetbox Draw an anchored ellipse of a given size. Parameters
transformmatplotlib.transforms.Transform
The transformation object for the coordinate system in use, i.e., matplotlib.axes.Axes.transData.
width, heightfloat
Width and height of the ellipse, given in coordinates of transform.
anglefloat
Rotation of the ellipse, in degrees, anti-clockwise.
locstr
Location of this ellipse. Valid locations are 'upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center, 'lower right'. For backward compatibility, numeric values are accepted as well. See the parameter loc of Legend for details.
padfloat, default: 0.1
Padding around the ellipse, in fraction of the font size.
borderpadfloat, default: 0.1
Border padding, in fraction of the font size.
frameonbool, default: True
If True, draw a box around the ellipse.
propmatplotlib.font_manager.FontProperties, optional
Font property used as a reference for paddings. **kwargs
Keyword arguments forwarded to AnchoredOffsetbox. Attributes
ellipsematplotlib.patches.Ellipse
Ellipse patch drawn. set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, bbox_to_anchor=<UNSET>, child=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, gid=<UNSET>, height=<UNSET>, in_layout=<UNSET>, label=<UNSET>, offset=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, width=<UNSET>, zorder=<UNSET>)[source]
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
bbox_to_anchor unknown
child unknown
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
figure Figure
gid str
height float
in_layout bool
label object
offset (float, float) or callable
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
width float
zorder float
Examples using mpl_toolkits.axes_grid1.anchored_artists.AnchoredEllipse
Simple Anchored Artists | |
doc_4054 |
Bases: matplotlib.ticker.LogFormatterMathtext Format values following scientific notation in a logarithmic axis. | |
doc_4055 | See Migration guide for more details. tf.compat.v1.raw_ops.UnbatchDataset
tf.raw_ops.UnbatchDataset(
input_dataset, output_types, output_shapes, name=None
)
Args
input_dataset A Tensor of type variant.
output_types A list of tf.DTypes that has length >= 1.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_4056 | Return a DOMEventStream that represents the (Unicode) string. | |
doc_4057 | See Migration guide for more details. tf.compat.v1.raw_ops.RetrieveTPUEmbeddingAdagradParametersGradAccumDebug
tf.raw_ops.RetrieveTPUEmbeddingAdagradParametersGradAccumDebug(
num_shards, shard_id, table_id=-1, table_name='', config='',
name=None
)
An op that retrieves optimization parameters from embedding to host memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up the correct embedding table configuration. For example, this op is used to retrieve updated parameters before saving a checkpoint.
Args
num_shards An int.
shard_id An int.
table_id An optional int. Defaults to -1.
table_name An optional string. Defaults to "".
config An optional string. Defaults to "".
name A name for the operation (optional).
Returns A tuple of Tensor objects (parameters, accumulators, gradient_accumulators). parameters A Tensor of type float32.
accumulators A Tensor of type float32.
gradient_accumulators A Tensor of type float32. | |
doc_4058 | >>> print(windll.kernel32)
<WinDLL 'kernel32', handle ... at ...>
>>> print(cdll.msvcrt)
<CDLL 'msvcrt', handle ... at ...>
>>> libc = cdll.msvcrt
>>>
Windows appends the usual .dll file suffix automatically. Note Accessing the standard C library through cdll.msvcrt will use an outdated version of the library that may be incompatible with the one being used by Python. Where possible, use native Python functionality, or else import and use the msvcrt module. On Linux, it is required to specify the filename including the extension to load a library, so attribute access can not be used to load libraries. Either the LoadLibrary() method of the dll loaders should be used, or you should load the library by creating an instance of CDLL by calling the constructor: >>> cdll.LoadLibrary("libc.so.6")
<CDLL 'libc.so.6', handle ... at ...>
>>> libc = CDLL("libc.so.6")
>>> libc
<CDLL 'libc.so.6', handle ... at ...>
>>>
Accessing functions from loaded dlls Functions are accessed as attributes of dll objects: >>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ctypes.py", line 239, in __getattr__
func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
Note that win32 system dlls like kernel32 and user32 often export ANSI as well as UNICODE versions of a function. The UNICODE version is exported with an W appended to the name, while the ANSI version is exported with an A appended to the name. The win32 GetModuleHandle function, which returns a module handle for a given module name, has the following C prototype, and a macro is used to expose one of them as GetModuleHandle depending on whether UNICODE is defined or not: /* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
windll does not try to select one of them by magic, you must access the version you need by specifying GetModuleHandleA or GetModuleHandleW explicitly, and then call it with bytes or string objects respectively. Sometimes, dlls export functions with names which aren’t valid Python identifiers, like "??2@YAPAXI@Z". In this case you have to use getattr() to retrieve the function: >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")
<_FuncPtr object at 0x...>
>>>
On Windows, some dlls export functions not by name but by ordinal. These functions can be accessed by indexing the dll object with the ordinal number: >>> cdll.kernel32[1]
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ctypes.py", line 310, in __getitem__
func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
Calling functions You can call these functions like any other Python callable. This example uses the time() function, which returns system time in seconds since the Unix epoch, and the GetModuleHandleA() function, which returns a win32 module handle. This example calls both functions with a NULL pointer (None should be used as the NULL pointer): >>> print(libc.time(None))
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))
0x1d000000
>>>
ValueError is raised when you call an stdcall function with the cdecl calling convention, or vice versa: >>> cdll.kernel32.GetModuleHandleA(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>
>>> windll.msvcrt.printf(b"spam")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
To find out the correct calling convention you have to look into the C header file or the documentation for the function you want to call. On Windows, ctypes uses win32 structured exception handling to prevent crashes from general protection faults when functions are called with invalid argument values: >>> windll.kernel32.GetModuleHandleA(32)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>
There are, however, enough ways to crash Python with ctypes, so you should be careful anyway. The faulthandler module can be helpful in debugging crashes (e.g. from segmentation faults produced by erroneous C library calls). None, integers, bytes objects and (unicode) strings are the only native Python objects that can directly be used as parameters in these function calls. None is passed as a C NULL pointer, bytes objects and strings are passed as pointer to the memory block that contains their data (char * or wchar_t *). Python integers are passed as the platforms default C int type, their value is masked to fit into the C type. Before we move on calling functions with other parameter types, we have to learn more about ctypes data types. Fundamental data types ctypes defines a number of primitive C compatible data types:
ctypes type C type Python type
c_bool _Bool bool (1)
c_char char 1-character bytes object
c_wchar wchar_t 1-character string
c_byte char int
c_ubyte unsigned char int
c_short short int
c_ushort unsigned short int
c_int int int
c_uint unsigned int int
c_long long int
c_ulong unsigned long int
c_longlong __int64 or long long int
c_ulonglong unsigned __int64 or unsigned long long int
c_size_t size_t int
c_ssize_t ssize_t or Py_ssize_t int
c_float float float
c_double double float
c_longdouble long double float
c_char_p char * (NUL terminated) bytes object or None
c_wchar_p wchar_t * (NUL terminated) string or None
c_void_p void * int or None The constructor accepts any object with a truth value. All these types can be created by calling them with an optional initializer of the correct type and value: >>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
Since these types are mutable, their value can also be changed afterwards: >>> i = c_int(42)
>>> print(i)
c_long(42)
>>> print(i.value)
42
>>> i.value = -99
>>> print(i.value)
-99
>>>
Assigning a new value to instances of the pointer types c_char_p, c_wchar_p, and c_void_p changes the memory location they point to, not the contents of the memory block (of course not, because Python bytes objects are immutable): >>> s = "Hello, World"
>>> c_s = c_wchar_p(s)
>>> print(c_s)
c_wchar_p(139966785747344)
>>> print(c_s.value)
Hello World
>>> c_s.value = "Hi, there"
>>> print(c_s) # the memory location has changed
c_wchar_p(139966783348904)
>>> print(c_s.value)
Hi, there
>>> print(s) # first object is unchanged
Hello, World
>>>
You should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has a create_string_buffer() function which creates these in various ways. The current memory block contents can be accessed (or changed) with the raw property; if you want to access it as NUL terminated string, use the value property: >>> from ctypes import *
>>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
>>> print(sizeof(p), repr(p.raw))
3 b'\x00\x00\x00'
>>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string
>>> print(sizeof(p), repr(p.raw))
6 b'Hello\x00'
>>> print(repr(p.value))
b'Hello'
>>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
>>> print(sizeof(p), repr(p.raw))
10 b'Hello\x00\x00\x00\x00\x00'
>>> p.value = b"Hi"
>>> print(sizeof(p), repr(p.raw))
10 b'Hi\x00lo\x00\x00\x00\x00\x00'
>>>
The create_string_buffer() function replaces the c_buffer() function (which is still available as an alias), as well as the c_string() function from earlier ctypes releases. To create a mutable memory block containing unicode characters of the C type wchar_t use the create_unicode_buffer() function. Calling functions, continued Note that printf prints to the real standard output channel, not to sys.stdout, so these examples will only work at the console prompt, not from within IDLE or PythonWin: >>> printf = libc.printf
>>> printf(b"Hello, %s\n", b"World!")
Hello, World!
14
>>> printf(b"Hello, %S\n", "World!")
Hello, World!
14
>>> printf(b"%d bottles of beer\n", 42)
42 bottles of beer
19
>>> printf(b"%f bottles of beer\n", 42.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
>>>
As has been mentioned before, all Python types except integers, strings, and bytes objects have to be wrapped in their corresponding ctypes type, so that they can be converted to the required C data type: >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
An int 1234, a double 3.140000
31
>>>
Calling functions with your own custom data types You can also customize ctypes argument conversion to allow instances of your own classes be used as function arguments. ctypes looks for an _as_parameter_ attribute and uses this as the function argument. Of course, it must be one of integer, string, or bytes: >>> class Bottles:
... def __init__(self, number):
... self._as_parameter_ = number
...
>>> bottles = Bottles(42)
>>> printf(b"%d bottles of beer\n", bottles)
42 bottles of beer
19
>>>
If you don’t want to store the instance’s data in the _as_parameter_ instance variable, you could define a property which makes the attribute available on request. Specifying the required argument types (function prototypes) It is possible to specify the required argument types of functions exported from DLLs by setting the argtypes attribute. argtypes must be a sequence of C data types (the printf function is probably not a good example here, because it takes a variable number and different types of parameters depending on the format string, on the other hand this is quite handy to experiment with this feature): >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
>>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
String 'Hi', Int 10, Double 2.200000
37
>>>
Specifying a format protects against incompatible argument types (just as a prototype for a C function), and tries to convert the arguments to valid types: >>> printf(b"%d %d %d", 1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: wrong type
>>> printf(b"%s %d %f\n", b"X", 2, 3)
X 2 3.000000
13
>>>
If you have defined your own classes which you pass to function calls, you have to implement a from_param() class method for them to be able to use them in the argtypes sequence. The from_param() class method receives the Python object passed to the function call, it should do a typecheck or whatever is needed to make sure this object is acceptable, and then return the object itself, its _as_parameter_ attribute, or whatever you want to pass as the C function argument in this case. Again, the result should be an integer, string, bytes, a ctypes instance, or an object with an _as_parameter_ attribute. Return types By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object. Here is a more advanced example, it uses the strchr function, which expects a string pointer and a char, and returns a pointer to a string: >>> strchr = libc.strchr
>>> strchr(b"abcdef", ord("d"))
8059983
>>> strchr.restype = c_char_p # c_char_p is a pointer to a string
>>> strchr(b"abcdef", ord("d"))
b'def'
>>> print(strchr(b"abcdef", ord("x")))
None
>>>
If you want to avoid the ord("x") calls above, you can set the argtypes attribute, and the second argument will be converted from a single character Python bytes object into a C char: >>> strchr.restype = c_char_p
>>> strchr.argtypes = [c_char_p, c_char]
>>> strchr(b"abcdef", b"d")
'def'
>>> strchr(b"abcdef", b"def")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: one character string expected
>>> print(strchr(b"abcdef", b"x"))
None
>>> strchr(b"abcdef", b"d")
'def'
>>>
You can also use a callable Python object (a function or a class for example) as the restype attribute, if the foreign function returns an integer. The callable will be called with the integer the C function returns, and the result of this call will be used as the result of your function call. This is useful to check for error return values and automatically raise an exception: >>> GetModuleHandle = windll.kernel32.GetModuleHandleA
>>> def ValidHandle(value):
... if value == 0:
... raise WinError()
... return value
...
>>>
>>> GetModuleHandle.restype = ValidHandle
>>> GetModuleHandle(None)
486539264
>>> GetModuleHandle("something silly")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in ValidHandle
OSError: [Errno 126] The specified module could not be found.
>>>
WinError is a function which will call Windows FormatMessage() api to get the string representation of an error code, and returns an exception. WinError takes an optional error code parameter, if no one is used, it calls GetLastError() to retrieve it. Please note that a much more powerful error checking mechanism is available through the errcheck attribute; see the reference manual for details. Passing pointers (or: passing parameters by reference) Sometimes a C api function expects a pointer to a data type as parameter, probably to write into the corresponding location, or if the data is too large to be passed by value. This is also known as passing parameters by reference. ctypes exports the byref() function which is used to pass parameters by reference. The same effect can be achieved with the pointer() function, although pointer() does a lot more work since it constructs a real pointer object, so it is faster to use byref() if you don’t need the pointer object in Python itself: >>> i = c_int()
>>> f = c_float()
>>> s = create_string_buffer(b'\000' * 32)
>>> print(i.value, f.value, repr(s.value))
0 0.0 b''
>>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
... byref(i), byref(f), s)
3
>>> print(i.value, f.value, repr(s.value))
1 3.1400001049 b'Hello'
>>>
Structures and unions Structures and unions must derive from the Structure and Union base classes which are defined in the ctypes module. Each subclass must define a _fields_ attribute. _fields_ must be a list of 2-tuples, containing a field name and a field type. The field type must be a ctypes type like c_int, or any other derived ctypes type: structure, union, array, pointer. Here is a simple example of a POINT structure, which contains two integers named x and y, and also shows how to initialize a structure in the constructor: >>> from ctypes import *
>>> class POINT(Structure):
... _fields_ = [("x", c_int),
... ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print(point.x, point.y)
10 20
>>> point = POINT(y=5)
>>> print(point.x, point.y)
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: too many initializers
>>>
You can, however, build much more complicated structures. A structure can itself contain other structures by using a structure as a field type. Here is a RECT structure which contains two POINTs named upperleft and lowerright: >>> class RECT(Structure):
... _fields_ = [("upperleft", POINT),
... ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print(rc.upperleft.x, rc.upperleft.y)
0 5
>>> print(rc.lowerright.x, rc.lowerright.y)
0 0
>>>
Nested structures can also be initialized in the constructor in several ways: >>> r = RECT(POINT(1, 2), POINT(3, 4))
>>> r = RECT((1, 2), (3, 4))
Field descriptors can be retrieved from the class, they are useful for debugging because they can provide useful information: >>> print(POINT.x)
<Field type=c_long, ofs=0, size=4>
>>> print(POINT.y)
<Field type=c_long, ofs=4, size=4>
>>>
Warning ctypes does not support passing unions or structures with bit-fields to functions by value. While this may work on 32-bit x86, it’s not guaranteed by the library to work in the general case. Unions and structures with bit-fields should always be passed to functions by pointer. Structure/union alignment and byte order By default, Structure and Union fields are aligned in the same way the C compiler does it. It is possible to override this behavior by specifying a _pack_ class attribute in the subclass definition. This must be set to a positive integer and specifies the maximum alignment for the fields. This is what #pragma pack(n) also does in MSVC. ctypes uses the native byte order for Structures and Unions. To build structures with non-native byte order, you can use one of the BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion base classes. These classes cannot contain pointer fields. Bit fields in structures and unions It is possible to create structures and unions containing bit fields. Bit fields are only possible for integer fields, the bit width is specified as the third item in the _fields_ tuples: >>> class Int(Structure):
... _fields_ = [("first_16", c_int, 16),
... ("second_16", c_int, 16)]
...
>>> print(Int.first_16)
<Field type=c_long, ofs=0:0, bits=16>
>>> print(Int.second_16)
<Field type=c_long, ofs=0:16, bits=16>
>>>
Arrays Arrays are sequences, containing a fixed number of instances of the same type. The recommended way to create array types is by multiplying a data type with a positive integer: TenPointsArrayType = POINT * 10
Here is an example of a somewhat artificial data type, a structure containing 4 POINTs among other stuff: >>> from ctypes import *
>>> class POINT(Structure):
... _fields_ = ("x", c_int), ("y", c_int)
...
>>> class MyStruct(Structure):
... _fields_ = [("a", c_int),
... ("b", c_float),
... ("point_array", POINT * 4)]
>>>
>>> print(len(MyStruct().point_array))
4
>>>
Instances are created in the usual way, by calling the class: arr = TenPointsArrayType()
for pt in arr:
print(pt.x, pt.y)
The above code print a series of 0 0 lines, because the array contents is initialized to zeros. Initializers of the correct type can also be specified: >>> from ctypes import *
>>> TenIntegers = c_int * 10
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> print(ii)
<c_long_Array_10 object at 0x...>
>>> for i in ii: print(i, end=" ")
...
1 2 3 4 5 6 7 8 9 10
>>>
Pointers Pointer instances are created by calling the pointer() function on a ctypes type: >>> from ctypes import *
>>> i = c_int(42)
>>> pi = pointer(i)
>>>
Pointer instances have a contents attribute which returns the object to which the pointer points, the i object above: >>> pi.contents
c_long(42)
>>>
Note that ctypes does not have OOR (original object return), it constructs a new, equivalent object each time you retrieve an attribute: >>> pi.contents is i
False
>>> pi.contents is pi.contents
False
>>>
Assigning another c_int instance to the pointer’s contents attribute would cause the pointer to point to the memory location where this is stored: >>> i = c_int(99)
>>> pi.contents = i
>>> pi.contents
c_long(99)
>>>
Pointer instances can also be indexed with integers: >>> pi[0]
99
>>>
Assigning to an integer index changes the pointed to value: >>> print(i)
c_long(99)
>>> pi[0] = 22
>>> print(i)
c_long(22)
>>>
It is also possible to use indexes different from 0, but you must know what you’re doing, just as in C: You can access or change arbitrary memory locations. Generally you only use this feature if you receive a pointer from a C function, and you know that the pointer actually points to an array instead of a single item. Behind the scenes, the pointer() function does more than simply create pointer instances, it has to create pointer types first. This is done with the POINTER() function, which accepts any ctypes type, and returns a new type: >>> PI = POINTER(c_int)
>>> PI
<class 'ctypes.LP_c_long'>
>>> PI(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected c_long instead of int
>>> PI(c_int(42))
<ctypes.LP_c_long object at 0x...>
>>>
Calling the pointer type without an argument creates a NULL pointer. NULL pointers have a False boolean value: >>> null_ptr = POINTER(c_int)()
>>> print(bool(null_ptr))
False
>>>
ctypes checks for NULL when dereferencing pointers (but dereferencing invalid non-NULL pointers would crash Python): >>> null_ptr[0]
Traceback (most recent call last):
....
ValueError: NULL pointer access
>>>
>>> null_ptr[0] = 1234
Traceback (most recent call last):
....
ValueError: NULL pointer access
>>>
Type conversions Usually, ctypes does strict type checking. This means, if you have POINTER(c_int) in the argtypes list of a function or as the type of a member field in a structure definition, only instances of exactly the same type are accepted. There are some exceptions to this rule, where ctypes accepts other objects. For example, you can pass compatible array instances instead of pointer types. So, for POINTER(c_int), ctypes accepts an array of c_int: >>> class Bar(Structure):
... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
...
>>> bar = Bar()
>>> bar.values = (c_int * 3)(1, 2, 3)
>>> bar.count = 3
>>> for i in range(bar.count):
... print(bar.values[i])
...
1
2
3
>>>
In addition, if a function argument is explicitly declared to be a pointer type (such as POINTER(c_int)) in argtypes, an object of the pointed type (c_int in this case) can be passed to the function. ctypes will apply the required byref() conversion in this case automatically. To set a POINTER type field to NULL, you can assign None: >>> bar.values = None
>>>
Sometimes you have instances of incompatible types. In C, you can cast one type into another type. ctypes provides a cast() function which can be used in the same way. The Bar structure defined above accepts POINTER(c_int) pointers or c_int arrays for its values field, but not instances of other types: >>> bar.values = (c_byte * 4)()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
>>>
For these cases, the cast() function is handy. The cast() function can be used to cast a ctypes instance into a pointer to a different ctypes data type. cast() takes two parameters, a ctypes object that is or can be converted to a pointer of some kind, and a ctypes pointer type. It returns an instance of the second argument, which references the same memory block as the first argument: >>> a = (c_byte * 4)()
>>> cast(a, POINTER(c_int))
<ctypes.LP_c_long object at ...>
>>>
So, cast() can be used to assign to the values field of Bar the structure: >>> bar = Bar()
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
>>> print(bar.values[0])
0
>>>
Incomplete Types Incomplete Types are structures, unions or arrays whose members are not yet specified. In C, they are specified by forward declarations, which are defined later: struct cell; /* forward declaration */
struct cell {
char *name;
struct cell *next;
};
The straightforward translation into ctypes code would be this, but it does not work: >>> class cell(Structure):
... _fields_ = [("name", c_char_p),
... ("next", POINTER(cell))]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in cell
NameError: name 'cell' is not defined
>>>
because the new class cell is not available in the class statement itself. In ctypes, we can define the cell class and set the _fields_ attribute later, after the class statement: >>> from ctypes import *
>>> class cell(Structure):
... pass
...
>>> cell._fields_ = [("name", c_char_p),
... ("next", POINTER(cell))]
>>>
Let’s try it. We create two instances of cell, and let them point to each other, and finally follow the pointer chain a few times: >>> c1 = cell()
>>> c1.name = b"foo"
>>> c2 = cell()
>>> c2.name = b"bar"
>>> c1.next = pointer(c2)
>>> c2.next = pointer(c1)
>>> p = c1
>>> for i in range(8):
... print(p.name, end=" ")
... p = p.next[0]
...
foo bar foo bar foo bar foo bar
>>>
Callback functions ctypes allows creating C callable function pointers from Python callables. These are sometimes called callback functions. First, you must create a class for the callback function. The class knows the calling convention, the return type, and the number and types of arguments this function will receive. The CFUNCTYPE() factory function creates types for callback functions using the cdecl calling convention. On Windows, the WINFUNCTYPE() factory function creates types for callback functions using the stdcall calling convention. Both of these factory functions are called with the result type as first argument, and the callback functions expected argument types as the remaining arguments. I will present an example here which uses the standard C library’s qsort() function, that is used to sort items with the help of a callback function. qsort() will be used to sort an array of integers: >>> IntArray5 = c_int * 5
>>> ia = IntArray5(5, 1, 7, 33, 99)
>>> qsort = libc.qsort
>>> qsort.restype = None
>>>
qsort() must be called with a pointer to the data to sort, the number of items in the data array, the size of one item, and a pointer to the comparison function, the callback. The callback will then be called with two pointers to items, and it must return a negative integer if the first item is smaller than the second, a zero if they are equal, and a positive integer otherwise. So our callback function receives pointers to integers, and must return an integer. First we create the type for the callback function: >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
>>>
To get started, here is a simple callback that shows the values it gets passed: >>> def py_cmp_func(a, b):
... print("py_cmp_func", a[0], b[0])
... return 0
...
>>> cmp_func = CMPFUNC(py_cmp_func)
>>>
The result: >>> qsort(ia, len(ia), sizeof(c_int), cmp_func)
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 5 7
py_cmp_func 1 7
>>>
Now we can actually compare the two items and return a useful result: >>> def py_cmp_func(a, b):
... print("py_cmp_func", a[0], b[0])
... return a[0] - b[0]
...
>>>
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func))
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 1 7
py_cmp_func 5 7
>>>
As we can easily check, our array is sorted now: >>> for i in ia: print(i, end=" ")
...
1 5 7 33 99
>>>
The function factories can be used as decorator factories, so we may as well write: >>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
... def py_cmp_func(a, b):
... print("py_cmp_func", a[0], b[0])
... return a[0] - b[0]
...
>>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 1 7
py_cmp_func 5 7
>>>
Note Make sure you keep references to CFUNCTYPE() objects as long as they are used from C code. ctypes doesn’t, and if you don’t, they may be garbage collected, crashing your program when a callback is made. Also, note that if the callback function is called in a thread created outside of Python’s control (e.g. by the foreign code that calls the callback), ctypes creates a new dummy Python thread on every invocation. This behavior is correct for most purposes, but it means that values stored with threading.local will not survive across different callbacks, even when those calls are made from the same C thread. Accessing values exported from dlls Some shared libraries not only export functions, they also export variables. An example in the Python library itself is the Py_OptimizeFlag, an integer set to 0, 1, or 2, depending on the -O or -OO flag given on startup. ctypes can access values like this with the in_dll() class methods of the type. pythonapi is a predefined symbol giving access to the Python C api: >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
>>> print(opt_flag)
c_long(0)
>>>
If the interpreter would have been started with -O, the sample would have printed c_long(1), or c_long(2) if -OO would have been specified. An extended example which also demonstrates the use of pointers accesses the PyImport_FrozenModules pointer exported by Python. Quoting the docs for that value: This pointer is initialized to point to an array of struct _frozen records, terminated by one whose members are all NULL or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules. So manipulating this pointer could even prove useful. To restrict the example size, we show only how this table can be read with ctypes: >>> from ctypes import *
>>>
>>> class struct_frozen(Structure):
... _fields_ = [("name", c_char_p),
... ("code", POINTER(c_ubyte)),
... ("size", c_int)]
...
>>>
We have defined the struct _frozen data type, so we can get the pointer to the table: >>> FrozenTable = POINTER(struct_frozen)
>>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
>>>
Since table is a pointer to the array of struct_frozen records, we can iterate over it, but we just have to make sure that our loop terminates, because pointers have no size. Sooner or later it would probably crash with an access violation or whatever, so it’s better to break out of the loop when we hit the NULL entry: >>> for item in table:
... if item.name is None:
... break
... print(item.name.decode("ascii"), item.size)
...
_frozen_importlib 31764
_frozen_importlib_external 41499
__hello__ 161
__phello__ -161
__phello__.spam 161
>>>
The fact that standard Python has a frozen module and a frozen package (indicated by the negative size member) is not well known, it is only used for testing. Try it out with import __hello__ for example. Surprises There are some edges in ctypes where you might expect something other than what actually happens. Consider the following example: >>> from ctypes import *
>>> class POINT(Structure):
... _fields_ = ("x", c_int), ("y", c_int)
...
>>> class RECT(Structure):
... _fields_ = ("a", POINT), ("b", POINT)
...
>>> p1 = POINT(1, 2)
>>> p2 = POINT(3, 4)
>>> rc = RECT(p1, p2)
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
1 2 3 4
>>> # now swap the two points
>>> rc.a, rc.b = rc.b, rc.a
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
3 4 3 4
>>>
Hm. We certainly expected the last statement to print 3 4 1 2. What happened? Here are the steps of the rc.a, rc.b = rc.b, rc.a line above: >>> temp0, temp1 = rc.b, rc.a
>>> rc.a = temp0
>>> rc.b = temp1
>>>
Note that temp0 and temp1 are objects still using the internal buffer of the rc object above. So executing rc.a = temp0 copies the buffer contents of temp0 into rc ‘s buffer. This, in turn, changes the contents of temp1. So, the last assignment rc.b = temp1, doesn’t have the expected effect. Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays doesn’t copy the sub-object, instead it retrieves a wrapper object accessing the root-object’s underlying buffer. Another example that may behave differently from what one would expect is this: >>> s = c_char_p()
>>> s.value = b"abc def ghi"
>>> s.value
b'abc def ghi'
>>> s.value is s.value
False
>>>
Note Objects instantiated from c_char_p can only have their value set to bytes or integers. Why is it printing False? ctypes instances are objects containing a memory block plus some descriptors accessing the contents of the memory. Storing a Python object in the memory block does not store the object itself, instead the contents of the object is stored. Accessing the contents again constructs a new Python object each time! Variable-sized data types ctypes provides some support for variable-sized arrays and structures. The resize() function can be used to resize the memory buffer of an existing ctypes object. The function takes the object as first argument, and the requested size in bytes as the second argument. The memory block cannot be made smaller than the natural memory block specified by the objects type, a ValueError is raised if this is tried: >>> short_array = (c_short * 4)()
>>> print(sizeof(short_array))
8
>>> resize(short_array, 4)
Traceback (most recent call last):
...
ValueError: minimum size is 8
>>> resize(short_array, 32)
>>> sizeof(short_array)
32
>>> sizeof(type(short_array))
8
>>>
This is nice and fine, but how would one access the additional elements contained in this array? Since the type still only knows about 4 elements, we get errors accessing other elements: >>> short_array[:]
[0, 0, 0, 0]
>>> short_array[7]
Traceback (most recent call last):
...
IndexError: invalid index
>>>
Another way to use variable-sized data types with ctypes is to use the dynamic nature of Python, and (re-)define the data type after the required size is already known, on a case by case basis. ctypes reference Finding shared libraries When programming in a compiled language, shared libraries are accessed when compiling/linking a program, and when the program is run. The purpose of the find_library() function is to locate a library in a way similar to what the compiler or runtime loader does (on platforms with several versions of a shared library the most recent should be loaded), while the ctypes library loaders act like when a program is run, and call the runtime loader directly. The ctypes.util module provides a function which can help to determine the library to load.
ctypes.util.find_library(name)
Try to find a library and return a pathname. name is the library name without any prefix like lib, suffix like .so, .dylib or version number (this is the form used for the posix linker option -l). If no library can be found, returns None.
The exact functionality is system dependent. On Linux, find_library() tries to run external programs (/sbin/ldconfig, gcc, objdump and ld) to find the library file. It returns the filename of the library file. Changed in version 3.6: On Linux, the value of the environment variable LD_LIBRARY_PATH is used when searching for libraries, if a library cannot be found by any other means. Here are some examples: >>> from ctypes.util import find_library
>>> find_library("m")
'libm.so.6'
>>> find_library("c")
'libc.so.6'
>>> find_library("bz2")
'libbz2.so.1.0'
>>>
On OS X, find_library() tries several predefined naming schemes and paths to locate the library, and returns a full pathname if successful: >>> from ctypes.util import find_library
>>> find_library("c")
'/usr/lib/libc.dylib'
>>> find_library("m")
'/usr/lib/libm.dylib'
>>> find_library("bz2")
'/usr/lib/libbz2.dylib'
>>> find_library("AGL")
'/System/Library/Frameworks/AGL.framework/AGL'
>>>
On Windows, find_library() searches along the system search path, and returns the full pathname, but since there is no predefined naming scheme a call like find_library("c") will fail and return None. If wrapping a shared library with ctypes, it may be better to determine the shared library name at development time, and hardcode that into the wrapper module instead of using find_library() to locate the library at runtime. Loading shared libraries There are several ways to load shared libraries into the Python process. One way is to instantiate one of the following classes:
class ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
Instances of this class represent loaded shared libraries. Functions in these libraries use the standard C calling convention, and are assumed to return int. On Windows creating a CDLL instance may fail even if the DLL name exists. When a dependent DLL of the loaded DLL is not found, a OSError error is raised with the message “[WinError 126] The specified module could not be found”. This error message does not contain the name of the missing DLL because the Windows API does not return this information making this error hard to diagnose. To resolve this error and determine which DLL is not found, you need to find the list of dependent DLLs and determine which one is not found using Windows debugging and tracing tools.
See also Microsoft DUMPBIN tool – A tool to find DLL dependents.
class ctypes.OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
Windows only: Instances of this class represent loaded shared libraries, functions in these libraries use the stdcall calling convention, and are assumed to return the windows specific HRESULT code. HRESULT values contain information specifying whether the function call failed or succeeded, together with additional error code. If the return value signals a failure, an OSError is automatically raised. Changed in version 3.3: WindowsError used to be raised.
class ctypes.WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0)
Windows only: Instances of this class represent loaded shared libraries, functions in these libraries use the stdcall calling convention, and are assumed to return int by default. On Windows CE only the standard calling convention is used, for convenience the WinDLL and OleDLL use the standard calling convention on this platform.
The Python global interpreter lock is released before calling any function exported by these libraries, and reacquired afterwards.
class ctypes.PyDLL(name, mode=DEFAULT_MODE, handle=None)
Instances of this class behave like CDLL instances, except that the Python GIL is not released during the function call, and after the function execution the Python error flag is checked. If the error flag is set, a Python exception is raised. Thus, this is only useful to call Python C api functions directly.
All these classes can be instantiated by calling them with at least one argument, the pathname of the shared library. If you have an existing handle to an already loaded shared library, it can be passed as the handle named parameter, otherwise the underlying platforms dlopen or LoadLibrary function is used to load the library into the process, and to get a handle to it. The mode parameter can be used to specify how the library is loaded. For details, consult the dlopen(3) manpage. On Windows, mode is ignored. On posix systems, RTLD_NOW is always added, and is not configurable. The use_errno parameter, when set to true, enables a ctypes mechanism that allows accessing the system errno error number in a safe way. ctypes maintains a thread-local copy of the systems errno variable; if you call foreign functions created with use_errno=True then the errno value before the function call is swapped with the ctypes private copy, the same happens immediately after the function call. The function ctypes.get_errno() returns the value of the ctypes private copy, and the function ctypes.set_errno() changes the ctypes private copy to a new value and returns the former value. The use_last_error parameter, when set to true, enables the same mechanism for the Windows error code which is managed by the GetLastError() and SetLastError() Windows API functions; ctypes.get_last_error() and ctypes.set_last_error() are used to request and change the ctypes private copy of the windows error code. The winmode parameter is used on Windows to specify how the library is loaded (since mode is ignored). It takes any value that is valid for the Win32 API LoadLibraryEx flags parameter. When omitted, the default is to use the flags that result in the most secure DLL load to avoiding issues such as DLL hijacking. Passing the full path to the DLL is the safest way to ensure the correct library and dependencies are loaded. Changed in version 3.8: Added winmode parameter.
ctypes.RTLD_GLOBAL
Flag to use as mode parameter. On platforms where this flag is not available, it is defined as the integer zero.
ctypes.RTLD_LOCAL
Flag to use as mode parameter. On platforms where this is not available, it is the same as RTLD_GLOBAL.
ctypes.DEFAULT_MODE
The default mode which is used to load shared libraries. On OSX 10.3, this is RTLD_GLOBAL, otherwise it is the same as RTLD_LOCAL.
Instances of these classes have no public methods. Functions exported by the shared library can be accessed as attributes or by index. Please note that accessing the function through an attribute caches the result and therefore accessing it repeatedly returns the same object each time. On the other hand, accessing it through an index returns a new object each time: >>> from ctypes import CDLL
>>> libc = CDLL("libc.so.6") # On Linux
>>> libc.time == libc.time
True
>>> libc['time'] == libc['time']
False
The following public attributes are available, their name starts with an underscore to not clash with exported function names:
PyDLL._handle
The system handle used to access the library.
PyDLL._name
The name of the library passed in the constructor.
Shared libraries can also be loaded by using one of the prefabricated objects, which are instances of the LibraryLoader class, either by calling the LoadLibrary() method, or by retrieving the library as attribute of the loader instance.
class ctypes.LibraryLoader(dlltype)
Class which loads shared libraries. dlltype should be one of the CDLL, PyDLL, WinDLL, or OleDLL types. __getattr__() has special behavior: It allows loading a shared library by accessing it as attribute of a library loader instance. The result is cached, so repeated attribute accesses return the same library each time.
LoadLibrary(name)
Load a shared library into the process and return it. This method always returns a new instance of the library.
These prefabricated library loaders are available:
ctypes.cdll
Creates CDLL instances.
ctypes.windll
Windows only: Creates WinDLL instances.
ctypes.oledll
Windows only: Creates OleDLL instances.
ctypes.pydll
Creates PyDLL instances.
For accessing the C Python api directly, a ready-to-use Python shared library object is available:
ctypes.pythonapi
An instance of PyDLL that exposes Python C API functions as attributes. Note that all these functions are assumed to return C int, which is of course not always the truth, so you have to assign the correct restype attribute to use these functions.
Loading a library through any of these objects raises an auditing event ctypes.dlopen with string argument name, the name used to load the library.
Accessing a function on a loaded library raises an auditing event ctypes.dlsym with arguments library (the library object) and name (the symbol’s name as a string or integer).
In cases when only the library handle is available rather than the object, accessing a function raises an auditing event ctypes.dlsym/handle with arguments handle (the raw library handle) and name. Foreign functions As explained in the previous section, foreign functions can be accessed as attributes of loaded shared libraries. The function objects created in this way by default accept any number of arguments, accept any ctypes data instances as arguments, and return the default result type specified by the library loader. They are instances of a private class:
class ctypes._FuncPtr
Base class for C callable foreign functions. Instances of foreign functions are also C compatible data types; they represent C function pointers. This behavior can be customized by assigning to special attributes of the foreign function object.
restype
Assign a ctypes type to specify the result type of the foreign function. Use None for void, a function not returning anything. It is possible to assign a callable Python object that is not a ctypes type, in this case the function is assumed to return a C int, and the callable will be called with this integer, allowing further processing or error checking. Using this is deprecated, for more flexible post processing or error checking use a ctypes data type as restype and assign a callable to the errcheck attribute.
argtypes
Assign a tuple of ctypes types to specify the argument types that the function accepts. Functions using the stdcall calling convention can only be called with the same number of arguments as the length of this tuple; functions using the C calling convention accept additional, unspecified arguments as well. When a foreign function is called, each actual argument is passed to the from_param() class method of the items in the argtypes tuple, this method allows adapting the actual argument to an object that the foreign function accepts. For example, a c_char_p item in the argtypes tuple will convert a string passed as argument into a bytes object using ctypes conversion rules. New: It is now possible to put items in argtypes which are not ctypes types, but each item must have a from_param() method which returns a value usable as argument (integer, string, ctypes instance). This allows defining adapters that can adapt custom objects as function parameters.
errcheck
Assign a Python function or another callable to this attribute. The callable will be called with three or more arguments:
callable(result, func, arguments)
result is what the foreign function returns, as specified by the restype attribute. func is the foreign function object itself, this allows reusing the same callable object to check or post process the results of several functions. arguments is a tuple containing the parameters originally passed to the function call, this allows specializing the behavior on the arguments used.
The object that this function returns will be returned from the foreign function call, but it can also check the result value and raise an exception if the foreign function call failed.
exception ctypes.ArgumentError
This exception is raised when a foreign function call cannot convert one of the passed arguments.
On Windows, when a foreign function call raises a system exception (for example, due to an access violation), it will be captured and replaced with a suitable Python exception. Further, an auditing event ctypes.seh_exception with argument code will be raised, allowing an audit hook to replace the exception with its own.
Some ways to invoke foreign function calls may raise an auditing event ctypes.call_function with arguments function pointer and arguments. Function prototypes Foreign functions can also be created by instantiating function prototypes. Function prototypes are similar to function prototypes in C; they describe a function (return type, argument types, calling convention) without defining an implementation. The factory functions must be called with the desired result type and the argument types of the function, and can be used as decorator factories, and as such, be applied to functions through the @wrapper syntax. See Callback functions for examples.
ctypes.CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
The returned function prototype creates functions that use the standard C calling convention. The function will release the GIL during the call. If use_errno is set to true, the ctypes private copy of the system errno variable is exchanged with the real errno value before and after the call; use_last_error does the same for the Windows error code.
ctypes.WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Windows only: The returned function prototype creates functions that use the stdcall calling convention, except on Windows CE where WINFUNCTYPE() is the same as CFUNCTYPE(). The function will release the GIL during the call. use_errno and use_last_error have the same meaning as above.
ctypes.PYFUNCTYPE(restype, *argtypes)
The returned function prototype creates functions that use the Python calling convention. The function will not release the GIL during the call.
Function prototypes created by these factory functions can be instantiated in different ways, depending on the type and number of the parameters in the call:
prototype(address)
Returns a foreign function at the specified address which must be an integer.
prototype(callable)
Create a C callable function (a callback function) from a Python callable.
prototype(func_spec[, paramflags])
Returns a foreign function exported by a shared library. func_spec must be a 2-tuple (name_or_ordinal, library). The first item is the name of the exported function as string, or the ordinal of the exported function as small integer. The second item is the shared library instance.
prototype(vtbl_index, name[, paramflags[, iid]])
Returns a foreign function that will call a COM method. vtbl_index is the index into the virtual function table, a small non-negative integer. name is name of the COM method. iid is an optional pointer to the interface identifier which is used in extended error reporting. COM methods use a special calling convention: They require a pointer to the COM interface as first argument, in addition to those parameters that are specified in the argtypes tuple.
The optional paramflags parameter creates foreign function wrappers with much more functionality than the features described above. paramflags must be a tuple of the same length as argtypes. Each item in this tuple contains further information about a parameter, it must be a tuple containing one, two, or three items. The first item is an integer containing a combination of direction flags for the parameter: 1
Specifies an input parameter to the function. 2
Output parameter. The foreign function fills in a value. 4
Input parameter which defaults to the integer zero. The optional second item is the parameter name as string. If this is specified, the foreign function can be called with named parameters. The optional third item is the default value for this parameter. This example demonstrates how to wrap the Windows MessageBoxW function so that it supports default parameters and named arguments. The C declaration from the windows header file is this: WINUSERAPI int WINAPI
MessageBoxW(
HWND hWnd,
LPCWSTR lpText,
LPCWSTR lpCaption,
UINT uType);
Here is the wrapping with ctypes: >>> from ctypes import c_int, WINFUNCTYPE, windll
>>> from ctypes.wintypes import HWND, LPCWSTR, UINT
>>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
>>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
>>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)
The MessageBox foreign function can now be called in these ways: >>> MessageBox()
>>> MessageBox(text="Spam, spam, spam")
>>> MessageBox(flags=2, text="foo bar")
A second example demonstrates output parameters. The win32 GetWindowRect function retrieves the dimensions of a specified window by copying them into RECT structure that the caller has to supply. Here is the C declaration: WINUSERAPI BOOL WINAPI
GetWindowRect(
HWND hWnd,
LPRECT lpRect);
Here is the wrapping with ctypes: >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
>>> from ctypes.wintypes import BOOL, HWND, RECT
>>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
>>> paramflags = (1, "hwnd"), (2, "lprect")
>>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
>>>
Functions with output parameters will automatically return the output parameter value if there is a single one, or a tuple containing the output parameter values when there are more than one, so the GetWindowRect function now returns a RECT instance, when called. Output parameters can be combined with the errcheck protocol to do further output processing and error checking. The win32 GetWindowRect api function returns a BOOL to signal success or failure, so this function could do the error checking, and raises an exception when the api call failed: >>> def errcheck(result, func, args):
... if not result:
... raise WinError()
... return args
...
>>> GetWindowRect.errcheck = errcheck
>>>
If the errcheck function returns the argument tuple it receives unchanged, ctypes continues the normal processing it does on the output parameters. If you want to return a tuple of window coordinates instead of a RECT instance, you can retrieve the fields in the function and return them instead, the normal processing will no longer take place: >>> def errcheck(result, func, args):
... if not result:
... raise WinError()
... rc = args[1]
... return rc.left, rc.top, rc.bottom, rc.right
...
>>> GetWindowRect.errcheck = errcheck
>>>
Utility functions
ctypes.addressof(obj)
Returns the address of the memory buffer as integer. obj must be an instance of a ctypes type. Raises an auditing event ctypes.addressof with argument obj.
ctypes.alignment(obj_or_type)
Returns the alignment requirements of a ctypes type. obj_or_type must be a ctypes type or instance.
ctypes.byref(obj[, offset])
Returns a light-weight pointer to obj, which must be an instance of a ctypes type. offset defaults to zero, and must be an integer that will be added to the internal pointer value. byref(obj, offset) corresponds to this C code: (((char *)&obj) + offset)
The returned object can only be used as a foreign function call parameter. It behaves similar to pointer(obj), but the construction is a lot faster.
ctypes.cast(obj, type)
This function is similar to the cast operator in C. It returns a new instance of type which points to the same memory block as obj. type must be a pointer type, and obj must be an object that can be interpreted as a pointer.
ctypes.create_string_buffer(init_or_size, size=None)
This function creates a mutable character buffer. The returned object is a ctypes array of c_char. init_or_size must be an integer which specifies the size of the array, or a bytes object which will be used to initialize the array items. If a bytes object is specified as first argument, the buffer is made one item larger than its length so that the last element in the array is a NUL termination character. An integer can be passed as second argument which allows specifying the size of the array if the length of the bytes should not be used. Raises an auditing event ctypes.create_string_buffer with arguments init, size.
ctypes.create_unicode_buffer(init_or_size, size=None)
This function creates a mutable unicode character buffer. The returned object is a ctypes array of c_wchar. init_or_size must be an integer which specifies the size of the array, or a string which will be used to initialize the array items. If a string is specified as first argument, the buffer is made one item larger than the length of the string so that the last element in the array is a NUL termination character. An integer can be passed as second argument which allows specifying the size of the array if the length of the string should not be used. Raises an auditing event ctypes.create_unicode_buffer with arguments init, size.
ctypes.DllCanUnloadNow()
Windows only: This function is a hook which allows implementing in-process COM servers with ctypes. It is called from the DllCanUnloadNow function that the _ctypes extension dll exports.
ctypes.DllGetClassObject()
Windows only: This function is a hook which allows implementing in-process COM servers with ctypes. It is called from the DllGetClassObject function that the _ctypes extension dll exports.
ctypes.util.find_library(name)
Try to find a library and return a pathname. name is the library name without any prefix like lib, suffix like .so, .dylib or version number (this is the form used for the posix linker option -l). If no library can be found, returns None. The exact functionality is system dependent.
ctypes.util.find_msvcrt()
Windows only: return the filename of the VC runtime library used by Python, and by the extension modules. If the name of the library cannot be determined, None is returned. If you need to free memory, for example, allocated by an extension module with a call to the free(void *), it is important that you use the function in the same library that allocated the memory.
ctypes.FormatError([code])
Windows only: Returns a textual description of the error code code. If no error code is specified, the last error code is used by calling the Windows api function GetLastError.
ctypes.GetLastError()
Windows only: Returns the last error code set by Windows in the calling thread. This function calls the Windows GetLastError() function directly, it does not return the ctypes-private copy of the error code.
ctypes.get_errno()
Returns the current value of the ctypes-private copy of the system errno variable in the calling thread. Raises an auditing event ctypes.get_errno with no arguments.
ctypes.get_last_error()
Windows only: returns the current value of the ctypes-private copy of the system LastError variable in the calling thread. Raises an auditing event ctypes.get_last_error with no arguments.
ctypes.memmove(dst, src, count)
Same as the standard C memmove library function: copies count bytes from src to dst. dst and src must be integers or ctypes instances that can be converted to pointers.
ctypes.memset(dst, c, count)
Same as the standard C memset library function: fills the memory block at address dst with count bytes of value c. dst must be an integer specifying an address, or a ctypes instance.
ctypes.POINTER(type)
This factory function creates and returns a new ctypes pointer type. Pointer types are cached and reused internally, so calling this function repeatedly is cheap. type must be a ctypes type.
ctypes.pointer(obj)
This function creates a new pointer instance, pointing to obj. The returned object is of the type POINTER(type(obj)). Note: If you just want to pass a pointer to an object to a foreign function call, you should use byref(obj) which is much faster.
ctypes.resize(obj, size)
This function resizes the internal memory buffer of obj, which must be an instance of a ctypes type. It is not possible to make the buffer smaller than the native size of the objects type, as given by sizeof(type(obj)), but it is possible to enlarge the buffer.
ctypes.set_errno(value)
Set the current value of the ctypes-private copy of the system errno variable in the calling thread to value and return the previous value. Raises an auditing event ctypes.set_errno with argument errno.
ctypes.set_last_error(value)
Windows only: set the current value of the ctypes-private copy of the system LastError variable in the calling thread to value and return the previous value. Raises an auditing event ctypes.set_last_error with argument error.
ctypes.sizeof(obj_or_type)
Returns the size in bytes of a ctypes type or instance memory buffer. Does the same as the C sizeof operator.
ctypes.string_at(address, size=-1)
This function returns the C string starting at memory address address as a bytes object. If size is specified, it is used as size, otherwise the string is assumed to be zero-terminated. Raises an auditing event ctypes.string_at with arguments address, size.
ctypes.WinError(code=None, descr=None)
Windows only: this function is probably the worst-named thing in ctypes. It creates an instance of OSError. If code is not specified, GetLastError is called to determine the error code. If descr is not specified, FormatError() is called to get a textual description of the error. Changed in version 3.3: An instance of WindowsError used to be created.
ctypes.wstring_at(address, size=-1)
This function returns the wide character string starting at memory address address as a string. If size is specified, it is used as the number of characters of the string, otherwise the string is assumed to be zero-terminated. Raises an auditing event ctypes.wstring_at with arguments address, size.
Data types
class ctypes._CData
This non-public class is the common base class of all ctypes data types. Among other things, all ctypes type instances contain a memory block that hold C compatible data; the address of the memory block is returned by the addressof() helper function. Another instance variable is exposed as _objects; this contains other Python objects that need to be kept alive in case the memory block contains pointers. Common methods of ctypes data types, these are all class methods (to be exact, they are methods of the metaclass):
from_buffer(source[, offset])
This method returns a ctypes instance that shares the buffer of the source object. The source object must support the writeable buffer interface. The optional offset parameter specifies an offset into the source buffer in bytes; the default is zero. If the source buffer is not large enough a ValueError is raised. Raises an auditing event ctypes.cdata/buffer with arguments pointer, size, offset.
from_buffer_copy(source[, offset])
This method creates a ctypes instance, copying the buffer from the source object buffer which must be readable. The optional offset parameter specifies an offset into the source buffer in bytes; the default is zero. If the source buffer is not large enough a ValueError is raised. Raises an auditing event ctypes.cdata/buffer with arguments pointer, size, offset.
from_address(address)
This method returns a ctypes type instance using the memory specified by address which must be an integer.
This method, and others that indirectly call this method, raises an auditing event ctypes.cdata with argument address.
from_param(obj)
This method adapts obj to a ctypes type. It is called with the actual object used in a foreign function call when the type is present in the foreign function’s argtypes tuple; it must return an object that can be used as a function call parameter. All ctypes data types have a default implementation of this classmethod that normally returns obj if that is an instance of the type. Some types accept other objects as well.
in_dll(library, name)
This method returns a ctypes type instance exported by a shared library. name is the name of the symbol that exports the data, library is the loaded shared library.
Common instance variables of ctypes data types:
_b_base_
Sometimes ctypes data instances do not own the memory block they contain, instead they share part of the memory block of a base object. The _b_base_ read-only member is the root ctypes object that owns the memory block.
_b_needsfree_
This read-only variable is true when the ctypes data instance has allocated the memory block itself, false otherwise.
_objects
This member is either None or a dictionary containing Python objects that need to be kept alive so that the memory block contents is kept valid. This object is only exposed for debugging; never modify the contents of this dictionary.
Fundamental data types
class ctypes._SimpleCData
This non-public class is the base class of all fundamental ctypes data types. It is mentioned here because it contains the common attributes of the fundamental ctypes data types. _SimpleCData is a subclass of _CData, so it inherits their methods and attributes. ctypes data types that are not and do not contain pointers can now be pickled. Instances have a single attribute:
value
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.
Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently converted to native Python types. In other words, if a foreign function has a restype of c_char_p, you will always receive a Python bytes object, not a c_char_p instance. Subclasses of fundamental data types do not inherit this behavior. So, if a foreign functions restype is a subclass of c_void_p, you will receive an instance of this subclass from the function call. Of course, you can get the value of the pointer by accessing the value attribute. These are the fundamental ctypes data types:
class ctypes.c_byte
Represents the C signed char datatype, and interprets the value as small integer. The constructor accepts an optional integer initializer; no overflow checking is done.
class ctypes.c_char
Represents the C char datatype, and interprets the value as a single character. The constructor accepts an optional string initializer, the length of the string must be exactly one character.
class ctypes.c_char_p
Represents the C char * datatype when it points to a zero-terminated string. For a general character pointer that may also point to binary data, POINTER(c_char) must be used. The constructor accepts an integer address, or a bytes object.
class ctypes.c_double
Represents the C double datatype. The constructor accepts an optional float initializer.
class ctypes.c_longdouble
Represents the C long double datatype. The constructor accepts an optional float initializer. On platforms where sizeof(long double) ==
sizeof(double) it is an alias to c_double.
class ctypes.c_float
Represents the C float datatype. The constructor accepts an optional float initializer.
class ctypes.c_int
Represents the C signed int datatype. The constructor accepts an optional integer initializer; no overflow checking is done. On platforms where sizeof(int) == sizeof(long) it is an alias to c_long.
class ctypes.c_int8
Represents the C 8-bit signed int datatype. Usually an alias for c_byte.
class ctypes.c_int16
Represents the C 16-bit signed int datatype. Usually an alias for c_short.
class ctypes.c_int32
Represents the C 32-bit signed int datatype. Usually an alias for c_int.
class ctypes.c_int64
Represents the C 64-bit signed int datatype. Usually an alias for c_longlong.
class ctypes.c_long
Represents the C signed long datatype. The constructor accepts an optional integer initializer; no overflow checking is done.
class ctypes.c_longlong
Represents the C signed long long datatype. The constructor accepts an optional integer initializer; no overflow checking is done.
class ctypes.c_short
Represents the C signed short datatype. The constructor accepts an optional integer initializer; no overflow checking is done.
class ctypes.c_size_t
Represents the C size_t datatype.
class ctypes.c_ssize_t
Represents the C ssize_t datatype. New in version 3.2.
class ctypes.c_ubyte
Represents the C unsigned char datatype, it interprets the value as small integer. The constructor accepts an optional integer initializer; no overflow checking is done.
class ctypes.c_uint
Represents the C unsigned int datatype. The constructor accepts an optional integer initializer; no overflow checking is done. On platforms where sizeof(int) == sizeof(long) it is an alias for c_ulong.
class ctypes.c_uint8
Represents the C 8-bit unsigned int datatype. Usually an alias for c_ubyte.
class ctypes.c_uint16
Represents the C 16-bit unsigned int datatype. Usually an alias for c_ushort.
class ctypes.c_uint32
Represents the C 32-bit unsigned int datatype. Usually an alias for c_uint.
class ctypes.c_uint64
Represents the C 64-bit unsigned int datatype. Usually an alias for c_ulonglong.
class ctypes.c_ulong
Represents the C unsigned long datatype. The constructor accepts an optional integer initializer; no overflow checking is done.
class ctypes.c_ulonglong
Represents the C unsigned long long datatype. The constructor accepts an optional integer initializer; no overflow checking is done.
class ctypes.c_ushort
Represents the C unsigned short datatype. The constructor accepts an optional integer initializer; no overflow checking is done.
class ctypes.c_void_p
Represents the C void * type. The value is represented as integer. The constructor accepts an optional integer initializer.
class ctypes.c_wchar
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.
class ctypes.c_wchar_p
Represents the C wchar_t * datatype, which must be a pointer to a zero-terminated wide character string. The constructor accepts an integer address, or a string.
class ctypes.c_bool
Represent the C bool datatype (more accurately, _Bool from C99). Its value can be True or False, and the constructor accepts any object that has a truth value.
class ctypes.HRESULT
Windows only: Represents a HRESULT value, which contains success or error information for a function or method call.
class ctypes.py_object
Represents the C PyObject * datatype. Calling this without an argument creates a NULL PyObject * pointer.
The ctypes.wintypes module provides quite some other Windows specific data types, for example HWND, WPARAM, or DWORD. Some useful structures like MSG or RECT are also defined. Structured data types
class ctypes.Union(*args, **kw)
Abstract base class for unions in native byte order.
class ctypes.BigEndianStructure(*args, **kw)
Abstract base class for structures in big endian byte order.
class ctypes.LittleEndianStructure(*args, **kw)
Abstract base class for structures in little endian byte order.
Structures with non-native byte order cannot contain pointer type fields, or any other data types containing pointer type fields.
class ctypes.Structure(*args, **kw)
Abstract base class for structures in native byte order. Concrete structure and union types must be created by subclassing one of these types, and at least define a _fields_ class variable. ctypes will create descriptors which allow reading and writing the fields by direct attribute accesses. These are the
_fields_
A sequence defining the structure fields. The items must be 2-tuples or 3-tuples. The first item is the name of the field, the second item specifies the type of the field; it can be any ctypes data type. For integer type fields like c_int, a third optional item can be given. It must be a small positive integer defining the bit width of the field. Field names must be unique within one structure or union. This is not checked, only one field can be accessed when names are repeated. It is possible to define the _fields_ class variable after the class statement that defines the Structure subclass, this allows creating data types that directly or indirectly reference themselves: class List(Structure):
pass
List._fields_ = [("pnext", POINTER(List)),
...
]
The _fields_ class variable must, however, be defined before the type is first used (an instance is created, sizeof() is called on it, and so on). Later assignments to the _fields_ class variable will raise an AttributeError. It is possible to define sub-subclasses of structure types, they inherit the fields of the base class plus the _fields_ defined in the sub-subclass, if any.
_pack_
An optional small integer that allows overriding the alignment of structure fields in the instance. _pack_ must already be defined when _fields_ is assigned, otherwise it will have no effect.
_anonymous_
An optional sequence that lists the names of unnamed (anonymous) fields. _anonymous_ must be already defined when _fields_ is assigned, otherwise it will have no effect. The fields listed in this variable must be structure or union type fields. ctypes will create descriptors in the structure type that allows accessing the nested fields directly, without the need to create the structure or union field. Here is an example type (Windows): class _U(Union):
_fields_ = [("lptdesc", POINTER(TYPEDESC)),
("lpadesc", POINTER(ARRAYDESC)),
("hreftype", HREFTYPE)]
class TYPEDESC(Structure):
_anonymous_ = ("u",)
_fields_ = [("u", _U),
("vt", VARTYPE)]
The TYPEDESC structure describes a COM data type, the vt field specifies which one of the union fields is valid. Since the u field is defined as anonymous field, it is now possible to access the members directly off the TYPEDESC instance. td.lptdesc and td.u.lptdesc are equivalent, but the former is faster since it does not need to create a temporary union instance: td = TYPEDESC()
td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)
It is possible to define sub-subclasses of structures, they inherit the fields of the base class. If the subclass definition has a separate _fields_ variable, the fields specified in this are appended to the fields of the base class. Structure and union constructors accept both positional and keyword arguments. Positional arguments are used to initialize member fields in the same order as they are appear in _fields_. Keyword arguments in the constructor are interpreted as attribute assignments, so they will initialize _fields_ with the same name, or create new attributes for names not present in _fields_.
Arrays and pointers
class ctypes.Array(*args)
Abstract base class for arrays. The recommended way to create concrete array types is by multiplying any ctypes data type with a positive integer. Alternatively, you can subclass this type and define _length_ and _type_ class variables. Array elements can be read and written using standard subscript and slice accesses; for slice reads, the resulting object is not itself an Array.
_length_
A positive integer specifying the number of elements in the array. Out-of-range subscripts result in an IndexError. Will be returned by len().
_type_
Specifies the type of each element in the array.
Array subclass constructors accept positional arguments, used to initialize the elements in order.
class ctypes._Pointer
Private, abstract base class for pointers. Concrete pointer types are created by calling POINTER() with the type that will be pointed to; this is done automatically by pointer(). If a pointer points to an array, its elements can be read and written using standard subscript and slice accesses. Pointer objects have no size, so len() will raise TypeError. Negative subscripts will read from the memory before the pointer (as in C), and out-of-range subscripts will probably crash with an access violation (if you’re lucky).
_type_
Specifies the type pointed to.
contents
Returns the object to which to pointer points. Assigning to this attribute changes the pointer to point to the assigned object. | |
doc_4059 | The total number of objects, across all pages. Note When determining the number of objects contained in object_list, Paginator will first try calling object_list.count(). If object_list has no count() method, then Paginator will fall back to using len(object_list). This allows objects, such as QuerySet, to use a more efficient count() method when available. | |
doc_4060 | Renders a label tag for the form field using the template specified by Form.template_name_label. The available context is:
field: This instance of the BoundField.
contents: By default a concatenated string of BoundField.label and Form.label_suffix (or Field.label_suffix, if set). This can be overridden by the contents and label_suffix arguments.
attrs: A dict containing for, Form.required_css_class, and id. id is generated by the field’s widget attrs or BoundField.auto_id. Additional attributes can be provided by the attrs argument.
use_tag: A boolean which is True if the label has an id. If False the default template omits the <label> tag. Tip In your template field is the instance of the BoundField. Therefore field.field accesses BoundField.field being the field you declare, e.g. forms.CharField. To separately render the label tag of a form field, you can call its label_tag() method: >>> f = ContactForm(data={'message': ''})
>>> print(f['message'].label_tag())
<label for="id_message">Message:</label>
If you’d like to customize the rendering this can be achieved by overriding the Form.template_name_label attribute or more generally by overriding the default template, see also Overriding built-in form templates. Changed in Django 4.0: The label is now rendered using the template engine. | |
doc_4061 | Return True if the underlying lock is acquired. | |
doc_4062 |
Parameters
new_scale (float) – Value to use as the new scale backoff factor. | |
doc_4063 | Return the hyperbolic tangent of x. | |
doc_4064 | Byte-compile all the .py files found along sys.path. Return a true value if all the files compiled successfully, and a false value otherwise. If skip_curdir is true (the default), the current directory is not included in the search. All other parameters are passed to the compile_dir() function. Note that unlike the other compile functions, maxlevels defaults to 0. Changed in version 3.2: Added the legacy and optimize parameter. Changed in version 3.5: quiet parameter was changed to a multilevel value. Changed in version 3.5: The legacy parameter only writes out .pyc files, not .pyo files no matter what the value of optimize is. Changed in version 3.7: The invalidation_mode parameter was added. Changed in version 3.7.2: The invalidation_mode parameter’s default value is updated to None. | |
doc_4065 |
Estimates the shrunk Ledoit-Wolf covariance matrix. Read more in the User Guide. Parameters
Xarray-like of shape (n_samples, n_features)
Data from which to compute the covariance estimate
assume_centeredbool, default=False
If True, data will not be centered before computation. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, data will be centered before computation.
block_sizeint, default=1000
Size of blocks into which the covariance matrix will be split. This is purely a memory optimization and does not affect results. Returns
shrunk_covndarray of shape (n_features, n_features)
Shrunk covariance.
shrinkagefloat
Coefficient in the convex combination used for the computation of the shrunk estimate. Notes The regularized (shrunk) covariance is: (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features) where mu = trace(cov) / n_features | |
doc_4066 |
Return the snap setting. See set_snap for details. | |
doc_4067 | Return an independent clone of this BytesGenerator instance with the exact same option settings, and fp as the new outfp. | |
doc_4068 | draw a circle circle(surface, x, y, r, color) -> None Draws an unfilled circle on the given surface. For a filled circle use filled_circle().
Parameters:
surface (Surface) -- surface to draw on
x (int) -- x coordinate of the center of the circle
y (int) -- y coordinate of the center of the circle
r (int) -- radius of the circle
color (Color or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
Returns:
None
Return type:
NoneType | |
doc_4069 |
Return the xaxis' tick locations in data coordinates. | |
doc_4070 | Returns the unique elements of the input tensor. Note This function is different from torch.unique_consecutive() in the sense that this function also eliminates non-consecutive duplicate values. Note Currently in the CUDA implementation and the CPU implementation when dim is specified, torch.unique always sort the tensor at the beginning regardless of the sort argument. Sorting could be slow, so if your input tensor is already sorted, it is recommended to use torch.unique_consecutive() which avoids the sorting. Parameters
input (Tensor) – the input tensor
sorted (bool) – Whether to sort the unique elements in ascending order before returning as output.
return_inverse (bool) – Whether to also return the indices for where elements in the original input ended up in the returned unique list.
return_counts (bool) – Whether to also return the counts for each unique element.
dim (int) – the dimension to apply unique. If None, the unique of the flattened input is returned. default: None
Returns
A tensor or a tuple of tensors containing
output (Tensor): the output list of unique scalar elements.
inverse_indices (Tensor): (optional) if return_inverse is True, there will be an additional returned tensor (same shape as input) representing the indices for where elements in the original input map to in the output; otherwise, this function will only return a single tensor.
counts (Tensor): (optional) if return_counts is True, there will be an additional returned tensor (same shape as output or output.size(dim), if dim was specified) representing the number of occurrences for each unique value or tensor. Return type
(Tensor, Tensor (optional), Tensor (optional)) Example: >>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long))
>>> output
tensor([ 2, 3, 1])
>>> output, inverse_indices = torch.unique(
... torch.tensor([1, 3, 2, 3], dtype=torch.long), sorted=True, return_inverse=True)
>>> output
tensor([ 1, 2, 3])
>>> inverse_indices
tensor([ 0, 2, 1, 2])
>>> output, inverse_indices = torch.unique(
... torch.tensor([[1, 3], [2, 3]], dtype=torch.long), sorted=True, return_inverse=True)
>>> output
tensor([ 1, 2, 3])
>>> inverse_indices
tensor([[ 0, 2],
[ 1, 2]]) | |
doc_4071 | See Migration guide for more details. tf.compat.v1.raw_ops.LoadTPUEmbeddingADAMParametersGradAccumDebug
tf.raw_ops.LoadTPUEmbeddingADAMParametersGradAccumDebug(
parameters, momenta, velocities, gradient_accumulators, num_shards, shard_id,
table_id=-1, table_name='', config='', name=None
)
An op that loads optimization parameters into HBM for embedding. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up the correct embedding table configuration. For example, this op is used to install parameters that are loaded from a checkpoint before a training loop is executed.
Args
parameters A Tensor of type float32. Value of parameters used in the ADAM optimization algorithm.
momenta A Tensor of type float32. Value of momenta used in the ADAM optimization algorithm.
velocities A Tensor of type float32. Value of velocities used in the ADAM optimization algorithm.
gradient_accumulators A Tensor of type float32. Value of gradient_accumulators used in the ADAM optimization algorithm.
num_shards An int.
shard_id An int.
table_id An optional int. Defaults to -1.
table_name An optional string. Defaults to "".
config An optional string. Defaults to "".
name A name for the operation (optional).
Returns The created Operation. | |
doc_4072 |
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1). | |
doc_4073 |
Cast to DatetimeIndex of Timestamps, at beginning of period. Parameters
freq:str, default frequency of PeriodIndex
Desired frequency.
how:{‘s’, ‘e’, ‘start’, ‘end’}
Convention for converting period to timestamp; start of period vs. end.
copy:bool, default True
Whether or not to return a copy. Returns
Series with DatetimeIndex | |
doc_4074 | Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that check_password_hash() can check the hash. The format for the hashed string looks like this: method$salt$hash
This method can not generate unsalted passwords but it is possible to set param method=’plain’ in order to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password. If PBKDF2 is wanted it can be enabled by setting the method to pbkdf2:method:iterations where iterations is optional: pbkdf2:sha256:80000$salt$hash
pbkdf2:sha256$salt$hash
Parameters
password (str) – the password to hash.
method (str) – the hash method to use (one that hashlib supports). Can optionally be in the format pbkdf2:method:iterations to enable PBKDF2.
salt_length (int) – the length of the salt in letters. Return type
str | |
doc_4075 |
Wiener-Hunt deconvolution Return the deconvolution with a Wiener-Hunt approach (i.e. with Fourier diagonalisation). Parameters
image(M, N) ndarray
Input degraded image
psfndarray
Point Spread Function. This is assumed to be the impulse response (input image space) if the data-type is real, or the transfer function (Fourier space) if the data-type is complex. There is no constraints on the shape of the impulse response. The transfer function must be of shape (M, N) if is_real is True, (M, N // 2 + 1) otherwise (see np.fft.rfftn).
balancefloat
The regularisation parameter value that tunes the balance between the data adequacy that improve frequency restoration and the prior adequacy that reduce frequency restoration (to avoid noise artifacts).
regndarray, optional
The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf. Shape constraint is the same as for the psf parameter.
is_realboolean, optional
True by default. Specify if psf and reg are provided with hermitian hypothesis, that is only half of the frequency plane is provided (due to the redundancy of Fourier transform of real signal). It’s apply only if psf and/or reg are provided as transfer function. For the hermitian property see uft module or np.fft.rfftn.
clipboolean, optional
True by default. If True, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns
im_deconv(M, N) ndarray
The deconvolved image. Notes This function applies the Wiener filter to a noisy and degraded image by an impulse response (or PSF). If the data model is \[y = Hx + n\] where \(n\) is noise, \(H\) the PSF and \(x\) the unknown original image, the Wiener filter is \[\hat x = F^\dagger (|\Lambda_H|^2 + \lambda |\Lambda_D|^2) \Lambda_H^\dagger F y\] where \(F\) and \(F^\dagger\) are the Fourier and inverse Fourier transforms respectively, \(\Lambda_H\) the transfer function (or the Fourier transform of the PSF, see [Hunt] below) and \(\Lambda_D\) the filter to penalize the restored image frequencies (Laplacian by default, that is penalization of high frequency). The parameter \(\lambda\) tunes the balance between the data (that tends to increase high frequency, even those coming from noise), and the regularization. These methods are then specific to a prior model. Consequently, the application or the true image nature must corresponds to the prior model. By default, the prior model (Laplacian) introduce image smoothness or pixel correlation. It can also be interpreted as high-frequency penalization to compensate the instability of the solution with respect to the data (sometimes called noise amplification or “explosive” solution). Finally, the use of Fourier space implies a circulant property of \(H\), see [Hunt]. References
1
François Orieux, Jean-François Giovannelli, and Thomas Rodet, “Bayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution”, J. Opt. Soc. Am. A 27, 1593-1607 (2010) https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593 http://research.orieux.fr/files/papers/OGR-JOSA10.pdf
2
B. R. Hunt “A matrix theory proof of the discrete convolution theorem”, IEEE Trans. on Audio and Electroacoustics, vol. au-19, no. 4, pp. 285-288, dec. 1971 Examples >>> from skimage import color, data, restoration
>>> img = color.rgb2gray(data.astronaut())
>>> from scipy.signal import convolve2d
>>> psf = np.ones((5, 5)) / 25
>>> img = convolve2d(img, psf, 'same')
>>> img += 0.1 * img.std() * np.random.standard_normal(img.shape)
>>> deconvolved_img = restoration.wiener(img, psf, 1100) | |
doc_4076 | Name of the archive member. | |
doc_4077 | The name of the module defining the class described. | |
doc_4078 | Enable TLS 1.3 post-handshake client authentication. Post-handshake auth is disabled by default and a server can only request a TLS client certificate during the initial handshake. When enabled, a server may request a TLS client certificate at any time after the handshake. When enabled on client-side sockets, the client signals the server that it supports post-handshake authentication. When enabled on server-side sockets, SSLContext.verify_mode must be set to CERT_OPTIONAL or CERT_REQUIRED, too. The actual client cert exchange is delayed until SSLSocket.verify_client_post_handshake() is called and some I/O is performed. Note Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the property value is None and can’t be modified New in version 3.8. | |
doc_4079 |
Return the fontangle as float. | |
doc_4080 | See Migration guide for more details. tf.compat.v1.raw_ops.StatefulUniform
tf.raw_ops.StatefulUniform(
resource, algorithm, shape, dtype=tf.dtypes.float32, name=None
)
The generated values follow a uniform distribution in the range [0, 1). The lower bound 0 is included in the range, while the upper bound 1 is excluded.
Args
resource A Tensor of type resource. The handle of the resource variable that stores the state of the RNG.
algorithm A Tensor of type int64. The RNG algorithm.
shape A Tensor. The shape of the output tensor.
dtype An optional tf.DType. Defaults to tf.float32. The type of the output.
name A name for the operation (optional).
Returns A Tensor of type dtype. | |
doc_4081 | Return the filename corresponding to the controlling terminal of the process. Availability: Unix. | |
doc_4082 | A boolean indicating whether the command outputs SQL statements; if True, the output will automatically be wrapped with BEGIN; and COMMIT;. Default value is False. | |
doc_4083 |
Return the current hatching pattern. | |
doc_4084 |
Dot product that handle the sparse matrix case correctly. Parameters
a{ndarray, sparse matrix}
b{ndarray, sparse matrix}
dense_outputbool, default=False
When False, a and b both being sparse will yield sparse output. When True, output will always be a dense array. Returns
dot_product{ndarray, sparse matrix}
Sparse if a and b are sparse and dense_output=False. | |
doc_4085 | Set when tests can be skipped when they are not useful for PGO. | |
doc_4086 |
YDbDr to RGB color space conversion. Parameters
ydbdr(…, 3) array_like
The image in YDbDr format. Final dimension denotes channels. Returns
out(…, 3) ndarray
The image in RGB format. Same dimensions as input. Raises
ValueError
If ydbdr is not at least 2-D with shape (…, 3). Notes This is the color space commonly used by video codecs, also called the reversible color transform in JPEG2000. References
1
https://en.wikipedia.org/wiki/YDbDr | |
doc_4087 | A string representation of the network, with the mask in prefix notation. with_prefixlen and compressed are always the same as str(network). exploded uses the exploded form the network address. | |
doc_4088 | Alias of BadZipFile, for compatibility with older Python versions. Deprecated since version 3.2. | |
doc_4089 | Valid values are 7bit, 8bit, base64, and quoted-printable. See RFC 2045 for more information. | |
doc_4090 |
Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same. Note New code should use the shuffle method of a default_rng() instance instead; please see the Quick Start. Parameters
xndarray or MutableSequence
The array, list or mutable sequence to be shuffled. Returns
None
See also Generator.shuffle
which should be used for new code. Examples >>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
[1 7 5 2 9 4 3 6 0 8] # random
Multi-dimensional arrays are only shuffled along the first axis: >>> arr = np.arange(9).reshape((3, 3))
>>> np.random.shuffle(arr)
>>> arr
array([[3, 4, 5], # random
[6, 7, 8],
[0, 1, 2]]) | |
doc_4091 | See Migration guide for more details. tf.compat.v1.raw_ops.BytesProducedStatsDataset
tf.raw_ops.BytesProducedStatsDataset(
input_dataset, tag, output_types, output_shapes, name=None
)
Args
input_dataset A Tensor of type variant.
tag A Tensor of type string.
output_types A list of tf.DTypes that has length >= 1.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_4092 | See Migration guide for more details. tf.compat.v1.raw_ops.Copy
tf.raw_ops.Copy(
input, tensor_name='', debug_ops_spec=[], name=None
)
Performs CPU-to-CPU or GPU-to-GPU deep-copying of tensor, depending on the device on which the tensor is allocated. N.B.: If the all downstream attached debug ops are disabled given the current gRPC gating status, the output will simply forward the input tensor without deep-copying. See the documentation of Debug* ops for more details. Unlike the CopyHost Op, this op does not have HostMemory constraint on its input or output.
Args
input A Tensor. Input tensor.
tensor_name An optional string. Defaults to "". The name of the input tensor.
debug_ops_spec An optional list of strings. Defaults to []. A list of debug op spec (op, url, gated_grpc) for attached debug ops. Each element of the list has the format ;;, wherein gated_grpc is boolean represented as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", "DebugIdentity;file:///tmp/tfdbg_1;0".
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_4093 |
Clear the current figure. | |
doc_4094 |
Return the numeric string left-filled with zeros Calls str.zfill element-wise. Parameters
aarray_like, {str, unicode}
Input array.
widthint
Width of string to left-fill elements in a. Returns
outndarray, {str, unicode}
Output array of str or unicode, depending on input type See also str.zfill | |
doc_4095 |
Truncate series to the given degree. Reduce the degree of the series to deg by discarding the high order terms. If deg is greater than the current degree a copy of the current series is returned. This can be useful in least squares where the coefficients of the high degree terms may be very small. New in version 1.5.0. Parameters
degnon-negative int
The series is reduced to degree deg by discarding the high order terms. The value of deg must be a non-negative integer. Returns
new_seriesseries
New instance of series with reduced degree. | |
doc_4096 | See Migration guide for more details. tf.compat.v1.raw_ops.MapDefun
tf.raw_ops.MapDefun(
arguments, captured_inputs, output_types, output_shapes, f,
max_intra_op_parallelism=1, name=None
)
The function given by f is assumed to be stateless, and is executed concurrently on all the slices; up to batch_size (i.e. the size of the 0th dimension of each argument) functions will be scheduled at once. The max_intra_op_parallelism attr, which defaults to 1, can be used to limit the intra op parallelism. To limit inter-op parallelism, a user can set a private threadpool on the dataset using tf.data.Options's ThreadingOptions. Note that this op is not exposed to users directly, but is invoked in tf.data rewrites.
Args
arguments A list of Tensor objects. A list of tensors whose types are Targuments, corresponding to the inputs the function should be mapped over.
captured_inputs A list of Tensor objects. A list of tensors whose types are Tcaptured, corresponding to the captured inputs of the defun.
output_types A list of tf.DTypes that has length >= 1. A list of types.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1. A list of shapes.
f A function decorated with @Defun.
max_intra_op_parallelism An optional int. Defaults to 1.
name A name for the operation (optional).
Returns A list of Tensor objects of type output_types. | |
doc_4097 |
Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: viewer += Plugin(...)
Also note that attach automatically calls the filter function so that the image matches the filtered value specified by attached widgets. | |
doc_4098 |
Applies the silu function, element-wise. silu(x)=x∗σ(x),where σ(x) is the logistic sigmoid.\text{silu}(x) = x * \sigma(x), \text{where } \sigma(x) \text{ is the logistic sigmoid.}
Note See Gaussian Error Linear Units (GELUs) where the SiLU (Sigmoid Linear Unit) was originally coined, and see Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning and Swish: a Self-Gated Activation Function where the SiLU was experimented with later. Shape:
Input: (N,∗)(N, *) where * means, any number of additional dimensions Output: (N,∗)(N, *) , same shape as the input Examples: >>> m = nn.SiLU()
>>> input = torch.randn(2)
>>> output = m(input) | |
doc_4099 | class turtle.RawPen(canvas)
Parameters
canvas – a tkinter.Canvas, a ScrolledCanvas or a TurtleScreen Create a turtle. The turtle has all methods described above as “methods of Turtle/RawTurtle”. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.