_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_26400 | tf.compat.v1.logging.fatal(
msg, *args, **kwargs
) | |
doc_26401 | See Migration guide for more details. tf.compat.v1.raw_ops.StringToHashBucketStrong
tf.raw_ops.StringToHashBucketStrong(
input, num_buckets, key, name=None
)
The hash function is deterministic on the content of the string within the process. The hash function is a keyed hash function, where attribute key defines the key of the hash function. key is an array of 2 elements. A strong hash is important when inputs may be malicious, e.g. URLs with additional components. Adversaries could try to make their inputs hash to the same bucket for a denial-of-service attack or to skew the results. A strong hash can be used to make it difficult to find inputs with a skewed hash value distribution over buckets. This requires that the hash function is seeded by a high-entropy (random) "key" unknown to the adversary. The additional robustness comes at a cost of roughly 4x higher compute time than tf.string_to_hash_bucket_fast. Examples:
tf.strings.to_hash_bucket_strong(["Hello", "TF"], 3, [1, 2]).numpy()
array([2, 0])
Args
input A Tensor of type string. The strings to assign a hash bucket.
num_buckets An int that is >= 1. The number of buckets.
key A list of ints. The key used to seed the hash function, passed as a list of two uint64 elements.
name A name for the operation (optional).
Returns A Tensor of type int64. | |
doc_26402 | Returns a new instance of the QueueHandler class. The instance is initialized with the queue to send messages to. The queue can be any queue-like object; it’s used as-is by the enqueue() method, which needs to know how to send messages to it. The queue is not required to have the task tracking API, which means that you can use SimpleQueue instances for queue.
emit(record)
Enqueues the result of preparing the LogRecord. Should an exception occur (e.g. because a bounded queue has filled up), the handleError() method is called to handle the error. This can result in the record silently being dropped (if logging.raiseExceptions is False) or a message printed to sys.stderr (if logging.raiseExceptions is True).
prepare(record)
Prepares a record for queuing. The object returned by this method is enqueued. The base implementation formats the record to merge the message, arguments, and exception information, if present. It also removes unpickleable items from the record in-place. You might want to override this method if you want to convert the record to a dict or JSON string, or send a modified copy of the record while leaving the original intact.
enqueue(record)
Enqueues the record on the queue using put_nowait(); you may want to override this if you want to use blocking behaviour, or a timeout, or a customized queue implementation. | |
doc_26403 |
Upsamples the input, using nearest neighbours’ pixel values. Warning This function is deprecated in favor of torch.nn.quantized.functional.interpolate(). This is equivalent with nn.quantized.functional.interpolate(..., mode='nearest'). Note The input quantization parameters propagate to the output. Note Only 2D inputs are supported Parameters
input (Tensor) – quantized input
size (int or Tuple[int, int] or Tuple[int, int, int]) – output spatial size.
scale_factor (int) – multiplier for spatial size. Has to be an integer. | |
doc_26404 | tf.keras.utils.pack_x_y_sample_weight(
x, y=None, sample_weight=None
)
This is a convenience utility for packing data into the tuple formats that Model.fit uses. Standalone usage:
x = tf.ones((10, 1))
data = tf.keras.utils.pack_x_y_sample_weight(x)
isinstance(data, tf.Tensor)
True
y = tf.ones((10, 1))
data = tf.keras.utils.pack_x_y_sample_weight(x, y)
isinstance(data, tuple)
True
x, y = data
Arguments
x Features to pass to Model.
y Ground-truth targets to pass to Model.
sample_weight Sample weight for each element.
Returns Tuple in the format used in Model.fit. | |
doc_26405 | Retrieve certificates from Windows’ system cert store. store_name may be one of CA, ROOT or MY. Windows may provide additional cert stores, too. The function returns a list of (cert_bytes, encoding_type, trust) tuples. The encoding_type specifies the encoding of cert_bytes. It is either x509_asn for X.509 ASN.1 data or pkcs_7_asn for PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set of OIDS or exactly True if the certificate is trustworthy for all purposes. Example: >>> ssl.enum_certificates("CA")
[(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
(b'data...', 'x509_asn', True)]
Availability: Windows. New in version 3.4. | |
doc_26406 |
Convert an array of datetimes into an array of strings. Parameters
arrarray_like of datetime64
The array of UTC timestamps to format.
unitstr
One of None, ‘auto’, or a datetime unit.
timezone{‘naive’, ‘UTC’, ‘local’} or tzinfo
Timezone information to use when displaying the datetime. If ‘UTC’, end with a Z to indicate UTC time. If ‘local’, convert to the local timezone first, and suffix with a +-#### timezone offset. If a tzinfo object, then do as with ‘local’, but use the specified timezone.
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}
Casting to allow when changing between datetime units. Returns
str_arrndarray
An array of strings the same shape as arr. Examples >>> import pytz
>>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
>>> d
array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
'2002-10-27T07:30'], dtype='datetime64[m]')
Setting the timezone to UTC shows the same information, but with a Z suffix >>> np.datetime_as_string(d, timezone='UTC')
array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
'2002-10-27T07:30Z'], dtype='<U35')
Note that we picked datetimes that cross a DST boundary. Passing in a pytz timezone object will print the appropriate offset >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
'2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')
Passing in a unit will change the precision >>> np.datetime_as_string(d, unit='h')
array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
dtype='<U32')
>>> np.datetime_as_string(d, unit='s')
array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
'2002-10-27T07:30:00'], dtype='<U38')
‘casting’ can be used to specify whether precision can be changed >>> np.datetime_as_string(d, unit='h', casting='safe')
Traceback (most recent call last):
...
TypeError: Cannot create a datetime string as units 'h' from a NumPy
datetime with units 'm' according to the rule 'safe' | |
doc_26407 |
Get the face color of the Figure rectangle. | |
doc_26408 |
Generate a png file containing latex's rendering of tex string. Return the file name. | |
doc_26409 | tf.compat.v1.summary.all_v2_summary_ops()
This includes ops from TF 2.0 tf.summary and TF 1.x tf.contrib.summary (except for tf.contrib.summary.graph and tf.contrib.summary.import_event), but does not include TF 1.x tf.summary ops.
Returns List of summary ops, or None if called under eager execution. | |
doc_26410 | tf.keras.losses.logcosh, tf.keras.metrics.log_cosh, tf.keras.metrics.logcosh, tf.losses.log_cosh, tf.losses.logcosh, tf.metrics.log_cosh, tf.metrics.logcosh Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.log_cosh, tf.compat.v1.keras.losses.logcosh, tf.compat.v1.keras.metrics.log_cosh, tf.compat.v1.keras.metrics.logcosh
tf.keras.losses.log_cosh(
y_true, y_pred
)
log(cosh(x)) is approximately equal to (x ** 2) / 2 for small x and to abs(x) - log(2) for large x. This means that 'logcosh' works mostly like the mean squared error, but will not be so strongly affected by the occasional wildly incorrect prediction. Standalone usage:
y_true = np.random.random(size=(2, 3))
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.logcosh(y_true, y_pred)
assert loss.shape == (2,)
x = y_pred - y_true
assert np.allclose(
loss.numpy(),
np.mean(x + np.log(np.exp(-2. * x) + 1.) - math_ops.log(2.), axis=-1),
atol=1e-5)
Args
y_true Ground truth values. shape = [batch_size, d0, .. dN].
y_pred The predicted values. shape = [batch_size, d0, .. dN].
Returns Logcosh error values. shape = [batch_size, d0, .. dN-1]. | |
doc_26411 | See Migration guide for more details. tf.compat.v1.raw_ops.AssignAddVariableOp
tf.raw_ops.AssignAddVariableOp(
resource, value, name=None
)
Any ReadVariableOp with a control dependency on this op is guaranteed to see the incremented value or a subsequent newer one.
Args
resource A Tensor of type resource. handle to the resource in which to store the variable.
value A Tensor. the value by which the variable will be incremented.
name A name for the operation (optional).
Returns The created Operation. | |
doc_26412 | See Migration guide for more details. tf.compat.v1.keras.layers.Subtract
tf.keras.layers.Subtract(
**kwargs
)
It takes as input a list of tensors of size 2, both of the same shape, and returns a single tensor, (inputs[0] - inputs[1]), also of the same shape. Examples: import keras
input1 = keras.layers.Input(shape=(16,))
x1 = keras.layers.Dense(8, activation='relu')(input1)
input2 = keras.layers.Input(shape=(32,))
x2 = keras.layers.Dense(8, activation='relu')(input2)
# Equivalent to subtracted = keras.layers.subtract([x1, x2])
subtracted = keras.layers.Subtract()([x1, x2])
out = keras.layers.Dense(4)(subtracted)
model = keras.models.Model(inputs=[input1, input2], outputs=out)
Arguments
**kwargs standard layer keyword arguments. | |
doc_26413 | Create a new dictionary with keys from iterable and values set to value. | |
doc_26414 | This method returns a bitmask specifying the available mixer controls (“Control” being a specific mixable “channel”, such as SOUND_MIXER_PCM or SOUND_MIXER_SYNTH). This bitmask indicates a subset of all available mixer controls—the SOUND_MIXER_* constants defined at module level. To determine if, for example, the current mixer object supports a PCM mixer, use the following Python code: mixer=ossaudiodev.openmixer()
if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
# PCM is supported
... code ...
For most purposes, the SOUND_MIXER_VOLUME (master volume) and SOUND_MIXER_PCM controls should suffice—but code that uses the mixer should be flexible when it comes to choosing mixer controls. On the Gravis Ultrasound, for example, SOUND_MIXER_VOLUME does not exist. | |
doc_26415 |
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
data_interval unknown
figure Figure
gid str
in_layout bool
inverted unknown
label object
label_coords unknown
label_position {'top', 'bottom'}
label_text str
major_formatter Formatter, str, or function
major_locator Locator
minor_formatter Formatter, str, or function
minor_locator Locator
pane_color unknown
pane_pos unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
pickradius float
rasterized bool
remove_overlapping_locs unknown
rotate_label unknown
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
tick_params unknown
ticklabels sequence of str or of Texts
ticks list of floats
ticks_position {'top', 'bottom', 'both', 'default', 'none'}
transform Transform
units units tag
url str
view_interval unknown
visible bool
zorder float | |
doc_26416 | If file_or_dir is a directory and not a symbolic link, then recursively descend the directory tree named by file_or_dir, checking all .py files along the way. If file_or_dir is an ordinary Python source file, it is checked for whitespace related problems. The diagnostic messages are written to standard output using the print() function. | |
doc_26417 | Must be zero. | |
doc_26418 |
Return the vertices of the mesh as an (M+1, N+1, 2) array. M, N are the number of quadrilaterals in the rows / columns of the mesh, corresponding to (M+1, N+1) vertices. The last dimension specifies the components (x, y). | |
doc_26419 |
Perform classification on samples in X. For an one-class model, +1 or -1 is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
Class labels for samples in X. | |
doc_26420 | class collections.abc.MutableSet
ABCs for read-only and mutable sets. | |
doc_26421 |
Return a backend-specific tuple to return to the backend after all processing is done. | |
doc_26422 | This attribute is None by default and becomes a Tensor the first time a call to backward() computes gradients for self. The attribute will then contain the gradients computed and future calls to backward() will accumulate (add) gradients into it. | |
doc_26423 |
Examples using mpl_toolkits.axes_grid1.axes_divider.make_axes_area_auto_adjustable
Make Room For Ylabel Using Axesgrid | |
doc_26424 | Set the current process-wide policy to policy. If policy is set to None, the default policy is restored. | |
doc_26425 |
Do cartesian product of the given sequence of tensors. The behavior is similar to python’s itertools.product. Parameters
*tensors – any number of 1 dimensional tensors. Returns
A tensor equivalent to converting all the input tensors into lists,
do itertools.product on these lists, and finally convert the resulting list into tensor. Return type
Tensor Example: >>> a = [1, 2, 3]
>>> b = [4, 5]
>>> list(itertools.product(a, b))
[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
>>> tensor_a = torch.tensor(a)
>>> tensor_b = torch.tensor(b)
>>> torch.cartesian_prod(tensor_a, tensor_b)
tensor([[1, 4],
[1, 5],
[2, 4],
[2, 5],
[3, 4],
[3, 5]]) | |
doc_26426 | Profile the cmd via exec(). | |
doc_26427 | The total number of to be consumed bytes. | |
doc_26428 |
Bases: mpl_toolkits.axes_grid1.axes_divider.SubplotDivider A SubplotDivider for laying out axes vertically, while ensuring that they have equal widths. Parameters
figmatplotlib.figure.Figure
*argstuple (nrows, ncols, index) or int
The array of subplots in the figure has dimensions (nrows,
ncols), and index is the index of the subplot being created. index starts at 1 in the upper left corner and increases to the right. If nrows, ncols, and index are all single digit numbers, then args can be passed as a single 3-digit number (e.g. 234 for (2, 3, 4)). locate(nx, ny, nx1=None, ny1=None, axes=None, renderer=None)[source]
Parameters
nx, nx1int
Integers specifying the column-position of the cell. When nx1 is None, a single nx-th column is specified. Otherwise location of columns spanning between nx to nx1 (but excluding nx1-th column) is specified.
ny, ny1int
Same as nx and nx1, but for row positions. axes
renderer
new_locator(ny, ny1=None)[source]
Create a new AxesLocator for the specified cell. Parameters
ny, ny1int
Integers specifying the row-position of the cell. When ny1 is None, a single ny-th row is specified. Otherwise location of rows spanning between ny to ny1 (but excluding ny1-th row) is specified. | |
doc_26429 | Set up the environment based on env_vars for running the interpreter in a subprocess. The values can include __isolated, __cleanenv, __cwd, and TERM. Changed in version 3.9: The function no longer strips whitespaces from stderr. | |
doc_26430 |
Bayesian ARD regression. Fit the weights of a regression model, using an ARD prior. The weights of the regression model are assumed to be in Gaussian distributions. Also estimate the parameters lambda (precisions of the distributions of the weights) and alpha (precision of the distribution of the noise). The estimation is done by an iterative procedures (Evidence Maximization) Read more in the User Guide. Parameters
n_iterint, default=300
Maximum number of iterations.
tolfloat, default=1e-3
Stop the algorithm if w has converged.
alpha_1float, default=1e-6
Hyper-parameter : shape parameter for the Gamma distribution prior over the alpha parameter.
alpha_2float, default=1e-6
Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the alpha parameter.
lambda_1float, default=1e-6
Hyper-parameter : shape parameter for the Gamma distribution prior over the lambda parameter.
lambda_2float, default=1e-6
Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the lambda parameter.
compute_scorebool, default=False
If True, compute the objective function at each step of the model.
threshold_lambdafloat, default=10 000
threshold for removing (pruning) weights with high precision from the computation.
fit_interceptbool, default=True
whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
normalizebool, default=False
This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
copy_Xbool, default=True
If True, X will be copied; else, it may be overwritten.
verbosebool, default=False
Verbose mode when fitting the model. Attributes
coef_array-like of shape (n_features,)
Coefficients of the regression model (mean of distribution)
alpha_float
estimated precision of the noise.
lambda_array-like of shape (n_features,)
estimated precisions of the weights.
sigma_array-like of shape (n_features, n_features)
estimated variance-covariance matrix of the weights
scores_float
if computed, value of the objective function (to be maximized)
intercept_float
Independent term in decision function. Set to 0.0 if fit_intercept = False.
X_offset_float
If normalize=True, offset subtracted for centering data to a zero mean.
X_scale_float
If normalize=True, parameter used to scale data to a unit standard deviation. Notes For an example, see examples/linear_model/plot_ard.py. References D. J. C. MacKay, Bayesian nonlinear modeling for the prediction competition, ASHRAE Transactions, 1994. R. Salakhutdinov, Lecture notes on Statistical Machine Learning, http://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=15 Their beta is our self.alpha_ Their alpha is our self.lambda_ ARD is a little different than the slide: only dimensions/features for which self.lambda_ < self.threshold_lambda are kept and the rest are discarded. Examples >>> from sklearn import linear_model
>>> clf = linear_model.ARDRegression()
>>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
ARDRegression()
>>> clf.predict([[1, 1]])
array([1.])
Methods
fit(X, y) Fit the ARDRegression model according to the given training data and parameters.
get_params([deep]) Get parameters for this estimator.
predict(X[, return_std]) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]
Fit the ARDRegression model according to the given training data and parameters. Iterative procedure to maximize the evidence Parameters
Xarray-like of shape (n_samples, n_features)
Training vector, where n_samples in the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
Target values (integers). Will be cast to X’s dtype if necessary Returns
selfreturns an instance of self.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X, return_std=False) [source]
Predict using the linear model. In addition to the mean of the predictive distribution, also its standard deviation can be returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Samples.
return_stdbool, default=False
Whether to return the standard deviation of posterior prediction. Returns
y_meanarray-like of shape (n_samples,)
Mean of predictive distribution of query points.
y_stdarray-like of shape (n_samples,)
Standard deviation of predictive distribution of query points.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_26431 | tf.compat.v1.enable_control_flow_v2()
control flow v2 (cfv2) is an improved version of control flow in TensorFlow with support for higher order derivatives. Enabling cfv2 will change the graph/function representation of control flow, e.g., tf.while_loop and tf.cond will generate functional While and If ops instead of low-level Switch, Merge etc. ops. Note: Importing and running graphs exported with old control flow will still be supported. Calling tf.enable_control_flow_v2() lets you opt-in to this TensorFlow 2.0 feature.
Note: v2 control flow is always enabled inside of tf.function. Calling this function is not required. | |
doc_26432 |
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y. | |
doc_26433 |
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes. | |
doc_26434 | Create a shared threading.Condition object and return a proxy for it. If lock is supplied then it should be a proxy for a threading.Lock or threading.RLock object. Changed in version 3.3: The wait_for() method was added. | |
doc_26435 | Set the current directory on the server. | |
doc_26436 |
Pick the best locator based on a distance. | |
doc_26437 |
Richardson-Lucy deconvolution. Parameters
imagendarray
Input degraded image (can be N dimensional).
psfndarray
The point spread function.
iterationsint, optional
Number of iterations. This parameter plays the role of regularisation.
clipboolean, optional
True by default. If true, pixel value of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. filter_epsilon: float, optional
Value below which intermediate results become 0 to avoid division by small numbers. Returns
im_deconvndarray
The deconvolved image. References
1
https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution Examples >>> from skimage import img_as_float, data, restoration
>>> camera = img_as_float(data.camera())
>>> from scipy.signal import convolve2d
>>> psf = np.ones((5, 5)) / 25
>>> camera = convolve2d(camera, psf, 'same')
>>> camera += 0.1 * camera.std() * np.random.standard_normal(camera.shape)
>>> deconvolved = restoration.richardson_lucy(camera, psf, 5) | |
doc_26438 |
Container for the Philox (4x64) pseudo-random number generator. Parameters
seed{None, int, array_like[ints], SeedSequence}, optional
A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.
counter{None, int, array_like}, optional
Counter to use in the Philox state. Can be either a Python int (long in 2.x) in [0, 2**256) or a 4-element uint64 array. If not provided, the RNG is initialized at 0.
key{None, int, array_like}, optional
Key to use in the Philox state. Unlike seed, the value in key is directly set. Can be either a Python int in [0, 2**128) or a 2-element uint64 array. key and seed cannot both be used. Notes Philox is a 64-bit PRNG that uses a counter-based design based on weaker (and faster) versions of cryptographic functions [1]. Instances using different values of the key produce independent sequences. Philox has a period of \(2^{256} - 1\) and supports arbitrary advancing and jumping the sequence in increments of \(2^{128}\). These features allow multiple non-overlapping sequences to be generated. Philox provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. State and Seeding The Philox state vector consists of a 256-bit value encoded as a 4-element uint64 array and a 128-bit value encoded as a 2-element uint64 array. The former is a counter which is incremented by 1 for every 4 64-bit randoms produced. The second is a key which determined the sequence produced. Using different keys produces independent sequences. The input seed is processed by SeedSequence to generate the key. The counter is set to 0. Alternately, one can omit the seed parameter and set the key and counter directly. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, Philox, SeedSequence
>>> sg = SeedSequence(1234)
>>> rg = [Generator(Philox(s)) for s in sg.spawn(10)]
Philox can be used in parallel applications by calling the jumped method to advances the state as-if \(2^{128}\) random numbers have been generated. Alternatively, advance can be used to advance the counter for any positive step in [0, 2**256). When using jumped, all generators should be chained to ensure that the segments come from the same sequence. >>> from numpy.random import Generator, Philox
>>> bit_generator = Philox(1234)
>>> rg = []
>>> for _ in range(10):
... rg.append(Generator(bit_generator))
... bit_generator = bit_generator.jumped()
Alternatively, Philox can be used in parallel applications by using a sequence of distinct keys where each instance uses different key. >>> key = 2**96 + 2**33 + 2**17 + 2**9
>>> rg = [Generator(Philox(key=key+i)) for i in range(10)]
Compatibility Guarantee Philox makes a guarantee that a fixed seed will always produce the same random integer stream. References 1
John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, “Parallel Random Numbers: As Easy as 1, 2, 3,” Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011. Examples >>> from numpy.random import Generator, Philox
>>> rg = Generator(Philox(1234))
>>> rg.standard_normal()
0.123 # random
Attributes
lock: threading.Lock
Lock instance that is shared so that the same bit git generator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock.
State
state Get or set the PRNG state Parallel generation
advance(delta) Advance the underlying RNG as-if delta draws have occurred.
jumped([jumps]) Returns a new bit generator with the state jumped Extending
cffi CFFI interface
ctypes ctypes interface | |
doc_26439 | socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.) | |
doc_26440 | Return non-zero if the mode is from a whiteout. New in version 3.4. | |
doc_26441 | Same as article(), but sends a HEAD command. The lines returned (or written to file) will only contain the message headers, not the body. | |
doc_26442 |
Return an IntervalArray identical to the current one, but closed on the specified side. Parameters
closed:{‘left’, ‘right’, ‘both’, ‘neither’}
Whether the intervals are closed on the left-side, right-side, both or neither. Returns
new_index:IntervalArray
Examples
>>> index = pd.arrays.IntervalArray.from_breaks(range(4))
>>> index
<IntervalArray>
[(0, 1], (1, 2], (2, 3]]
Length: 3, dtype: interval[int64, right]
>>> index.set_closed('both')
<IntervalArray>
[[0, 1], [1, 2], [2, 3]]
Length: 3, dtype: interval[int64, both] | |
doc_26443 | Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (\t), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed. >>> '01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234' | |
doc_26444 | Namespace-aware variant of AttributesImpl, which will be passed to startElementNS(). It is derived from AttributesImpl, but understands attribute names as two-tuples of namespaceURI and localname. In addition, it provides a number of methods expecting qualified names as they appear in the original document. This class implements the AttributesNS interface (see section The AttributesNS Interface). | |
doc_26445 |
Pass the inputs (and mask) through the decoder layer in turn. Parameters
tgt – the sequence to the decoder (required).
memory – the sequence from the last layer of the encoder (required).
tgt_mask – the mask for the tgt sequence (optional).
memory_mask – the mask for the memory sequence (optional).
tgt_key_padding_mask – the mask for the tgt keys per batch (optional).
memory_key_padding_mask – the mask for the memory keys per batch (optional). Shape:
see the docs in Transformer class. | |
doc_26446 |
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly. | |
doc_26447 | Prepare for object destruction. IOBase provides a default implementation of this method that calls the instance’s close() method. | |
doc_26448 | Add and return a RadioButtonGroup control. | |
doc_26449 | This exception is raised when the urlretrieve() function detects that the amount of the downloaded data is less than the expected amount (given by the Content-Length header). The content attribute stores the downloaded (and supposedly truncated) data. | |
doc_26450 | See Migration guide for more details. tf.compat.v1.raw_ops.DebugNumericSummaryV2
tf.raw_ops.DebugNumericSummaryV2(
input, output_dtype=tf.dtypes.float32, tensor_debug_mode=-1, tensor_id=-1,
name=None
)
Computes a numeric summary of the input tensor. The shape of the output depends on the tensor_debug_mode attribute. This op is used internally by TensorFlow Debugger (tfdbg) v2.
Args
input A Tensor. Input tensor, to be summarized by the op.
output_dtype An optional tf.DType from: tf.float32, tf.float64. Defaults to tf.float32. Optional. The type of the output. Can be float32 or float64 (default: float32).
tensor_debug_mode An optional int. Defaults to -1. Tensor debug mode: the mode in which the input tensor is summarized by the op. See the TensorDebugMode enum in tensorflow/core/protobuf/debug_event.proto for details. Supported values: 2 (CURT_HEALTH): Output a float32/64 tensor of shape [2]. The 1st element is the tensor_id, if provided, and -1 otherwise. The 2nd element is a bit which is set to 1 if the input tensor has an infinity or nan value, or zero otherwise. 3 (CONCISE_HEALTH): Output a float32/64 tensor of shape [5]. The 1st element is the tensor_id, if provided, and -1 otherwise. The remaining four slots are the total number of elements, -infs, +infs, and nans in the input tensor respectively. 4 (FULL_HEALTH): Output a float32/64 tensor of shape [11]. The 1st element is the tensor_id, if provided, and -1 otherwise. The 2nd element is the device_id, if provided, and -1 otherwise. The 3rd element holds the datatype value of the input tensor as according to the enumerated type in tensorflow/core/framework/types.proto. The remaining elements hold the total number of elements, -infs, +infs, nans, negative finite numbers, zeros, and positive finite numbers in the input tensor respectively. 5 (SHAPE): Output a float32/64 tensor of shape [10]. The 1st element is the tensor_id, if provided, and -1 otherwise. The 2nd element holds the datatype value of the input tensor as according to the enumerated type in tensorflow/core/framework/types.proto. The 3rd element holds the rank of the tensor. The 4th element holds the number of elements within the tensor. Finally the remaining 6 elements hold the shape of the tensor. If the rank of the tensor is lower than 6, the shape is right padded with zeros. If the rank is greater than 6, the head of the shape is truncated. 6 (FULL_NUMERICS): Output a float32/64 tensor of shape [22]. The 1st element is the tensor_id, if provided, and -1 otherwise. The 2nd element is the device_id, if provided, and -1 otherwise. The 3rd element holds the datatype value of the input tensor as according to the enumerated type in tensorflow/core/framework/types.proto. The 4th element holds the rank of the tensor. The 5th to 11th elements hold the shape of the tensor. If the rank of the tensor is lower than 6, the shape is right padded with zeros. If the rank is greater than 6, the head of the shape is truncated. The 12th to 18th elements hold the number of elements, -infs, +infs, nans, denormal floats, negative finite numbers, zeros, and positive finite numbers in the input tensor respectively. The final four elements hold the min value, max value, mean, and variance of the input tensor. 8 (REDUCE_INF_NAN_THREE_SLOTS): Output a float32/64 tensor of shape [3]. The 1st element is -inf if any elements of the input tensor is -inf, or zero otherwise. The 2nd element is +inf if any elements of the input tensor is +inf, or zero otherwise. The 3rd element is nan if any element of the input tensor is nan, or zero otherwise.
tensor_id An optional int. Defaults to -1. Optional. An integer identifier for the tensor being summarized by this op.
name A name for the operation (optional).
Returns A Tensor of type output_dtype. | |
doc_26451 |
Set the number of degrees between each longitude grid. | |
doc_26452 |
Jaccard similarity coefficient score. The Jaccard index [1], or Jaccard similarity coefficient, defined as the size of the intersection divided by the size of the union of two label sets, is used to compare set of predicted labels for a sample to the corresponding set of labels in y_true. Read more in the User Guide. Parameters
y_true1d array-like, or label indicator array / sparse matrix
Ground truth (correct) labels.
y_pred1d array-like, or label indicator array / sparse matrix
Predicted labels, as returned by a classifier.
labelsarray-like of shape (n_classes,), default=None
The set of labels to include when average != 'binary', and their order if average is None. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order.
pos_labelstr or int, default=1
The class to report if average='binary' and the data is binary. If the data are multiclass or multilabel, this will be ignored; setting labels=[pos_label] and average != 'binary' will report scores for that label only.
average{None, ‘micro’, ‘macro’, ‘samples’, ‘weighted’, ‘binary’}, default=’binary’
If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data:
'binary':
Only report results for the class specified by pos_label. This is applicable only if targets (y_{true,pred}) are binary.
'micro':
Calculate metrics globally by counting the total true positives, false negatives and false positives.
'macro':
Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
'weighted':
Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). This alters ‘macro’ to account for label imbalance.
'samples':
Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights.
zero_division“warn”, {0.0, 1.0}, default=”warn”
Sets the value to return when there is a zero division, i.e. when there there are no negative values in predictions and labels. If set to “warn”, this acts like 0, but a warning is also raised. Returns
scorefloat (if average is not None) or array of floats, shape = [n_unique_labels]
See also
accuracy_score, f_score, multilabel_confusion_matrix
Notes jaccard_score may be a poor metric if there are no positives for some samples or classes. Jaccard is undefined if there are no true or predicted labels, and our implementation will return a score of 0 with a warning. References
1
Wikipedia entry for the Jaccard index. Examples >>> import numpy as np
>>> from sklearn.metrics import jaccard_score
>>> y_true = np.array([[0, 1, 1],
... [1, 1, 0]])
>>> y_pred = np.array([[1, 1, 1],
... [1, 0, 0]])
In the binary case: >>> jaccard_score(y_true[0], y_pred[0])
0.6666...
In the multilabel case: >>> jaccard_score(y_true, y_pred, average='samples')
0.5833...
>>> jaccard_score(y_true, y_pred, average='macro')
0.6666...
>>> jaccard_score(y_true, y_pred, average=None)
array([0.5, 0.5, 1. ])
In the multiclass case: >>> y_pred = [0, 2, 1, 2]
>>> y_true = [0, 1, 2, 2]
>>> jaccard_score(y_true, y_pred, average=None)
array([1. , 0. , 0.33...]) | |
doc_26453 | Send a file until EOF is reached by using high-performance os.sendfile and return the total number of bytes which were sent. file must be a regular file object opened in binary mode. If os.sendfile is not available (e.g. Windows) or file is not a regular file send() will be used instead. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case file.tell() can be used to figure out the number of bytes which were sent. The socket must be of SOCK_STREAM type. Non-blocking sockets are not supported. New in version 3.5. | |
doc_26454 |
Perform one epoch of stochastic gradient descent on given samples. Internally, this method uses max_iter = 1. Therefore, it is not guaranteed that a minimum of the cost function is reached after calling it once. Matters such as objective convergence and early stopping should be handled by the user. Parameters
X{array-like, sparse matrix}, shape (n_samples, n_features)
Subset of training data
ynumpy array of shape (n_samples,)
Subset of target values
sample_weightarray-like, shape (n_samples,), default=None
Weights applied to individual samples. If not provided, uniform weights are assumed. Returns
selfreturns an instance of self. | |
doc_26455 | A wrapper for a buffer representing picklable data. buffer must be a buffer-providing object, such as a bytes-like object or a N-dimensional array. PickleBuffer is itself a buffer provider, therefore it is possible to pass it to other APIs expecting a buffer-providing object, such as memoryview. PickleBuffer objects can only be serialized using pickle protocol 5 or higher. They are eligible for out-of-band serialization. New in version 3.8.
raw()
Return a memoryview of the memory area underlying this buffer. The returned object is a one-dimensional, C-contiguous memoryview with format B (unsigned bytes). BufferError is raised if the buffer is neither C- nor Fortran-contiguous.
release()
Release the underlying buffer exposed by the PickleBuffer object. | |
doc_26456 | Replaces item’s child with newchildren. Children present in item that are not present in newchildren are detached from the tree. No items in newchildren may be an ancestor of item. Note that not specifying newchildren results in detaching item’s children. | |
doc_26457 | Returns the value of the field nominated by USERNAME_FIELD. | |
doc_26458 | Return True if obj is true, and False otherwise. This is equivalent to using the bool constructor. | |
doc_26459 | >>> g = GeoIP2()
>>> g.country('google.com')
{'country_code': 'US', 'country_name': 'United States'}
>>> g.city('72.14.207.99')
{'city': 'Mountain View',
'continent_code': 'NA',
'continent_name': 'North America',
'country_code': 'US',
'country_name': 'United States',
'dma_code': 807,
'is_in_european_union': False,
'latitude': 37.419200897216797,
'longitude': -122.05740356445312,
'postal_code': '94043',
'region': 'CA',
'time_zone': 'America/Los_Angeles'}
>>> g.lat_lon('salon.com')
(39.0437, -77.4875)
>>> g.lon_lat('uh.edu')
(-95.4342, 29.834)
>>> g.geos('24.124.1.80').wkt
'POINT (-97 38)'
API Reference
class GeoIP2(path=None, cache=0, country=None, city=None)
The GeoIP object does not require any parameters to use the default settings. However, at the very least the GEOIP_PATH setting should be set with the path of the location of your GeoIP datasets. The following initialization keywords may be used to customize any of the defaults.
Keyword Arguments Description
path Base directory to where GeoIP data is located or the full path to where the city or country data files (.mmdb) are located. Assumes that both the city and country datasets are located in this directory; overrides the GEOIP_PATH setting.
cache The cache settings when opening up the GeoIP datasets. May be an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, and GEOIP_INDEX_CACHE MODE_MEMORY C API settings, respectively. Defaults to 0 (MODE_AUTO).
country The name of the GeoIP country data file. Defaults to GeoLite2-Country.mmdb. Setting this keyword overrides the GEOIP_COUNTRY setting.
city The name of the GeoIP city data file. Defaults to GeoLite2-City.mmdb. Setting this keyword overrides the GEOIP_CITY setting. Methods Instantiating
classmethod GeoIP2.open(path, cache)
This classmethod instantiates the GeoIP object from the given database path and given cache setting. Querying All the following querying routines may take either a string IP address or a fully qualified domain name (FQDN). For example, both '205.186.163.125' and 'djangoproject.com' would be valid query parameters.
GeoIP2.city(query)
Returns a dictionary of city information for the given query. Some of the values in the dictionary may be undefined (None).
GeoIP2.country(query)
Returns a dictionary with the country code and country for the given query.
GeoIP2.country_code(query)
Returns the country code corresponding to the query.
GeoIP2.country_name(query)
Returns the country name corresponding to the query. Coordinate Retrieval
GeoIP2.coords(query)
Returns a coordinate tuple of (longitude, latitude).
GeoIP2.lon_lat(query)
Returns a coordinate tuple of (longitude, latitude).
GeoIP2.lat_lon(query)
Returns a coordinate tuple of (latitude, longitude),
GeoIP2.geos(query)
Returns a Point object corresponding to the query. Settings GEOIP_PATH A string or pathlib.Path specifying the directory where the GeoIP data files are located. This setting is required unless manually specified with path keyword when initializing the GeoIP2 object. GEOIP_COUNTRY The basename to use for the GeoIP country data file. Defaults to 'GeoLite2-Country.mmdb'. GEOIP_CITY The basename to use for the GeoIP city data file. Defaults to 'GeoLite2-City.mmdb'. Exceptions
exception GeoIP2Exception
The exception raised when an error occurs in a call to the underlying geoip2 library.
Footnotes
[1]
GeoIP(R) is a registered trademark of MaxMind, Inc. | |
doc_26460 |
Returns the number of splitting iterations in the cross-validator Parameters
Xobject
Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
yobject
Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
groupsarray-like of shape (n_samples,), default=None
Group labels for the samples used while splitting the dataset into train/test set. Returns
n_splitsint
Returns the number of splitting iterations in the cross-validator. | |
doc_26461 | initialize pygame.fastevent init() -> None Initialize the pygame.fastevent module. | |
doc_26462 |
Bases: object Event for tool manipulation (add/remove). | |
doc_26463 |
Set multiple properties at once. Supported properties are
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
latitude_grid unknown
longitude_grid unknown
longitude_grid_ends unknown
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim unknown
xmargin float greater than -0.5
xscale unknown
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim unknown
ymargin float greater than -0.5
yscale unknown
yticklabels unknown
yticks unknown
zorder float | |
doc_26464 |
Bases: matplotlib.container.Container Container for the artists of error bars (e.g. created by Axes.errorbar). The container can be treated as the lines tuple itself. Additionally, you can access these and further parameters by the attributes. Attributes
linestuple
Tuple of (data_line, caplines, barlinecols). data_line : Line2D instance of x, y plot markers and/or line. caplines : tuple of Line2D instances of the error bar caps. barlinecols : list of LineCollection with the horizontal and vertical error ranges.
has_xerr, has_yerrbool
True if the errorbar has x/y errors. | |
doc_26465 | A WSGI middleware which provides static content for development environments or simple server setups. Its usage is quite simple: import os
from werkzeug.middleware.shared_data import SharedDataMiddleware
app = SharedDataMiddleware(app, {
'/shared': os.path.join(os.path.dirname(__file__), 'shared')
})
The contents of the folder ./shared will now be available on http://example.com/shared/. This is pretty useful during development because a standalone media server is not required. Files can also be mounted on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders. If pkg_resources is available you can also tell the middleware to serve files from package data: app = SharedDataMiddleware(app, {
'/static': ('myapplication', 'static')
})
This will then serve the static folder in the myapplication Python package. The optional disallow parameter can be a list of fnmatch() rules for files that are not accessible from the web. If cache is set to False no caching headers are sent. Currently the middleware does not support non-ASCII filenames. If the encoding on the file system happens to match the encoding of the URI it may work but this could also be by accident. We strongly suggest using ASCII only file names for static files. The middleware will guess the mimetype using the Python mimetype module. If it’s unable to figure out the charset it will fall back to fallback_mimetype. Parameters
app (WSGIApplication) – the application to wrap. If you don’t want to wrap an application you can pass it NotFound.
exports (Union[Dict[str, Union[str, Tuple[str, str]]], Iterable[Tuple[str, Union[str, Tuple[str, str]]]]]) – a list or dict of exported files and folders.
disallow (None) – a list of fnmatch() rules.
cache (bool) – enable or disable caching headers.
cache_timeout (int) – the cache timeout in seconds for the headers.
fallback_mimetype (str) – The fallback mimetype for unknown files. Return type
None Changelog Changed in version 1.0: The default fallback_mimetype is application/octet-stream. If a filename looks like a text mimetype, the utf-8 charset is added to it. New in version 0.6: Added fallback_mimetype. Changed in version 0.5: Added cache_timeout.
is_allowed(filename)
Subclasses can override this method to disallow the access to certain files. However by providing disallow in the constructor this method is overwritten. Parameters
filename (str) – Return type
bool | |
doc_26466 |
Transform a new matrix using the built clustering Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples,)
A M by N array of M observations in N dimensions or a length M array of M one-dimensional observations. Returns
Yndarray of shape (n_samples, n_clusters) or (n_clusters,)
The pooled values for each feature cluster. | |
doc_26467 |
Alias for set_linestyle. | |
doc_26468 |
Pause the animation. | |
doc_26469 | See Migration guide for more details. tf.compat.v1.raw_ops.TensorArraySplitV3
tf.raw_ops.TensorArraySplitV3(
handle, value, lengths, flow_in, name=None
)
Assuming that lengths takes on values (n0, n1, ..., n(T-1)) and that value has shape (n0 + n1 + ... + n(T-1) x d0 x d1 x ...), this splits values into a TensorArray with T tensors. TensorArray index t will be the subtensor of values with starting position (n0 + n1 + ... + n(t-1), 0, 0, ...) and having size nt x d0 x d1 x ...
Args
handle A Tensor of type resource. The handle to a TensorArray.
value A Tensor. The concatenated tensor to write to the TensorArray.
lengths A Tensor of type int64. The vector of lengths, how to split the rows of value into the TensorArray.
flow_in A Tensor of type float32. A float scalar that enforces proper chaining of operations.
name A name for the operation (optional).
Returns A Tensor of type float32. | |
doc_26470 | The example’s indentation in the containing string, i.e., the number of space characters that precede the example’s first prompt. | |
doc_26471 | Send advice option to the kernel about the memory region beginning at start and extending length bytes. option must be one of the MADV_* constants available on the system. If start and length are omitted, the entire mapping is spanned. On some systems (including Linux), start must be a multiple of the PAGESIZE. Availability: Systems with the madvise() system call. New in version 3.8. | |
doc_26472 | Return one of the two sequences that generated a delta. Given a sequence produced by Differ.compare() or ndiff(), extract lines originating from file 1 or 2 (parameter which), stripping off line prefixes. Example: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
... 'ore\ntree\nemu\n'.splitlines(keepends=True))
>>> diff = list(diff) # materialize the generated delta into a list
>>> print(''.join(restore(diff, 1)), end="")
one
two
three
>>> print(''.join(restore(diff, 2)), end="")
ore
tree
emu | |
doc_26473 | A single except clause. type is the exception type it will match, typically a Name node (or None for a catch-all except: clause). name is a raw string for the name to hold the exception, or None if the clause doesn’t have as foo. body is a list of nodes. >>> print(ast.dump(ast.parse("""\
... try:
... a + 1
... except TypeError:
... pass
... """), indent=4))
Module(
body=[
Try(
body=[
Expr(
value=BinOp(
left=Name(id='a', ctx=Load()),
op=Add(),
right=Constant(value=1)))],
handlers=[
ExceptHandler(
type=Name(id='TypeError', ctx=Load()),
body=[
Pass()])],
orelse=[],
finalbody=[])],
type_ignores=[]) | |
doc_26474 | This is essentially a wrapper around the fcntl() locking calls. fd is the file descriptor (file objects providing a fileno() method are accepted as well) of the file to lock or unlock, and cmd is one of the following values:
LOCK_UN – unlock
LOCK_SH – acquire a shared lock
LOCK_EX – acquire an exclusive lock When cmd is LOCK_SH or LOCK_EX, it can also be bitwise ORed with LOCK_NB to avoid blocking on lock acquisition. If LOCK_NB is used and the lock cannot be acquired, an OSError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (depending on the operating system; for portability, check for both values). On at least some systems, LOCK_EX can only be used if the file descriptor refers to a file opened for writing. len is the number of bytes to lock, start is the byte offset at which the lock starts, relative to whence, and whence is as with io.IOBase.seek(), specifically:
0 – relative to the start of the file (os.SEEK_SET)
1 – relative to the current buffer position (os.SEEK_CUR)
2 – relative to the end of the file (os.SEEK_END) The default for start is 0, which means to start at the beginning of the file. The default for len is 0 which means to lock to the end of the file. The default for whence is also 0. Raises an auditing event fcntl.lockf with arguments fd, cmd, len, start, whence. | |
doc_26475 |
Set the foreground color of the text Parameters
colorcolor | |
doc_26476 | See Migration guide for more details. tf.compat.v1.raw_ops.HistogramFixedWidth
tf.raw_ops.HistogramFixedWidth(
values, value_range, nbins, dtype=tf.dtypes.int32, name=None
)
Given the tensor values, this operation returns a rank 1 histogram counting the number of entries in values that fall into every bin. The bins are equal width and determined by the arguments value_range and nbins. # Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)
nbins = 5
value_range = [0.0, 5.0]
new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15]
with tf.get_default_session() as sess:
hist = tf.histogram_fixed_width(new_values, value_range, nbins=5)
variables.global_variables_initializer().run()
sess.run(hist) => [2, 1, 1, 0, 2]
Args
values A Tensor. Must be one of the following types: int32, int64, float32, float64. Numeric Tensor.
value_range A Tensor. Must have the same type as values. Shape [2] Tensor of same dtype as values. values <= value_range[0] will be mapped to hist[0], values >= value_range[1] will be mapped to hist[-1].
nbins A Tensor of type int32. Scalar int32 Tensor. Number of histogram bins.
dtype An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int32.
name A name for the operation (optional).
Returns A Tensor of type dtype. | |
doc_26477 |
Disconnect callback id cid. Example usage: cid = toolmanager.toolmanager_connect('tool_trigger_zoom', onpress)
#...later
toolmanager.toolmanager_disconnect(cid) | |
doc_26478 | Return the length of the file, which can be larger than the size of the memory-mapped area. | |
doc_26479 |
Implements feature hashing, aka the hashing trick. This class turns sequences of symbolic feature names (strings) into scipy.sparse matrices, using a hash function to compute the matrix column corresponding to a name. The hash function employed is the signed 32-bit version of Murmurhash3. Feature names of type byte string are used as-is. Unicode strings are converted to UTF-8 first, but no Unicode normalization is done. Feature values must be (finite) numbers. This class is a low-memory alternative to DictVectorizer and CountVectorizer, intended for large-scale (online) learning and situations where memory is tight, e.g. when running prediction code on embedded devices. Read more in the User Guide. New in version 0.13. Parameters
n_featuresint, default=2**20
The number of features (columns) in the output matrices. Small numbers of features are likely to cause hash collisions, but large numbers will cause larger coefficient dimensions in linear learners.
input_type{“dict”, “pair”, “string”}, default=”dict”
Either “dict” (the default) to accept dictionaries over (feature_name, value); “pair” to accept pairs of (feature_name, value); or “string” to accept single strings. feature_name should be a string, while value should be a number. In the case of “string”, a value of 1 is implied. The feature_name is hashed to find the appropriate column for the feature. The value’s sign might be flipped in the output (but see non_negative, below).
dtypenumpy dtype, default=np.float64
The type of feature values. Passed to scipy.sparse matrix constructors as the dtype argument. Do not set this to bool, np.boolean or any unsigned integer type.
alternate_signbool, default=True
When True, an alternating sign is added to the features as to approximately conserve the inner product in the hashed space even for small n_features. This approach is similar to sparse random projection. .. versionchanged:: 0.19
alternate_sign replaces the now deprecated non_negative parameter. See also
DictVectorizer
Vectorizes string-valued features using a hash table.
sklearn.preprocessing.OneHotEncoder
Handles nominal/categorical features. Examples >>> from sklearn.feature_extraction import FeatureHasher
>>> h = FeatureHasher(n_features=10)
>>> D = [{'dog': 1, 'cat':2, 'elephant':4},{'dog': 2, 'run': 5}]
>>> f = h.transform(D)
>>> f.toarray()
array([[ 0., 0., -4., -1., 0., 0., 0., 0., 0., 2.],
[ 0., 0., 0., -2., -5., 0., 0., 0., 0., 0.]])
Methods
fit([X, y]) No-op.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
transform(raw_X) Transform a sequence of instances to a scipy.sparse matrix.
fit(X=None, y=None) [source]
No-op. This method doesn’t do anything. It exists purely for compatibility with the scikit-learn transformer API. Parameters
Xndarray
Returns
selfFeatureHasher
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
transform(raw_X) [source]
Transform a sequence of instances to a scipy.sparse matrix. Parameters
raw_Xiterable over iterable over raw features, length = n_samples
Samples. Each sample must be iterable an (e.g., a list or tuple) containing/generating feature names (and optionally values, see the input_type constructor argument) which will be hashed. raw_X need not support the len function, so it can be the result of a generator; n_samples is determined on the fly. Returns
Xsparse matrix of shape (n_samples, n_features)
Feature matrix, for use with estimators or further transformers. | |
doc_26480 |
Bases: matplotlib.backend_bases.RendererBase Create a new PGF renderer that translates any drawing instruction into text commands to be interpreted in a latex pgfpicture environment. Attributes
figurematplotlib.figure.Figure
Matplotlib figure to initialize height, width and dpi from.
fhfile-like
File handle for the output of the drawing commands. draw_image(gc, x, y, im, transform=None)[source]
Draw an RGBA image. Parameters
gcGraphicsContextBase
A graphics context with clipping information.
xscalar
The distance in physical units (i.e., dots or pixels) from the left hand side of the canvas.
yscalar
The distance in physical units (i.e., dots or pixels) from the bottom side of the canvas.
im(N, M, 4) array-like of np.uint8
An array of RGBA pixels.
transformmatplotlib.transforms.Affine2DBase
If and only if the concrete backend is written such that option_scale_image() returns True, an affine transformation (i.e., an Affine2DBase) may be passed to draw_image(). The translation vector of the transformation is given in physical units (i.e., dots or pixels). Note that the transformation does not override x and y, and has to be applied before translating the result by x and y (this can be accomplished by adding x and y to the translation vector defined by transform).
draw_markers(gc, marker_path, marker_trans, path, trans, rgbFace=None)[source]
Draw a marker at each of path's vertices (excluding control points). This provides a fallback implementation of draw_markers that makes multiple calls to draw_path(). Some backends may want to override this method in order to draw the marker only once and reuse it multiple times. Parameters
gcGraphicsContextBase
The graphics context.
marker_transmatplotlib.transforms.Transform
An affine transform applied to the marker.
transmatplotlib.transforms.Transform
An affine transform applied to the path.
draw_path(gc, path, transform, rgbFace=None)[source]
Draw a Path instance using the given affine transform.
draw_tex(gc, x, y, s, prop, angle, ismath='TeX', mtext=None)[source]
draw_text(gc, x, y, s, prop, angle, ismath=False, mtext=None)[source]
Draw the text instance. Parameters
gcGraphicsContextBase
The graphics context.
xfloat
The x location of the text in display coords.
yfloat
The y location of the text baseline in display coords.
sstr
The text string.
propmatplotlib.font_manager.FontProperties
The font properties.
anglefloat
The rotation angle in degrees anti-clockwise.
mtextmatplotlib.text.Text
The original text object to be rendered. Notes Note for backend implementers: When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in text.py: if 0: bbox_artist(self, renderer)
to if 1, and then the actual bounding box will be plotted along with your text.
flipy()[source]
Return whether y values increase from top to bottom. Note that this only affects drawing of texts and images.
get_canvas_width_height()[source]
Return the canvas width and height in display coords.
get_text_width_height_descent(s, prop, ismath)[source]
Get the width, height, and descent (offset from the bottom to the baseline), in display coords, of the string s with FontProperties prop.
option_image_nocomposite()[source]
Return whether image composition by Matplotlib should be skipped. Raster backends should usually return False (letting the C-level rasterizer take care of image composition); vector backends should usually return not rcParams["image.composite_image"].
option_scale_image()[source]
Return whether arbitrary affine transformations in draw_image() are supported (True for most vector backends).
points_to_pixels(points)[source]
Convert points to display units. You need to override this function (unless your backend doesn't have a dpi, e.g., postscript or svg). Some imaging systems assume some value for pixels per inch: points to pixels = points * pixels_per_inch/72 * dpi/72
Parameters
pointsfloat or array-like
a float or a numpy array of float Returns
Points converted to pixels | |
doc_26481 |
Create a twin Axes sharing the yaxis. Create a new Axes with an invisible y-axis and an independent x-axis positioned opposite to the original one (i.e. at top). The y-axis autoscale setting will be inherited from the original Axes. To ensure that the tick marks of both x-axes align, see LinearLocator. Returns
Axes
The newly created Axes instance Notes For those who are 'picking' artists while using twiny, pick events are only called for the artists in the top-most Axes. | |
doc_26482 | If flag is true, turn debugging on. Otherwise, turn debugging off. When debugging is on, commands to be executed are printed, and the shell is given set -x command to be more verbose. | |
doc_26483 |
A LinearReLU module fused from Linear and ReLU modules We adopt the same interface as torch.nn.quantized.Linear. Variables
as torch.nn.quantized.Linear (Same) – Examples: >>> m = nn.intrinsic.LinearReLU(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 30]) | |
doc_26484 |
Return the clipbox. | |
doc_26485 |
Return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) Returns
list
See also numpy.ndarray.tolist
Return the array as an a.ndim-levels deep nested list of Python scalars. | |
doc_26486 |
Returns True if the file is large enough to require multiple chunks to access all of its content give some chunk_size. | |
doc_26487 | Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today - from datetime.date.today()
For DateTimeField: default=timezone.now - from django.utils.timezone.now() | |
doc_26488 | See Migration guide for more details. tf.compat.v1.raw_ops.AnonymousMultiDeviceIterator
tf.raw_ops.AnonymousMultiDeviceIterator(
devices, output_types, output_shapes, name=None
)
Args
devices A list of strings that has length >= 1.
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 tuple of Tensor objects (handle, deleter). handle A Tensor of type resource.
deleter A Tensor of type variant. | |
doc_26489 |
Return the data portion of the masked array as a hierarchical Python list. Data items are converted to the nearest compatible Python type. Masked values are converted to fill_value. If fill_value is None, the corresponding entries in the output list will be None. Parameters
fill_valuescalar, optional
The value to use for invalid entries. Default is None. Returns
resultlist
The Python list representation of the masked array. Examples >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4)
>>> x.tolist()
[[1, None, 3], [None, 5, None], [7, None, 9]]
>>> x.tolist(-999)
[[1, -999, 3], [-999, 5, -999], [7, -999, 9]] | |
doc_26490 | class sklearn.linear_model.RidgeCV(alphas=0.1, 1.0, 10.0, *, fit_intercept=True, normalize=False, scoring=None, cv=None, gcv_mode=None, store_cv_values=False, alpha_per_target=False) [source]
Ridge regression with built-in cross-validation. See glossary entry for cross-validation estimator. By default, it performs efficient Leave-One-Out Cross-Validation. Read more in the User Guide. Parameters
alphasndarray of shape (n_alphas,), default=(0.1, 1.0, 10.0)
Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to 1 / (2C) in other linear models such as LogisticRegression or LinearSVC. If using Leave-One-Out cross-validation, alphas must be positive.
fit_interceptbool, default=True
Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
normalizebool, default=False
This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
scoringstring, callable, default=None
A string (see model evaluation documentation) or a scorer callable object / function with signature scorer(estimator, X, y). If None, the negative mean squared error if cv is ‘auto’ or None (i.e. when using leave-one-out cross-validation), and r2 score otherwise.
cvint, cross-validation generator or an iterable, default=None
Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the efficient Leave-One-Out cross-validation integer, to specify the number of folds.
CV splitter, An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if y is binary or multiclass, StratifiedKFold is used, else, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.
gcv_mode{‘auto’, ‘svd’, eigen’}, default=’auto’
Flag indicating which strategy to use when performing Leave-One-Out Cross-Validation. Options are: 'auto' : use 'svd' if n_samples > n_features, otherwise use 'eigen'
'svd' : force use of singular value decomposition of X when X is
dense, eigenvalue decomposition of X^T.X when X is sparse.
'eigen' : force computation via eigendecomposition of X.X^T
The ‘auto’ mode is the default and is intended to pick the cheaper option of the two depending on the shape of the training data.
store_cv_valuesbool, default=False
Flag indicating if the cross-validation values corresponding to each alpha should be stored in the cv_values_ attribute (see below). This flag is only compatible with cv=None (i.e. using Leave-One-Out Cross-Validation).
alpha_per_targetbool, default=False
Flag indicating whether to optimize the alpha value (picked from the alphas parameter list) for each target separately (for multi-output settings: multiple prediction targets). When set to True, after fitting, the alpha_ attribute will contain a value for each target. When set to False, a single alpha is used for all targets. New in version 0.24. Attributes
cv_values_ndarray of shape (n_samples, n_alphas) or shape (n_samples, n_targets, n_alphas), optional
Cross-validation values for each alpha (only available if store_cv_values=True and cv=None). After fit() has been called, this attribute will contain the mean squared errors (by default) or the values of the {loss,score}_func function (if provided in the constructor).
coef_ndarray of shape (n_features) or (n_targets, n_features)
Weight vector(s).
intercept_float or ndarray of shape (n_targets,)
Independent term in decision function. Set to 0.0 if fit_intercept = False.
alpha_float or ndarray of shape (n_targets,)
Estimated regularization parameter, or, if alpha_per_target=True, the estimated regularization parameter for each target.
best_score_float or ndarray of shape (n_targets,)
Score of base estimator with best alpha, or, if alpha_per_target=True, a score for each target. New in version 0.23. See also
Ridge
Ridge regression.
RidgeClassifier
Ridge classifier.
RidgeClassifierCV
Ridge classifier with built-in cross validation. Examples >>> from sklearn.datasets import load_diabetes
>>> from sklearn.linear_model import RidgeCV
>>> X, y = load_diabetes(return_X_y=True)
>>> clf = RidgeCV(alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y)
>>> clf.score(X, y)
0.5166...
Methods
fit(X, y[, sample_weight]) Fit Ridge regression model with cv.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit Ridge regression model with cv. Parameters
Xndarray of shape (n_samples, n_features)
Training data. If using GCV, will be cast to float64 if necessary.
yndarray of shape (n_samples,) or (n_samples, n_targets)
Target values. Will be cast to X’s dtype if necessary.
sample_weightfloat or ndarray of shape (n_samples,), default=None
Individual weights for each sample. If given a float, every sample will have the same weight. Returns
selfobject
Notes When sample_weight is provided, the selected hyperparameter may depend on whether we use leave-one-out cross-validation (cv=None or cv=’auto’) or another form of cross-validation, because only leave-one-out cross-validation takes the sample weights into account when computing the validation score.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X) [source]
Predict using the linear model. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape (n_samples,)
Returns predicted values.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
Examples using sklearn.linear_model.RidgeCV
Combine predictors using stacking
Common pitfalls in interpretation of coefficients of linear models
Face completion with a multi-output estimators
Effect of transforming the targets in regression model | |
doc_26491 |
Fit the ARDRegression model according to the given training data and parameters. Iterative procedure to maximize the evidence Parameters
Xarray-like of shape (n_samples, n_features)
Training vector, where n_samples in the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
Target values (integers). Will be cast to X’s dtype if necessary Returns
selfreturns an instance of self. | |
doc_26492 |
Getter for the precision matrix. Returns
precision_array-like of shape (n_features, n_features)
The precision matrix associated to the current covariance object. | |
doc_26493 |
For each element, return True if there are only decimal characters in the element. Calls unicode.isdecimal element-wise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Parameters
aarray_like, unicode
Input array. Returns
outndarray, bool
Array of booleans identical in shape to a. See also unicode.isdecimal | |
doc_26494 |
Transform features using quantiles information. This method transforms the features to follow a uniform or a normal distribution. Therefore, for a given feature, this transformation tends to spread out the most frequent values. It also reduces the impact of (marginal) outliers: this is therefore a robust preprocessing scheme. The transformation is applied on each feature independently. First an estimate of the cumulative distribution function of a feature is used to map the original values to a uniform distribution. The obtained values are then mapped to the desired output distribution using the associated quantile function. Features values of new/unseen data that fall below or above the fitted range will be mapped to the bounds of the output distribution. Note that this transform is non-linear. It may distort linear correlations between variables measured at the same scale but renders variables measured at different scales more directly comparable. Read more in the User Guide. New in version 0.19. Parameters
n_quantilesint, default=1000 or n_samples
Number of quantiles to be computed. It corresponds to the number of landmarks used to discretize the cumulative distribution function. If n_quantiles is larger than the number of samples, n_quantiles is set to the number of samples as a larger number of quantiles does not give a better approximation of the cumulative distribution function estimator.
output_distribution{‘uniform’, ‘normal’}, default=’uniform’
Marginal distribution for the transformed data. The choices are ‘uniform’ (default) or ‘normal’.
ignore_implicit_zerosbool, default=False
Only applies to sparse matrices. If True, the sparse entries of the matrix are discarded to compute the quantile statistics. If False, these entries are treated as zeros.
subsampleint, default=1e5
Maximum number of samples used to estimate the quantiles for computational efficiency. Note that the subsampling procedure may differ for value-identical sparse and dense matrices.
random_stateint, RandomState instance or None, default=None
Determines random number generation for subsampling and smoothing noise. Please see subsample for more details. Pass an int for reproducible results across multiple function calls. See Glossary
copybool, default=True
Set to False to perform inplace transformation and avoid a copy (if the input is already a numpy array). Attributes
n_quantiles_int
The actual number of quantiles used to discretize the cumulative distribution function.
quantiles_ndarray of shape (n_quantiles, n_features)
The values corresponding the quantiles of reference.
references_ndarray of shape (n_quantiles, )
Quantiles of references. See also
quantile_transform
Equivalent function without the estimator API.
PowerTransformer
Perform mapping to a normal distribution using a power transform.
StandardScaler
Perform standardization that is faster, but less robust to outliers.
RobustScaler
Perform robust standardization that removes the influence of outliers but does not put outliers and inliers on the same scale. Notes NaNs are treated as missing values: disregarded in fit, and maintained in transform. For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py. Examples >>> import numpy as np
>>> from sklearn.preprocessing import QuantileTransformer
>>> rng = np.random.RandomState(0)
>>> X = np.sort(rng.normal(loc=0.5, scale=0.25, size=(25, 1)), axis=0)
>>> qt = QuantileTransformer(n_quantiles=10, random_state=0)
>>> qt.fit_transform(X)
array([...])
Methods
fit(X[, y]) Compute the quantiles used for transforming.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Back-projection to the original space.
set_params(**params) Set the parameters of this estimator.
transform(X) Feature-wise transformation of the data.
fit(X, y=None) [source]
Compute the quantiles used for transforming. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The data used to scale along the features axis. If a sparse matrix is provided, it will be converted into a sparse csc_matrix. Additionally, the sparse matrix needs to be nonnegative if ignore_implicit_zeros is False.
yNone
Ignored. Returns
selfobject
Fitted transformer.
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
inverse_transform(X) [source]
Back-projection to the original space. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The data used to scale along the features axis. If a sparse matrix is provided, it will be converted into a sparse csc_matrix. Additionally, the sparse matrix needs to be nonnegative if ignore_implicit_zeros is False. Returns
Xt{ndarray, sparse matrix} of (n_samples, n_features)
The projected data.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
transform(X) [source]
Feature-wise transformation of the data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The data used to scale along the features axis. If a sparse matrix is provided, it will be converted into a sparse csc_matrix. Additionally, the sparse matrix needs to be nonnegative if ignore_implicit_zeros is False. Returns
Xt{ndarray, sparse matrix} of shape (n_samples, n_features)
The projected data. | |
doc_26495 | See Migration guide for more details. tf.compat.v1.io.encode_proto
tf.io.encode_proto(
sizes, values, field_names, message_type,
descriptor_source='local://', name=None
)
The types of the tensors in values must match the schema for the fields specified in field_names. All the tensors in values must have a common shape prefix, batch_shape. The sizes tensor specifies repeat counts for each field. The repeat count (last dimension) of a each tensor in values must be greater than or equal to corresponding repeat count in sizes. A message_type name must be provided to give context for the field names. The actual message descriptor can be looked up either in the linked-in descriptor pool or a filename provided by the caller using the descriptor_source attribute. For the most part, the mapping between Proto field types and TensorFlow dtypes is straightforward. However, there are a few special cases: A proto field that contains a submessage or group can only be converted to DT_STRING (the serialized submessage). This is to reduce the complexity of the API. The resulting string can be used as input to another instance of the decode_proto op. TensorFlow lacks support for unsigned integers. The ops represent uint64 types as a DT_INT64 with the same twos-complement bit pattern (the obvious way). Unsigned int32 values can be represented exactly by specifying type DT_INT64, or using twos-complement if the caller specifies DT_INT32 in the output_types attribute. The descriptor_source attribute selects the source of protocol descriptors to consult when looking up message_type. This may be: An empty string or "local://", in which case protocol descriptors are created for C++ (not Python) proto definitions linked to the binary. A file, in which case protocol descriptors are created from the file, which is expected to contain a FileDescriptorSet serialized as a string. NOTE: You can build a descriptor_source file using the --descriptor_set_out and --include_imports options to the protocol compiler protoc. A "bytes://", in which protocol descriptors are created from <bytes>, which is expected to be a FileDescriptorSet serialized as a string.
Args
sizes A Tensor of type int32. Tensor of int32 with shape [batch_shape, len(field_names)].
values A list of Tensor objects. List of tensors containing values for the corresponding field.
field_names A list of strings. List of strings containing proto field names.
message_type A string. Name of the proto message type to decode.
descriptor_source An optional string. Defaults to "local://".
name A name for the operation (optional).
Returns A Tensor of type string. | |
doc_26496 |
Alias for get_linestyle. | |
doc_26497 | The strftime() format to use when parsing the day. By default, this is '%d'. | |
doc_26498 | Module shlex
Support for creating Unix shell-like mini-languages which can be used as an alternate format for application configuration files.
Module json
The json module implements a subset of JavaScript syntax which can also be used for this purpose. Quick Start Let’s take a very basic configuration file that looks like this: [DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
The structure of INI files is described in the following section. Essentially, the file consists of sections, each of which contains keys with values. configparser classes can read and write such files. Let’s start by creating the above configuration file programmatically. >>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
... 'Compression': 'yes',
... 'CompressionLevel': '9'}
>>> config['bitbucket.org'] = {}
>>> config['bitbucket.org']['User'] = 'hg'
>>> config['topsecret.server.com'] = {}
>>> topsecret = config['topsecret.server.com']
>>> topsecret['Port'] = '50022' # mutates the parser
>>> topsecret['ForwardX11'] = 'no' # same here
>>> config['DEFAULT']['ForwardX11'] = 'yes'
>>> with open('example.ini', 'w') as configfile:
... config.write(configfile)
...
As you can see, we can treat a config parser much like a dictionary. There are differences, outlined later, but the behavior is very close to what you would expect from a dictionary. Now that we have created and saved a configuration file, let’s read it back and explore the data it holds. >>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']:
... print(key)
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
As we can see above, the API is pretty straightforward. The only bit of magic involves the DEFAULT section which provides default values for all other sections 1. Note also that keys in sections are case-insensitive and stored in lowercase 1. Supported Datatypes Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own: >>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
Since this task is so common, config parsers provide a range of handy getter methods to handle integers, floats and booleans. The last one is the most interesting because simply passing the value to bool() would do no good since bool('False') is still True. This is why config parsers also provide getboolean(). This method is case-insensitive and recognizes Boolean values from 'yes'/'no', 'on'/'off', 'true'/'false' and '1'/'0' 1. For example: >>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True
Apart from getboolean(), config parsers also provide equivalent getint() and getfloat() methods. You can register your own converters and customize the provided ones. 1 Fallback Values As with a dictionary, you can use a section’s get() method to provide fallback values: >>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'
Please note that default values have precedence over fallback values. For instance, in our example the 'CompressionLevel' key was specified only in the 'DEFAULT' section. If we try to get it from the section 'topsecret.server.com', we will always get the default, even if we specify a fallback: >>> topsecret.get('CompressionLevel', '3')
'9'
One more thing to be aware of is that the parser-level get() method provides a custom, more complex interface, maintained for backwards compatibility. When using this method, a fallback value can be provided via the fallback keyword-only argument: >>> config.get('bitbucket.org', 'monster',
... fallback='No such things as monsters')
'No such things as monsters'
The same fallback argument can be used with the getint(), getfloat() and getboolean() methods, for example: >>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False
Supported INI File Structure A configuration file consists of sections, each led by a [section] header, followed by key/value entries separated by a specific string (= or : by default 1). By default, section names are case sensitive but keys are not 1. Leading and trailing whitespace is removed from keys and values. Values can be omitted, in which case the key/value delimiter may also be left out. Values can also span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser’s mode, blank lines may be treated as parts of multiline values or ignored. Configuration files may include comments, prefixed by specific characters (# and ; by default 1). Comments may appear on their own on an otherwise empty line, possibly indented. 1 For example: [Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values
[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true
[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
I sleep all night and I work all day
[No Values]
key_without_value
empty string value here =
[You can use comments]
# like this
; or this
# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.
[Sections Can Be Indented]
can_values_be_as_well = True
does_that_mean_anything_special = False
purpose = formatting for readability
multiline_values = are
handled just fine as
long as they are indented
deeper than the first line
of a value
# Did I mention we can indent comments, too?
Interpolation of values On top of the core functionality, ConfigParser supports interpolation. This means values can be preprocessed before returning them from get() calls.
class configparser.BasicInterpolation
The default implementation used by ConfigParser. It enables values to contain format strings which refer to other values in the same section, or values in the special default section 1. Additional default values can be provided on initialization. For example: [Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures
[Escape]
gain: 80%% # use a %% to escape the % sign (% is the only character that needs to be escaped)
In the example above, ConfigParser with interpolation set to BasicInterpolation() would resolve %(home_dir)s to the value of home_dir (/Users in this case). %(my_dir)s in effect would resolve to /Users/lumberjack. All interpolations are done on demand so keys used in the chain of references do not have to be specified in any specific order in the configuration file. With interpolation set to None, the parser would simply return %(my_dir)s/Pictures as the value of my_pictures and %(home_dir)s/lumberjack as the value of my_dir.
class configparser.ExtendedInterpolation
An alternative handler for interpolation which implements a more advanced syntax, used for instance in zc.buildout. Extended interpolation is using ${section:option} to denote a value from a foreign section. Interpolation can span multiple levels. For convenience, if the section: part is omitted, interpolation defaults to the current section (and possibly the default values from the special section). For example, the configuration specified above with basic interpolation, would look like this with extended interpolation: [Paths]
home_dir: /Users
my_dir: ${home_dir}/lumberjack
my_pictures: ${my_dir}/Pictures
[Escape]
cost: $$80 # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)
Values from other sections can be fetched as well: [Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local
[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/
[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Mapping Protocol Access New in version 3.2. Mapping protocol access is a generic name for functionality that enables using custom objects as if they were dictionaries. In case of configparser, the mapping interface implementation is using the parser['section']['option'] notation. parser['section'] in particular returns a proxy for the section’s data in the parser. This means that the values are not copied but they are taken from the original parser on demand. What’s even more important is that when values are changed on a section proxy, they are actually mutated in the original parser. configparser objects behave as close to actual dictionaries as possible. The mapping interface is complete and adheres to the MutableMapping ABC. However, there are a few differences that should be taken into account:
By default, all keys in sections are accessible in a case-insensitive manner 1. E.g. for option in parser["section"] yields only optionxform’ed option key names. This means lowercased keys by default. At the same time, for a section that holds the key 'a', both expressions return True: "a" in parser["section"]
"A" in parser["section"]
All sections include DEFAULTSECT values as well which means that .clear() on a section may not leave the section visibly empty. This is because default values cannot be deleted from the section (because technically they are not there). If they are overridden in the section, deleting causes the default value to be visible again. Trying to delete a default value causes a KeyError.
DEFAULTSECT cannot be removed from the parser: trying to delete it raises ValueError,
parser.clear() leaves it intact,
parser.popitem() never returns it.
parser.get(section, option, **kwargs) - the second argument is not a fallback value. Note however that the section-level get() methods are compatible both with the mapping protocol and the classic configparser API.
parser.items() is compatible with the mapping protocol (returns a list of section_name, section_proxy pairs including the DEFAULTSECT). However, this method can also be invoked with arguments: parser.items(section, raw,
vars). The latter call returns a list of option, value pairs for a specified section, with all interpolations expanded (unless raw=True is provided). The mapping protocol is implemented on top of the existing legacy API so that subclasses overriding the original interface still should have mappings working as expected. Customizing Parser Behaviour There are nearly as many INI format variants as there are applications using it. configparser goes a long way to provide support for the largest sensible set of INI styles available. The default functionality is mainly dictated by historical background and it’s very likely that you will want to customize some of the features. The most common way to change the way a specific config parser works is to use the __init__() options:
defaults, default value: None This option accepts a dictionary of key-value pairs which will be initially put in the DEFAULT section. This makes for an elegant way to support concise configuration files that don’t specify values which are the same as the documented default. Hint: if you want to specify default values for a specific section, use read_dict() before you read the actual file.
dict_type, default value: dict This option has a major impact on how the mapping protocol will behave and how the written configuration files look. With the standard dictionary, every section is stored in the order they were added to the parser. Same goes for options within sections. An alternative dictionary type can be used for example to sort sections and options on write-back. Please note: there are ways to add a set of key-value pairs in a single operation. When you use a regular dictionary in those operations, the order of the keys will be ordered. For example: >>> parser = configparser.ConfigParser()
>>> parser.read_dict({'section1': {'key1': 'value1',
... 'key2': 'value2',
... 'key3': 'value3'},
... 'section2': {'keyA': 'valueA',
... 'keyB': 'valueB',
... 'keyC': 'valueC'},
... 'section3': {'foo': 'x',
... 'bar': 'y',
... 'baz': 'z'}
... })
>>> parser.sections()
['section1', 'section2', 'section3']
>>> [option for option in parser['section3']]
['foo', 'bar', 'baz']
allow_no_value, default value: False Some configuration files are known to include settings without values, but which otherwise conform to the syntax supported by configparser. The allow_no_value parameter to the constructor can be used to indicate that such values should be accepted: >>> import configparser
>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-external-locking
... old_passwords = 1
... skip-bdb
... # we don't need ACID today
... skip-innodb
... """
>>> config = configparser.ConfigParser(allow_no_value=True)
>>> config.read_string(sample_config)
>>> # Settings with values are treated as before:
>>> config["mysqld"]["user"]
'mysql'
>>> # Settings without values provide None:
>>> config["mysqld"]["skip-bdb"]
>>> # Settings which aren't specified still raise an error:
>>> config["mysqld"]["does-not-exist"]
Traceback (most recent call last):
...
KeyError: 'does-not-exist'
delimiters, default value: ('=', ':') Delimiters are substrings that delimit keys from values within a section. The first occurrence of a delimiting substring on a line is considered a delimiter. This means values (but not keys) can contain the delimiters. See also the space_around_delimiters argument to ConfigParser.write().
comment_prefixes, default value: ('#', ';')
inline_comment_prefixes, default value: None Comment prefixes are strings that indicate the start of a valid comment within a config file. comment_prefixes are used only on otherwise empty lines (optionally indented) whereas inline_comment_prefixes can be used after every valid value (e.g. section names, options and empty lines as well). By default inline comments are disabled and '#' and ';' are used as prefixes for whole line comments. Changed in version 3.2: In previous versions of configparser behaviour matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',). Please note that config parsers don’t support escaping of comment prefixes so using inline_comment_prefixes may prevent users from specifying option values with characters used as comment prefixes. When in doubt, avoid setting inline_comment_prefixes. In any circumstances, the only way of storing comment prefix characters at the beginning of a line in multiline values is to interpolate the prefix, for example: >>> from configparser import ConfigParser, ExtendedInterpolation
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> # the default BasicInterpolation could be used as well
>>> parser.read_string("""
... [DEFAULT]
... hash = #
...
... [hashes]
... shebang =
... ${hash}!/usr/bin/env python
... ${hash} -*- coding: utf-8 -*-
...
... extensions =
... enabled_extension
... another_extension
... #disabled_by_comment
... yet_another_extension
...
... interpolation not necessary = if # is not at line start
... even in multiline values = line #1
... line #2
... line #3
... """)
>>> print(parser['hashes']['shebang'])
#!/usr/bin/env python
# -*- coding: utf-8 -*-
>>> print(parser['hashes']['extensions'])
enabled_extension
another_extension
yet_another_extension
>>> print(parser['hashes']['interpolation not necessary'])
if # is not at line start
>>> print(parser['hashes']['even in multiline values'])
line #1
line #2
line #3
strict, default value: True When set to True, the parser will not allow for any section or option duplicates while reading from a single source (using read_file(), read_string() or read_dict()). It is recommended to use strict parsers in new applications. Changed in version 3.2: In previous versions of configparser behaviour matched strict=False.
empty_lines_in_values, default value: True In config parsers, values can span multiple lines as long as they are indented more than the key that holds them. By default parsers also let empty lines to be parts of values. At the same time, keys can be arbitrarily indented themselves to improve readability. In consequence, when configuration files get big and complex, it is easy for the user to lose track of the file structure. Take for instance: [Section]
key = multiline
value with a gotcha
this = is still a part of the multiline value of 'key'
This can be especially problematic for the user to see if she’s using a proportional font to edit the file. That is why when your application does not need values with empty lines, you should consider disallowing them. This will make empty lines split keys every time. In the example above, it would produce two keys, key and this.
default_section, default value: configparser.DEFAULTSECT (that is: "DEFAULT") The convention of allowing a special section of default values for other sections or interpolation purposes is a powerful concept of this library, letting users create complex declarative configurations. This section is normally called "DEFAULT" but this can be customized to point to any other valid section name. Some typical values include: "general" or "common". The name provided is used for recognizing default sections when reading from any source and is used when writing configuration back to a file. Its current value can be retrieved using the parser_instance.default_section attribute and may be modified at runtime (i.e. to convert files from one format to another).
interpolation, default value: configparser.BasicInterpolation Interpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section. RawConfigParser has a default value of None.
converters, default value: not set Config parsers provide option value getters that perform type conversion. By default getint(), getfloat(), and getboolean() are implemented. Should other getters be desirable, users may define them in a subclass or pass a dictionary where each key is a name of the converter and each value is a callable implementing said conversion. For instance, passing {'decimal': decimal.Decimal} would add getdecimal() on both the parser object and all section proxies. In other words, it will be possible to write both parser_instance.getdecimal('section', 'key', fallback=0) and parser_instance['section'].getdecimal('key', 0). If the converter needs to access the state of the parser, it can be implemented as a method on a config parser subclass. If the name of this method starts with get, it will be available on all section proxies, in the dict-compatible form (see the getdecimal() example above). More advanced customization may be achieved by overriding default values of these parser attributes. The defaults are defined on the classes, so they may be overridden by subclasses or by attribute assignment.
ConfigParser.BOOLEAN_STATES
By default when using getboolean(), config parsers consider the following values True: '1', 'yes', 'true', 'on' and the following values False: '0', 'no', 'false', 'off'. You can override this by specifying a custom dictionary of strings and their Boolean outcomes. For example: >>> custom = configparser.ConfigParser()
>>> custom['section1'] = {'funky': 'nope'}
>>> custom['section1'].getboolean('funky')
Traceback (most recent call last):
...
ValueError: Not a boolean: nope
>>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
>>> custom['section1'].getboolean('funky')
False
Other typical Boolean pairs include accept/reject or enabled/disabled.
ConfigParser.optionxform(option)
This method transforms option names on every read, get, or set operation. The default converts the name to lowercase. This also means that when a configuration file gets written, all keys will be lowercase. Override this method if that’s unsuitable. For example: >>> config = """
... [Section1]
... Key = Value
...
... [Section2]
... AnotherKey = Value
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> list(typical['Section1'].keys())
['key']
>>> list(typical['Section2'].keys())
['anotherkey']
>>> custom = configparser.RawConfigParser()
>>> custom.optionxform = lambda option: option
>>> custom.read_string(config)
>>> list(custom['Section1'].keys())
['Key']
>>> list(custom['Section2'].keys())
['AnotherKey']
Note The optionxform function transforms option names to a canonical form. This should be an idempotent function: if the name is already in canonical form, it should be returned unchanged.
ConfigParser.SECTCRE
A compiled regular expression used to parse section headers. The default matches [section] to the name "section". Whitespace is considered part of the section name, thus [ larch ] will be read as a section of name " larch ". Override this attribute if that’s unsuitable. For example: >>> import re
>>> config = """
... [Section 1]
... option = value
...
... [ Section 2 ]
... another = val
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> typical.sections()
['Section 1', ' Section 2 ']
>>> custom = configparser.ConfigParser()
>>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
>>> custom.read_string(config)
>>> custom.sections()
['Section 1', 'Section 2']
Note While ConfigParser objects also use an OPTCRE attribute for recognizing option lines, it’s not recommended to override it because that would interfere with constructor options allow_no_value and delimiters.
Legacy API Examples Mainly because of backwards compatibility concerns, configparser provides also a legacy API with explicit get/set methods. While there are valid use cases for the methods outlined below, mapping protocol access is preferred for new projects. The legacy API is at times more advanced, low-level and downright counterintuitive. An example of writing to a configuration file: import configparser
config = configparser.RawConfigParser()
# Please note that using RawConfigParser's set functions, you can assign
# non-string values to keys internally, but will receive an error when
# attempting to write to a file or when you get it in non-raw mode. Setting
# values using the mapping protocol or ConfigParser's set() does not allow
# such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
config.write(configfile)
An example of reading the configuration file again: import configparser
config = configparser.RawConfigParser()
config.read('example.cfg')
# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print(a_float + an_int)
# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
print(config.get('Section1', 'foo'))
To get interpolation, use ConfigParser: import configparser
cfg = configparser.ConfigParser()
cfg.read('example.cfg')
# Set the optional *raw* argument of get() to True if you wish to disable
# interpolation in a single get operation.
print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
# The optional *vars* argument is a dict with members that will take
# precedence in interpolation.
print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
'baz': 'evil'}))
# The optional *fallback* argument can be used to provide a fallback value
print(cfg.get('Section1', 'foo'))
# -> "Python is fun!"
print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
# -> "Python is fun!"
print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
# -> "No such things as monsters."
# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
# but we can also use:
print(cfg.get('Section1', 'monster', fallback=None))
# -> None
Default values are available in both types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere. import configparser
# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')
print(config.get('Section1', 'foo')) # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo')) # -> "Life is hard!"
ConfigParser Objects
class configparser.ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})
The main configuration parser. When defaults is given, it is initialized into the dictionary of intrinsic defaults. When dict_type is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values. When delimiters is given, it is used as the set of substrings that divide keys from values. When comment_prefixes is given, it will be used as the set of substrings that prefix comments in otherwise empty lines. Comments can be indented. When inline_comment_prefixes is given, it will be used as the set of substrings that prefix comments in non-empty lines. When strict is True (the default), the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary), raising DuplicateSectionError or DuplicateOptionError. When empty_lines_in_values is False (default: True), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When allow_no_value is True (default: False), options without values are accepted; the value held for these is None and they are serialized without the trailing delimiter. When default_section is given, it specifies the name for the special section holding default values for other sections and interpolation purposes (normally named "DEFAULT"). This value can be retrieved and changed on runtime using the default_section instance attribute. Interpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section. All option names used in interpolation will be passed through the optionxform() method just like any other option name reference. For example, using the default implementation of optionxform() (which converts option names to lower case), the values foo %(bar)s and foo
%(BAR)s are equivalent. When converters is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its own corresponding get*() method on the parser object and section proxies. Changed in version 3.1: The default dict_type is collections.OrderedDict. Changed in version 3.2: allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section and interpolation were added. Changed in version 3.5: The converters argument was added. Changed in version 3.7: The defaults argument is read with read_dict(), providing consistent behavior across the parser: non-string keys and values are implicitly converted to strings. Changed in version 3.8: The default dict_type is dict, since it now preserves insertion order.
defaults()
Return a dictionary containing the instance-wide defaults.
sections()
Return a list of the sections available; the default section is not included in the list.
add_section(section)
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. The name of the section must be a string; if not, TypeError is raised. Changed in version 3.2: Non-string section names raise TypeError.
has_section(section)
Indicates whether the named section is present in the configuration. The default section is not acknowledged.
options(section)
Return a list of options available in the specified section.
has_option(section, option)
If the given section exists, and contains the given option, return True; otherwise return False. If the specified section is None or an empty string, DEFAULT is assumed.
read(filenames, encoding=None)
Attempt to read and parse an iterable of filenames, returning a list of filenames which were successfully parsed. If filenames is a string, a bytes object or a path-like object, it is treated as a single filename. If a file named in filenames cannot be opened, that file will be ignored. This is designed so that you can specify an iterable of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the iterable will be read. If none of the named files exist, the ConfigParser instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using read_file() before calling read() for any optional files: import configparser, os
config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
encoding='cp1250')
New in version 3.2: The encoding parameter. Previously, all files were read using the default encoding for open(). New in version 3.6.1: The filenames parameter accepts a path-like object. New in version 3.7: The filenames parameter accepts a bytes object.
read_file(f, source=None)
Read and parse configuration data from f which must be an iterable yielding Unicode strings (for example files opened in text mode). Optional argument source specifies the name of the file being read. If not given and f has a name attribute, that is used for source; the default is '<???>'. New in version 3.2: Replaces readfp().
read_string(string, source='<string>')
Parse configuration data from a string. Optional argument source specifies a context-specific name of the string passed. If not given, '<string>' is used. This should commonly be a filesystem path or a URL. New in version 3.2.
read_dict(dictionary, source='<dict>')
Load configuration from any object that provides a dict-like items() method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. Optional argument source specifies a context-specific name of the dictionary passed. If not given, <dict> is used. This method can be used to copy state between parsers. New in version 3.2.
get(section, option, *, raw=False, vars=None[, fallback])
Get an option value for the named section. If vars is provided, it must be a dictionary. The option is looked up in vars (if provided), section, and in DEFAULTSECT in that order. If the key is not found and fallback is provided, it is used as a fallback value. None can be provided as a fallback value. All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option. Changed in version 3.2: Arguments raw, vars and fallback are keyword only to protect users from trying to use the third argument as the fallback fallback (especially when using the mapping protocol).
getint(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to an integer. See get() for explanation of raw, vars and fallback.
getfloat(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to a floating point number. See get() for explanation of raw, vars and fallback.
getboolean(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError. See get() for explanation of raw, vars and fallback.
items(raw=False, vars=None)
items(section, raw=False, vars=None)
When section is not given, return a list of section_name, section_proxy pairs, including DEFAULTSECT. Otherwise, return a list of name, value pairs for the options in the given section. Optional arguments have the same meaning as for the get() method. Changed in version 3.8: Items present in vars no longer appear in the result. The previous behaviour mixed actual parser options with variables provided for interpolation.
set(section, option, value)
If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. option and value must be strings; if not, TypeError is raised.
write(fileobject, space_around_delimiters=True)
Write a representation of the configuration to the specified file object, which must be opened in text mode (accepting strings). This representation can be parsed by a future read() call. If space_around_delimiters is true, delimiters between keys and values are surrounded by spaces.
remove_option(section, option)
Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False.
remove_section(section)
Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False.
optionxform(option)
Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to str, for example, would make option names case sensitive: cfgparser = ConfigParser()
cfgparser.optionxform = str
Note that when reading configuration files, whitespace around the option names is stripped before optionxform() is called.
readfp(fp, filename=None)
Deprecated since version 3.2: Use read_file() instead. Changed in version 3.2: readfp() now iterates on fp instead of calling fp.readline(). For existing code calling readfp() with arguments which don’t support iteration, the following generator may be used as a wrapper around the file-like object: def readline_generator(fp):
line = fp.readline()
while line:
yield line
line = fp.readline()
Instead of parser.readfp(fp) use parser.read_file(readline_generator(fp)).
configparser.MAX_INTERPOLATION_DEPTH
The maximum depth for recursive interpolation for get() when the raw parameter is false. This is relevant only when the default interpolation is used.
RawConfigParser Objects
class configparser.RawConfigParser(defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT[, interpolation])
Legacy variant of the ConfigParser. It has interpolation disabled by default and allows for non-string section names, option names, and values via its unsafe add_section and set methods, as well as the legacy defaults= keyword argument handling. Changed in version 3.8: The default dict_type is dict, since it now preserves insertion order. Note Consider using ConfigParser instead which checks types of the values to be stored internally. If you don’t want interpolation, you can use ConfigParser(interpolation=None).
add_section(section)
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. Type of section is not checked which lets users create non-string named sections. This behaviour is unsupported and may cause internal errors.
set(section, option, value)
If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. While it is possible to use RawConfigParser (or ConfigParser with raw parameters set to true) for internal storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values. This method lets users assign non-string values to keys internally. This behaviour is unsupported and will cause errors when attempting to write to a file or get it in non-raw mode. Use the mapping protocol API which does not allow such assignments to take place.
Exceptions
exception configparser.Error
Base class for all other configparser exceptions.
exception configparser.NoSectionError
Exception raised when a specified section is not found.
exception configparser.DuplicateSectionError
Exception raised if add_section() is called with the name of a section that is already present or in strict parsers when a section if found more than once in a single input file, string or dictionary. New in version 3.2: Optional source and lineno attributes and arguments to __init__() were added.
exception configparser.DuplicateOptionError
Exception raised by strict parsers if a single option appears twice during reading from a single file, string or dictionary. This catches misspellings and case sensitivity-related errors, e.g. a dictionary may have two keys representing the same case-insensitive configuration key.
exception configparser.NoOptionError
Exception raised when a specified option is not found in the specified section.
exception configparser.InterpolationError
Base class for exceptions raised when problems occur performing string interpolation.
exception configparser.InterpolationDepthError
Exception raised when string interpolation cannot be completed because the number of iterations exceeds MAX_INTERPOLATION_DEPTH. Subclass of InterpolationError.
exception configparser.InterpolationMissingOptionError
Exception raised when an option referenced from a value does not exist. Subclass of InterpolationError.
exception configparser.InterpolationSyntaxError
Exception raised when the source text into which substitutions are made does not conform to the required syntax. Subclass of InterpolationError.
exception configparser.MissingSectionHeaderError
Exception raised when attempting to parse a file which has no section headers.
exception configparser.ParsingError
Exception raised when errors occur attempting to parse a file. Changed in version 3.2: The filename attribute and __init__() argument were renamed to source for consistency.
Footnotes
1(1,2,3,4,5,6,7,8,9,10)
Config parsers allow for heavy customization. If you are interested in changing the behaviour outlined by the footnote reference, consult the Customizing Parser Behaviour section. | |
doc_26499 | class collections.abc.ItemsView
class collections.abc.KeysView
class collections.abc.ValuesView
ABCs for mapping, items, keys, and values views. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.