_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_2600 | See Migration guide for more details. tf.compat.v1.raw_ops.MatrixLogarithm
tf.raw_ops.MatrixLogarithm(
input, name=None
)
\(log(exp(A)) = A\) This op is only defined for complex matrices. If A is positive-definite and real, then casting to a complex matrix, taking the logarithm and casting back to a real matrix will give the correct result. This function computes the matrix logarithm using the Schur-Parlett algorithm. Details of the algorithm can be found in Section 11.6.2 of: Nicholas J. Higham, Functions of Matrices: Theory and Computation, SIAM 2008. ISBN 978-0-898716-46-7. The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The output is a tensor of the same shape as the input containing the exponential for all input submatrices [..., :, :].
Args
input A Tensor. Must be one of the following types: complex64, complex128. Shape is [..., M, M].
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_2601 |
Draw a collection of paths selecting drawing properties from the lists facecolors, edgecolors, linewidths, linestyles and antialiaseds. offsets is a list of offsets to apply to each of the paths. The offsets in offsets are first transformed by offsetTrans before being applied. offset_position is unused now, but the argument is kept for backwards compatibility. This provides a fallback implementation of draw_path_collection() that makes multiple calls to draw_path(). Some backends may want to override this in order to render each set of path data only once, and then reference that path multiple times with the different offsets, colors, styles etc. The generator methods _iter_collection_raw_paths() and _iter_collection() are provided to help with (and standardize) the implementation across backends. It is highly recommended to use those generators, so that changes to the behavior of draw_path_collection() can be made globally. | |
doc_2602 | tf.compat.v1.train.ChiefSessionCreator(
scaffold=None, master='', config=None, checkpoint_dir=None,
checkpoint_filename_with_path=None
)
Args
scaffold A Scaffold used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph.
master String representation of the TensorFlow master to use.
config ConfigProto proto used to configure the session.
checkpoint_dir A string. Optional path to a directory where to restore variables.
checkpoint_filename_with_path Full file name path to the checkpoint file. Methods create_session View source
create_session() | |
doc_2603 | Add a new attribute node to the element, replacing an existing attribute if necessary if the name attribute matches. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use, InuseAttributeErr will be raised. | |
doc_2604 |
Return the list of minor Ticks. | |
doc_2605 |
Bases: matplotlib.ticker.Formatter Use a user-defined function for formatting. The function should take in two inputs (a tick value x and a position pos), and return a string containing the corresponding tick label. get_offset()[source]
set_offset_string(ofs)[source] | |
doc_2606 |
Computes the position of the points in the embedding space. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples, n_samples)
Input data. If dissimilarity=='precomputed', the input should be the dissimilarity matrix.
yIgnored
initndarray of shape (n_samples,), default=None
Starting configuration of the embedding to initialize the SMACOF algorithm. By default, the algorithm is initialized with a randomly chosen array. | |
doc_2607 | The URL to redirect to when the form is successfully processed. success_url may contain dictionary string formatting, which will be interpolated against the object’s field attributes. For example, you could use success_url="/polls/{slug}/" to redirect to a URL composed out of the slug field on a model. | |
doc_2608 |
Return a sequence of equally spaced Matplotlib dates. The dates start at dstart and reach up to, but not including dend. They are spaced by delta. Parameters
dstart, denddatetime
The date limits.
deltadatetime.timedelta
Spacing of the dates. Returns
numpy.array
A list floats representing Matplotlib dates. | |
doc_2609 |
Alias for set_markersize. | |
doc_2610 |
Predict probability for each possible outcome. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data. Returns
yndarray of shape (n_samples, n_features)
Array with prediction probabilities. | |
doc_2611 | tf.experimental.numpy.expm1(
x
)
Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.expm1. | |
doc_2612 |
An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array. Parameters
(for the __new__ method; see Notes below)
shapetuple of ints
Shape of created array.
dtypedata-type, optional
Any object that can be interpreted as a numpy data type.
bufferobject exposing buffer interface, optional
Used to fill the array with data.
offsetint, optional
Offset of array data in buffer.
stridestuple of ints, optional
Strides of data in memory.
order{‘C’, ‘F’}, optional
Row-major (C-style) or column-major (Fortran-style) order. See also array
Construct an array. zeros
Create an array, each element of which is zero. empty
Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”). dtype
Create a data-type. numpy.typing.NDArray
An ndarray alias generic w.r.t. its dtype.type. Notes There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted. No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
[ nan, 2.5e-323]])
Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]),
... offset=np.int_().itemsize,
... dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])
Attributes
Tndarray
Transpose of the array.
databuffer
The array’s elements, in memory.
dtypedtype object
Describes the format of the elements in the array.
flagsdict
Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
flatnumpy.flatiter object
Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO).
imagndarray
Imaginary part of the array.
realndarray
Real part of the array.
sizeint
Number of elements in the array.
itemsizeint
The memory use of each array element in bytes.
nbytesint
The total number of bytes required to store the array data, i.e., itemsize * size.
ndimint
The array’s number of dimensions.
shapetuple of ints
Shape of the array.
stridestuple of ints
The step-size required to move from one element to the next in memory. For example, a contiguous (3, 4) array of type int16 in C-order has strides (8, 2). This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (2 * 4).
ctypesctypes object
Class containing properties of the array needed for interaction with ctypes.
basendarray
If the array is a view into another array, that array is its base (unless that array is also a view). The base array is where the array data is actually stored. | |
doc_2613 | sklearn.utils.validation.check_symmetric(array, *, tol=1e-10, raise_warning=True, raise_exception=False) [source]
Make sure that array is 2D, square and symmetric. If the array is not symmetric, then a symmetrized version is returned. Optionally, a warning or exception is raised if the matrix is not symmetric. Parameters
array{ndarray, sparse matrix}
Input object to check / convert. Must be two-dimensional and square, otherwise a ValueError will be raised.
tolfloat, default=1e-10
Absolute tolerance for equivalence of arrays. Default = 1E-10.
raise_warningbool, default=True
If True then raise a warning if conversion is required.
raise_exceptionbool, default=False
If True then raise an exception if array is not symmetric. Returns
array_sym{ndarray, sparse matrix}
Symmetrized version of the input array, i.e. the average of array and array.transpose(). If sparse, then duplicate entries are first summed and zeros are eliminated. | |
doc_2614 | Indicates the format that the module uses. Version 0 is the historical format, version 1 shares interned strings and version 2 uses a binary format for floating point numbers. Version 3 adds support for object instancing and recursion. The current version is 4. | |
doc_2615 |
Process an button-2 event (end blocking input). Parameters
eventMouseEvent | |
doc_2616 |
Bases: matplotlib.widgets.Widget Widget connected to a single Axes. To guarantee that the widget remains responsive and not garbage-collected, a reference to the object should be maintained by the user. This is necessary because the callback registry maintains only weak-refs to the functions, which are member functions of the widget. If there are no references to the widget object it may be garbage collected which will disconnect the callbacks. Attributes
axAxes
The parent axes for the widget.
canvasFigureCanvasBase
The parent figure canvas for the widget.
activebool
Is the widget active? propertycids[source]
connect_event(event, callback)[source]
Connect a callback function with an event. This should be used in lieu of figure.canvas.mpl_connect since this function stores callback ids for later clean up.
disconnect_events()[source]
Disconnect all events created by this widget. | |
doc_2617 | Name of the ndbm implementation library used. | |
doc_2618 |
Construct a Bbox by padding this one on all four sides by p. | |
doc_2619 |
Abstract base class of all scalar types without predefined length. The actual size of these types depends on the specific np.dtype instantiation. | |
doc_2620 |
Context-manager that sets gradient calculation to on or off. set_grad_enabled will enable or disable grads based on its argument mode. It can be used as a context-manager or as a function. This context manager is thread local; it will not affect computation in other threads. Parameters
mode (bool) – Flag whether to enable grad (True), or disable (False). This can be used to conditionally enable gradients. Example: >>> x = torch.tensor([1], requires_grad=True)
>>> is_train = False
>>> with torch.set_grad_enabled(is_train):
... y = x * 2
>>> y.requires_grad
False
>>> torch.set_grad_enabled(True)
>>> y = x * 2
>>> y.requires_grad
True
>>> torch.set_grad_enabled(False)
>>> y = x * 2
>>> y.requires_grad
False | |
doc_2621 | Is raised when a compression method is not supported or when the data cannot be decoded properly. | |
doc_2622 | See Migration guide for more details. tf.compat.v1.keras.layers.SpatialDropout1D
tf.keras.layers.SpatialDropout1D(
rate, **kwargs
)
This version performs the same function as Dropout, however, it drops entire 1D feature maps instead of individual elements. If adjacent frames within feature maps are strongly correlated (as is normally the case in early convolution layers) then regular dropout will not regularize the activations and will otherwise just result in an effective learning rate decrease. In this case, SpatialDropout1D will help promote independence between feature maps and should be used instead.
Arguments
rate Float between 0 and 1. Fraction of the input units to drop. Call arguments:
inputs: A 3D tensor.
training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). Input shape: 3D tensor with shape: (samples, timesteps, channels) Output shape: Same as input. References: Efficient Object Localization Using Convolutional Networks | |
doc_2623 | tf.initializers.VarianceScaling, tf.initializers.variance_scaling, tf.keras.initializers.variance_scaling
tf.keras.initializers.VarianceScaling(
scale=1.0, mode='fan_in', distribution='truncated_normal',
seed=None
)
Also available via the shortcut function tf.keras.initializers.variance_scaling. With distribution="truncated_normal" or "untruncated_normal", samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) stddev = sqrt(scale / n), where n is: number of input units in the weight tensor, if mode="fan_in"
number of output units, if mode="fan_out"
average of the numbers of input and output units, if mode="fan_avg"
With distribution="uniform", samples are drawn from a uniform distribution within [-limit, limit], where limit = sqrt(3 * scale / n). Examples:
# Standalone usage:
initializer = tf.keras.initializers.VarianceScaling(
scale=0.1, mode='fan_in', distribution='uniform')
values = initializer(shape=(2, 2))
# Usage in a Keras layer:
initializer = tf.keras.initializers.VarianceScaling(
scale=0.1, mode='fan_in', distribution='uniform')
layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)
Args
scale Scaling factor (positive float).
mode One of "fan_in", "fan_out", "fan_avg".
distribution Random distribution to use. One of "truncated_normal", "untruncated_normal" and "uniform".
seed A Python integer. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. Methods from_config View source
@classmethod
from_config(
config
)
Instantiates an initializer from a configuration dictionary. Example: initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
Args
config A Python dictionary. It will typically be the output of get_config.
Returns An Initializer instance.
get_config View source
get_config()
Returns the configuration of the initializer as a JSON-serializable dict.
Returns A JSON-serializable Python dict.
__call__ View source
__call__(
shape, dtype=None, **kwargs
)
Returns a tensor object initialized as specified by the initializer.
Args
shape Shape of the tensor.
dtype Optional dtype of the tensor. Only floating point types are supported. If not specified, tf.keras.backend.floatx() is used, which default to float32 unless you configured it otherwise (via tf.keras.backend.set_floatx(float_dtype))
**kwargs Additional keyword arguments. | |
doc_2624 |
The number of types. The number of numerical NumPy types - of which there are 18 total - on which the ufunc can operate. See also numpy.ufunc.types
Examples >>> np.add.ntypes
18
>>> np.multiply.ntypes
18
>>> np.power.ntypes
17
>>> np.exp.ntypes
7
>>> np.remainder.ntypes
14 | |
doc_2625 |
Place a legend on the Axes. Call signatures: legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)
The call signatures correspond to the following different ways to use this method: 1. Automatic detection of elements to be shown in the legend The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments. In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist: ax.plot([1, 2, 3], label='Inline label')
ax.legend()
or: line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
ax.legend()
Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling Axes.legend without any arguments and without setting the labels manually will result in no legend being drawn. 2. Explicitly listing the artists and labels in the legend For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively: ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
3. Explicitly listing the artists in the legend This is similar to 2, but the labels are taken from the artists' label properties. Example: line1, = ax.plot([1, 2, 3], label='label1')
line2, = ax.plot([1, 2, 3], label='label2')
ax.legend(handles=[line1, line2])
4. Labeling existing plot elements Discouraged This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up. To make a legend for all artists on an Axes, call this function with an iterable of strings, one for each legend item. For example: ax.plot([1, 2, 3])
ax.plot([5, 6, 7])
ax.legend(['First line', 'Second line'])
Parameters
handlessequence of Artist, optional
A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
labelslist of str, optional
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. Returns
Legend
Other Parameters
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures)
The location of the legend. The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure. The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure. The string 'center' places the legend at the center of the axes/figure. The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location. The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored). For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each "string" locations can also be given as a numeric value:
Location String Location Code
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend. Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called. If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure): loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used: loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncolint, default: 1
The number of columns that the legend has.
propNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.
fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.
labelcolorstr or list, default: rcParams["legend.labelcolor"] (default: 'None')
The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). Labelcolor can be set globally using rcParams["legend.labelcolor"] (default: 'None'). If None, use rcParams["text.color"] (default: 'black').
numpointsint, default: rcParams["legend.numpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a Line2D (line).
scatterpointsint, default: rcParams["legend.scatterpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot).
scatteryoffsetsiterable of floats, default: [0.375, 0.5, 0.3125]
The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5].
markerscalefloat, default: rcParams["legend.markerscale"] (default: 1.0)
The relative size of legend markers compared with the originally drawn ones.
markerfirstbool, default: True
If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.
frameonbool, default: rcParams["legend.frameon"] (default: True)
Whether the legend should be drawn on a patch (frame).
fancyboxbool, default: rcParams["legend.fancybox"] (default: True)
Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background.
shadowbool, default: rcParams["legend.shadow"] (default: False)
Whether to draw a shadow behind the legend.
framealphafloat, default: rcParams["legend.framealpha"] (default: 0.8)
The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored.
facecolor"inherit" or color, default: rcParams["legend.facecolor"] (default: 'inherit')
The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white').
edgecolor"inherit" or color, default: rcParams["legend.edgecolor"] (default: '0.8')
The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').
mode{"expand", None}
If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).
bbox_transformNone or matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used.
titlestr or None
The legend's title. Default is no title (None).
title_fontpropertiesNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend's title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current rcParams["legend.title_fontsize"] (default: None) will be used.
title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: rcParams["legend.title_fontsize"] (default: None)
The font size of the legend's title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.
borderpadfloat, default: rcParams["legend.borderpad"] (default: 0.4)
The fractional whitespace inside the legend border, in font-size units.
labelspacingfloat, default: rcParams["legend.labelspacing"] (default: 0.5)
The vertical space between the legend entries, in font-size units.
handlelengthfloat, default: rcParams["legend.handlelength"] (default: 2.0)
The length of the legend handles, in font-size units.
handleheightfloat, default: rcParams["legend.handleheight"] (default: 0.7)
The height of the legend handles, in font-size units.
handletextpadfloat, default: rcParams["legend.handletextpad"] (default: 0.8)
The pad between the legend handle and text, in font-size units.
borderaxespadfloat, default: rcParams["legend.borderaxespad"] (default: 0.5)
The pad between the axes and legend border, in font-size units.
columnspacingfloat, default: rcParams["legend.columnspacing"] (default: 2.0)
The spacing between columns, in font-size units.
handler_mapdict or None
The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map. See also Figure.legend
Notes Some artists are not supported by this function. See Legend guide for details. Examples (Source code, png, pdf)
Examples using matplotlib.axes.Axes.legend
Bar Label Demo
Stacked bar chart
Grouped bar chart with labels
Plotting categorical variables
Fill Between and Alpha
Hat graph
Customizing dashed line styles
Lines with a ticked patheffect
prop_cycle property markevery in rcParams
Scatter plots with a legend
Stackplots and streamgraphs
Stairs Demo
Contourf Hatching
Tricontour Demo
Secondary Axis
Plot a confidence ellipse of a two-dimensional dataset
Using histograms to plot a cumulative distribution
The histogram (hist) function with multiple data sets
Bar of pie
Labeling a pie and a donut
Polar Legend
Composing Custom Legends
Legend using pre-defined labels
Legend Demo
Mathtext
Rendering math equations using TeX
Parasite Axes demo
Parasite axis demo
Anatomy of a figure
Legend Picking
Patheffect Demo
TickedStroke patheffect
Plot 2D data on 3D plot
Parametric Curve
Multiple Yaxis With Spines
Group barchart with units
Simple Legend01
Simple Legend02
Basic Usage
Legend guide
Constrained Layout Guide
Tight Layout guide
Specifying Colors | |
doc_2626 | If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand. | |
doc_2627 | A data structure of functions to call to modify the keyword arguments when generating URLs, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the url_defaults() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. | |
doc_2628 |
Fill NA/NaN values using the specified method. Parameters
value:scalar, dict, Series, or DataFrame
Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). Values not in the dict/Series/DataFrame will not be filled. This value cannot be a list.
method:{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None
Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap.
axis:{0 or ‘index’, 1 or ‘columns’}
Axis along which to fill missing values.
inplace:bool, default False
If True, fill in-place. Note: this will modify any other views on this object (e.g., a no-copy slice for a column in a DataFrame).
limit:int, default None
If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None.
downcast:dict, default is None
A dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). Returns
DataFrame or None
Object with missing values filled or None if inplace=True. See also interpolate
Fill NaN values using interpolation. reindex
Conform object to new index. asfreq
Convert TimeSeries to specified frequency. Examples
>>> df = pd.DataFrame([[np.nan, 2, np.nan, 0],
... [3, 4, np.nan, 1],
... [np.nan, np.nan, np.nan, np.nan],
... [np.nan, 3, np.nan, 4]],
... columns=list("ABCD"))
>>> df
A B C D
0 NaN 2.0 NaN 0.0
1 3.0 4.0 NaN 1.0
2 NaN NaN NaN NaN
3 NaN 3.0 NaN 4.0
Replace all NaN elements with 0s.
>>> df.fillna(0)
A B C D
0 0.0 2.0 0.0 0.0
1 3.0 4.0 0.0 1.0
2 0.0 0.0 0.0 0.0
3 0.0 3.0 0.0 4.0
We can also propagate non-null values forward or backward.
>>> df.fillna(method="ffill")
A B C D
0 NaN 2.0 NaN 0.0
1 3.0 4.0 NaN 1.0
2 3.0 4.0 NaN 1.0
3 3.0 3.0 NaN 4.0
Replace all NaN elements in column ‘A’, ‘B’, ‘C’, and ‘D’, with 0, 1, 2, and 3 respectively.
>>> values = {"A": 0, "B": 1, "C": 2, "D": 3}
>>> df.fillna(value=values)
A B C D
0 0.0 2.0 2.0 0.0
1 3.0 4.0 2.0 1.0
2 0.0 1.0 2.0 3.0
3 0.0 3.0 2.0 4.0
Only replace the first NaN element.
>>> df.fillna(value=values, limit=1)
A B C D
0 0.0 2.0 2.0 0.0
1 3.0 4.0 NaN 1.0
2 NaN 1.0 NaN 3.0
3 NaN 3.0 NaN 4.0
When filling using a DataFrame, replacement happens along the same column names and same indices
>>> df2 = pd.DataFrame(np.zeros((4, 4)), columns=list("ABCE"))
>>> df.fillna(df2)
A B C D
0 0.0 2.0 0.0 0.0
1 3.0 4.0 0.0 1.0
2 0.0 0.0 0.0 NaN
3 0.0 3.0 0.0 4.0
Note that column D is not affected since it is not present in df2. | |
doc_2629 | High-resolution per-process timer from the CPU. Availability: Unix. New in version 3.3. | |
doc_2630 | See torch.nan_to_num(). | |
doc_2631 |
Return the sum of the array elements over the given axis. Refer to numpy.sum for full documentation. See also numpy.sum
equivalent function | |
doc_2632 | ABC for coroutine compatible classes. These implement the following methods, defined in Coroutine Objects: send(), throw(), and close(). Custom implementations must also implement __await__(). All Coroutine instances are also instances of Awaitable. See also the definition of coroutine. Note In CPython, generator-based coroutines (generators decorated with types.coroutine() or asyncio.coroutine()) are awaitables, even though they do not have an __await__() method. Using isinstance(gencoro, Coroutine) for them will return False. Use inspect.isawaitable() to detect them. New in version 3.5. | |
doc_2633 |
Get feature names from all transformers. Returns
feature_nameslist of strings
Names of the features produced by transform. | |
doc_2634 | __iter__()
values()
Return an iterator over representations of all messages if called as itervalues() or __iter__() or return a list of such representations if called as values(). The messages are represented as instances of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized. Note The behavior of __iter__() is unlike that of dictionaries, which iterate over keys. | |
doc_2635 |
Bases: matplotlib.backend_bases.FigureCanvasBase draw()[source]
Render the Figure. It is important that this method actually walk the artist tree even if not output is produced because this will trigger deferred work (like computing limits auto-limits and tick values) that users may want access to before saving to disk.
filetypes={'pdf': 'LaTeX compiled PGF picture', 'pgf': 'LaTeX PGF picture', 'png': 'Portable Network Graphics'}
get_default_filetype()[source]
Return the default savefig file format as specified in rcParams["savefig.format"] (default: 'png'). The returned string does not include a period. This method is overridden in backends that only support a single file type.
get_renderer()[source]
print_pdf(fname_or_fh, *, metadata=None, **kwargs)[source]
Use LaTeX to compile a pgf generated figure to pdf.
print_pgf(fname_or_fh, **kwargs)[source]
Output pgf macros for drawing the figure so it can be included and rendered in latex documents.
print_png(fname_or_fh, **kwargs)[source]
Use LaTeX to compile a pgf figure to pdf and convert it to png. | |
doc_2636 | As soon as you have more complex URL setups it’s a good idea to use rule factories to avoid repetitive tasks. Some of them are builtin, others can be added by subclassing RuleFactory and overriding get_rules.
get_rules(map)
Subclasses of RuleFactory have to override this method and return an iterable of rules. Parameters
map (werkzeug.routing.Map) – Return type
Iterable[werkzeug.routing.Rule] | |
doc_2637 |
Least squares fit to data. Return a series instance that is the least squares fit to the data y sampled at x. The domain of the returned instance can be specified and this will often result in a superior fit with less chance of ill conditioning. Parameters
xarray_like, shape (M,)
x-coordinates of the M sample points (x[i], y[i]).
yarray_like, shape (M,)
y-coordinates of the M sample points (x[i], y[i]).
degint or 1-D array_like
Degree(s) of the fitting polynomials. If deg is a single integer all terms up to and including the deg’th term are included in the fit. For NumPy versions >= 1.11.0 a list of integers specifying the degrees of the terms to include may be used instead.
domain{None, [beg, end], []}, optional
Domain to use for the returned series. If None, then a minimal domain that covers the points x is chosen. If [] the class domain is used. The default value was the class domain in NumPy 1.4 and None in later versions. The [] option was added in numpy 1.5.0.
rcondfloat, optional
Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases.
fullbool, optional
Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned.
warray_like, shape (M,), optional
Weights. If not None, the weight w[i] applies to the unsquared residual y[i] - y_hat[i] at x[i]. Ideally the weights are chosen so that the errors of the products w[i]*y[i] all have the same variance. When using inverse-variance weighting, use w[i] = 1/sigma(y[i]). The default value is None. New in version 1.5.0.
window{[beg, end]}, optional
Window to use for the returned series. The default value is the default class domain New in version 1.6.0. Returns
new_seriesseries
A series that represents the least squares fit to the data and has the domain and window specified in the call. If the coefficients for the unscaled and unshifted basis polynomials are of interest, do new_series.convert().coef.
[resid, rank, sv, rcond]list
These values are only returned if full == True resid – sum of squared residuals of the least squares fit rank – the numerical rank of the scaled Vandermonde matrix sv – singular values of the scaled Vandermonde matrix rcond – value of rcond. For more details, see linalg.lstsq. | |
doc_2638 |
Alias for set_edgecolor. | |
doc_2639 | tf.losses.Loss Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.Loss
tf.keras.losses.Loss(
reduction=losses_utils.ReductionV2.AUTO, name=None
)
To be implemented by subclasses:
call(): Contains the logic for loss calculation using y_true, y_pred. Example subclass implementation: class MeanSquaredError(Loss):
def call(self, y_true, y_pred):
y_pred = tf.convert_to_tensor_v2(y_pred)
y_true = tf.cast(y_true, y_pred.dtype)
return tf.reduce_mean(math_ops.square(y_pred - y_true), axis=-1)
When used with tf.distribute.Strategy, outside of built-in training loops such as tf.keras compile and fit, please use 'SUM' or 'NONE' reduction types, and reduce losses explicitly in your training loop. Using 'AUTO' or 'SUM_OVER_BATCH_SIZE' will raise an error. Please see this custom training tutorial for more details on this. You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like: with strategy.scope():
loss_obj = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)
....
loss = (tf.reduce_sum(loss_obj(labels, predictions)) *
(1. / global_batch_size))
Args
reduction (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates that the reduction option will be determined by the usage context. For almost all cases this defaults to SUM_OVER_BATCH_SIZE. When used with tf.distribute.Strategy, outside of built-in training loops such as tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
name Optional name for the op. Methods call View source
@abc.abstractmethod
call(
y_true, y_pred
)
Invokes the Loss instance.
Args
y_true Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
y_pred The predicted values. shape = [batch_size, d0, .. dN]
Returns Loss values with the shape [batch_size, d0, .. dN-1].
from_config View source
@classmethod
from_config(
config
)
Instantiates a Loss from its config (output of get_config()).
Args
config Output of get_config().
Returns A Loss instance.
get_config View source
get_config()
Returns the config dictionary for a Loss instance. __call__ View source
__call__(
y_true, y_pred, sample_weight=None
)
Invokes the Loss instance.
Args
y_true Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
y_pred The predicted values. shape = [batch_size, d0, .. dN]
sample_weight Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the total loss for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)
Returns Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)
Raises
ValueError If the shape of sample_weight is invalid. | |
doc_2640 | See Migration guide for more details. tf.compat.v1.keras.layers.GaussianNoise
tf.keras.layers.GaussianNoise(
stddev, **kwargs
)
This is useful to mitigate overfitting (you could see it as a form of random data augmentation). Gaussian Noise (GS) is a natural choice as corruption process for real valued inputs. As it is a regularization layer, it is only active at training time.
Arguments
stddev Float, standard deviation of the noise distribution. Call arguments:
inputs: Input tensor (of any rank).
training: Python boolean indicating whether the layer should behave in training mode (adding noise) or in inference mode (doing nothing). Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input. | |
doc_2641 | Copy an array to a new surface pygame.pixelcopy.make_surface(array) -> Surface Create a new Surface that best resembles the data and format of the array. The array can be 2D or 3D with any sized integer values. | |
doc_2642 |
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation. | |
doc_2643 |
Return whether the polygon is closed. | |
doc_2644 | Return a list of 2-tuples containing all the message’s field headers and values. | |
doc_2645 | self.int() is equivalent to self.to(torch.int32). See to(). Parameters
memory_format (torch.memory_format, optional) – the desired memory format of returned Tensor. Default: torch.preserve_format. | |
doc_2646 |
Creates a criterion that measures the mean absolute error (MAE) between each element in the input xx and target yy . The unreduced (i.e. with reduction set to 'none') loss can be described as: ℓ(x,y)=L={l1,…,lN}⊤,ln=∣xn−yn∣,\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = \left| x_n - y_n \right|,
where NN is the batch size. If reduction is not 'none' (default 'mean'), then: ℓ(x,y)={mean(L),if reduction=‘mean’;sum(L),if reduction=‘sum’.\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}
xx and yy are tensors of arbitrary shapes with a total of nn elements each. The sum operation still operates over all the elements, and divides by nn . The division by nn can be avoided if one sets reduction = 'sum'. Supports real-valued and complex-valued inputs. Parameters
size_average (bool, optional) – Deprecated (see reduction). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there are multiple elements per sample. If the field size_average is set to False, the losses are instead summed for each minibatch. Ignored when reduce is False. Default: True
reduce (bool, optional) – Deprecated (see reduction). By default, the losses are averaged or summed over observations for each minibatch depending on size_average. When reduce is False, returns a loss per batch element instead and ignores size_average. Default: True
reduction (string, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied, 'mean': the sum of the output will be divided by the number of elements in the output, 'sum': the output will be summed. Note: size_average and reduce are in the process of being deprecated, and in the meantime, specifying either of those two args will override reduction. Default: 'mean'
Shape:
Input: (N,∗)(N, *) where ∗* means, any number of additional dimensions Target: (N,∗)(N, *) , same shape as the input Output: scalar. If reduction is 'none', then (N,∗)(N, *) , same shape as the input Examples: >>> loss = nn.L1Loss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.randn(3, 5)
>>> output = loss(input, target)
>>> output.backward() | |
doc_2647 | A special typing construct to indicate to type checkers that a name cannot be re-assigned or overridden in a subclass. For example: MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
class Connection:
TIMEOUT: Final[int] = 10
class FastConnector(Connection):
TIMEOUT = 1 # Error reported by type checker
There is no runtime checking of these properties. See PEP 591 for more details. New in version 3.8. | |
doc_2648 | See Migration guide for more details. tf.compat.v1.keras.activations.softplus
tf.keras.activations.softplus(
x
)
Example Usage:
a = tf.constant([-20, -1.0, 0.0, 1.0, 20], dtype = tf.float32)
b = tf.keras.activations.softplus(a)
b.numpy()
array([2.0611537e-09, 3.1326166e-01, 6.9314718e-01, 1.3132616e+00,
2.0000000e+01], dtype=float32)
Arguments
x Input tensor.
Returns The softplus activation: log(exp(x) + 1). | |
doc_2649 |
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). | |
doc_2650 | The maximum size (in bytes) of the call stack for the current process. This only affects the stack of the main thread in a multi-threaded process. | |
doc_2651 | tf.compat.v1.data.make_initializable_iterator(
dataset, shared_name=None
)
Note: The returned iterator will be in an uninitialized state, and you must run the iterator.initializer operation before using it:
dataset = ...
iterator = tf.compat.v1.data.make_initializable_iterator(dataset)
# ...
sess.run(iterator.initializer)
Args
dataset A tf.data.Dataset.
shared_name (Optional.) If non-empty, the returned iterator will be shared under the given name across multiple sessions that share the same devices (e.g. when using a remote server).
Returns A tf.data.Iterator for elements of dataset.
Raises
RuntimeError If eager execution is enabled. | |
doc_2652 |
Evaluate a Legendre series at points x. If c is of length n + 1, this function returns the value: \[p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x)\] The parameter x is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either x or its elements must support multiplication and addition both with themselves and with the elements of c. If c is a 1-D array, then p(x) will have the same shape as x. If c is multidimensional, then the shape of the result depends on the value of tensor. If tensor is true the shape will be c.shape[1:] + x.shape. If tensor is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters
xarray_like, compatible object
If x is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, x or its elements must support addition and multiplication with with themselves and with the elements of c.
carray_like
Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If c is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of c.
tensorboolean, optional
If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of x. Scalars have dimension 0 for this action. The result is that every column of coefficients in c is evaluated for every element of x. If False, x is broadcast over the columns of c for the evaluation. This keyword is useful when c is multidimensional. The default value is True. New in version 1.7.0. Returns
valuesndarray, algebra_like
The shape of the return value is described above. See also
legval2d, leggrid2d, legval3d, leggrid3d
Notes The evaluation uses Clenshaw recursion, aka synthetic division. | |
doc_2653 | List of socket.socket objects the server is listening on. Changed in version 3.7: Prior to Python 3.7 Server.sockets used to return an internal list of server sockets directly. In 3.7 a copy of that list is returned. | |
doc_2654 |
Description of the Tool. str: Tooltip used if the Tool is included in a Toolbar. | |
doc_2655 |
[Deprecated] dpi_cor is currently used for linewidth-related things and shrink factor. Mutation scale is affected by this. Returns
scalar
Notes Deprecated since version 3.4. | |
doc_2656 |
Print the current state of the nditer instance and debug info to stdout. | |
doc_2657 |
Add a vertical span (rectangle) across the Axes. The rectangle spans from xmin to xmax horizontally, and, by default, the whole y-axis vertically. The y-span can be set using ymin (default: 0) and ymax (default: 1) which are in axis units; e.g. ymin = 0.5 always refers to the middle of the y-axis regardless of the limits set by set_ylim. Parameters
xminfloat
Lower x-coordinate of the span, in data units.
xmaxfloat
Upper x-coordinate of the span, in data units.
yminfloat, default: 0
Lower y-coordinate of the span, in y-axis units (0-1).
ymaxfloat, default: 1
Upper y-coordinate of the span, in y-axis units (0-1). Returns
Polygon
Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax). Other Parameters
**kwargsPolygon properties
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
antialiased or aa bool or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
closed bool
color color
edgecolor or ec color or None
facecolor or fc color or None
figure Figure
fill bool
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw float or None
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
xy (N, 2) array-like
zorder float See also axhspan
Add a horizontal span across the Axes. Examples Draw a vertical, green, translucent rectangle from x = 1.25 to x = 1.55 that spans the yrange of the Axes. >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5) | |
doc_2658 | See Migration guide for more details. tf.compat.v1.raw_ops.ExperimentalDatasetCardinality
tf.raw_ops.ExperimentalDatasetCardinality(
input_dataset, name=None
)
Returns the cardinality of input_dataset.
Args
input_dataset A Tensor of type variant. A variant tensor representing the dataset to return cardinality for.
name A name for the operation (optional).
Returns A Tensor of type int64. | |
doc_2659 |
Insert scalar into an array (scalar is cast to array’s dtype, if possible) There must be at least 1 argument, and define the last argument as item. Then, a.itemset(*args) is equivalent to but faster than a[args] = item. The item should be a scalar value and args must select a single item in the array a. Parameters
*argsArguments
If one argument: a scalar, only used in case a is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple. Notes Compared to indexing syntax, itemset provides some speed increase for placing a scalar into a particular location in an ndarray, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using itemset (and item) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration. Examples >>> np.random.seed(123)
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[2, 2, 6],
[1, 3, 6],
[1, 0, 1]])
>>> x.itemset(4, 0)
>>> x.itemset((2, 2), 9)
>>> x
array([[2, 2, 6],
[1, 0, 6],
[1, 0, 9]]) | |
doc_2660 |
Transform X separately by each transformer, concatenate results. Parameters
Xiterable or array-like, depending on transformers
Input data to be transformed. Returns
X_tarray-like or sparse matrix of shape (n_samples, sum_n_components)
hstack of results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers. | |
doc_2661 | Add a file to the current component of the directory, starting a new one if there is no current component. By default, the file name in the source and the file table will be identical. If the src file is specified, it is interpreted relative to the current directory. Optionally, a version and a language can be specified for the entry in the File table. | |
doc_2662 | See Migration guide for more details. tf.compat.v1.raw_ops.ResourceApplyAdaMax
tf.raw_ops.ResourceApplyAdaMax(
var, m, v, beta1_power, lr, beta1, beta2, epsilon, grad, use_locking=False,
name=None
)
mt <- beta1 * m{t-1} + (1 - beta1) * g vt <- max(beta2 * v{t-1}, abs(g)) variable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon)
Args
var A Tensor of type resource. Should be from a Variable().
m A Tensor of type resource. Should be from a Variable().
v A Tensor of type resource. Should be from a Variable().
beta1_power A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. Must be a scalar.
lr A Tensor. Must have the same type as beta1_power. Scaling factor. Must be a scalar.
beta1 A Tensor. Must have the same type as beta1_power. Momentum factor. Must be a scalar.
beta2 A Tensor. Must have the same type as beta1_power. Momentum factor. Must be a scalar.
epsilon A Tensor. Must have the same type as beta1_power. Ridge term. Must be a scalar.
grad A Tensor. Must have the same type as beta1_power. The gradient.
use_locking An optional bool. Defaults to False. If True, updating of the var, m, and v tensors will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention.
name A name for the operation (optional).
Returns The created Operation. | |
doc_2663 |
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. | |
doc_2664 | sklearn.metrics.pairwise.kernel_metrics() [source]
Valid metrics for pairwise_kernels. This function simply returns the valid pairwise distance metrics. It exists, however, to allow for a verbose description of the mapping for each of the valid strings. The valid distance metrics, and the function they map to, are:
metric Function
‘additive_chi2’ sklearn.pairwise.additive_chi2_kernel
‘chi2’ sklearn.pairwise.chi2_kernel
‘linear’ sklearn.pairwise.linear_kernel
‘poly’ sklearn.pairwise.polynomial_kernel
‘polynomial’ sklearn.pairwise.polynomial_kernel
‘rbf’ sklearn.pairwise.rbf_kernel
‘laplacian’ sklearn.pairwise.laplacian_kernel
‘sigmoid’ sklearn.pairwise.sigmoid_kernel
‘cosine’ sklearn.pairwise.cosine_similarity Read more in the User Guide. | |
doc_2665 |
Return the last row(s) without any NaNs before where. The last row (for each element in where, if list) without any NaN is taken. In case of a DataFrame, the last row without NaN considering only the subset of columns (if not None) If there is no good value, NaN is returned for a Series or a Series of NaN values for a DataFrame Parameters
where:date or array-like of dates
Date(s) before which the last row(s) are returned.
subset:str or array-like of str, default None
For DataFrame, if not None, only use these columns to check for NaNs. Returns
scalar, Series, or DataFrame
The return can be: scalar : when self is a Series and where is a scalar Series: when self is a Series and where is an array-like, or when self is a DataFrame and where is a scalar DataFrame : when self is a DataFrame and where is an array-like Return scalar, Series, or DataFrame. See also merge_asof
Perform an asof merge. Similar to left join. Notes Dates are assumed to be sorted. Raises if this is not the case. Examples A Series and a scalar where.
>>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])
>>> s
10 1.0
20 2.0
30 NaN
40 4.0
dtype: float64
>>> s.asof(20)
2.0
For a sequence where, a Series is returned. The first value is NaN, because the first element of where is before the first index value.
>>> s.asof([5, 20])
5 NaN
20 2.0
dtype: float64
Missing values are not considered. The following is 2.0, not NaN, even though NaN is at the index location for 30.
>>> s.asof(30)
2.0
Take all columns into consideration
>>> df = pd.DataFrame({'a': [10, 20, 30, 40, 50],
... 'b': [None, None, None, None, 500]},
... index=pd.DatetimeIndex(['2018-02-27 09:01:00',
... '2018-02-27 09:02:00',
... '2018-02-27 09:03:00',
... '2018-02-27 09:04:00',
... '2018-02-27 09:05:00']))
>>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
... '2018-02-27 09:04:30']))
a b
2018-02-27 09:03:30 NaN NaN
2018-02-27 09:04:30 NaN NaN
Take a single column into consideration
>>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
... '2018-02-27 09:04:30']),
... subset=['a'])
a b
2018-02-27 09:03:30 30.0 NaN
2018-02-27 09:04:30 40.0 NaN | |
doc_2666 |
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data | |
doc_2667 | Set list_display to control which fields are displayed on the change list page of the admin. Example: list_display = ('first_name', 'last_name')
If you don’t set list_display, the admin site will display a single column that displays the __str__() representation of each object. There are four types of values that can be used in list_display. All but the simplest may use the display() decorator is used to customize how the field is presented:
The name of a model field. For example: class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name')
A callable that accepts one argument, the model instance. For example: @admin.display(description='Name')
def upper_case_name(obj):
return ("%s %s" % (obj.first_name, obj.last_name)).upper()
class PersonAdmin(admin.ModelAdmin):
list_display = (upper_case_name,)
A string representing a ModelAdmin method that accepts one argument, the model instance. For example: class PersonAdmin(admin.ModelAdmin):
list_display = ('upper_case_name',)
@admin.display(description='Name')
def upper_case_name(self, obj):
return ("%s %s" % (obj.first_name, obj.last_name)).upper()
A string representing a model attribute or method (without any required arguments). For example: from django.contrib import admin
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
@admin.display(description='Birth decade')
def decade_born_in(self):
return '%d’s' % (self.birthday.year // 10 * 10)
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'decade_born_in')
A few special cases to note about list_display: If the field is a ForeignKey, Django will display the __str__() of the related object.
ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.) If the field is a BooleanField, Django will display a pretty “yes”, “no”, or “unknown” icon instead of True, False, or None.
If the string given is a method of the model, ModelAdmin or a callable, Django will HTML-escape the output by default. To escape user input and allow your own unescaped tags, use format_html(). Here’s a full example model: from django.contrib import admin
from django.db import models
from django.utils.html import format_html
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6)
@admin.display
def colored_name(self):
return format_html(
'<span style="color: #{};">{} {}</span>',
self.color_code,
self.first_name,
self.last_name,
)
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'colored_name')
As some examples have already demonstrated, when using a callable, a model method, or a ModelAdmin method, you can customize the column’s title by wrapping the callable with the display() decorator and passing the description argument. Changed in Django 3.2: The description argument to the display() decorator is equivalent to setting the short_description attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.
If the value of a field is None, an empty string, or an iterable without elements, Django will display - (a dash). You can override this with AdminSite.empty_value_display: from django.contrib import admin
admin.site.empty_value_display = '(None)'
You can also use ModelAdmin.empty_value_display: class PersonAdmin(admin.ModelAdmin):
empty_value_display = 'unknown'
Or on a field level: class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'birth_date_view')
@admin.display(empty_value='unknown')
def birth_date_view(self, obj):
return obj.birth_date
Changed in Django 3.2: The empty_value argument to the display() decorator is equivalent to setting the empty_value_display attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.
If the string given is a method of the model, ModelAdmin or a callable that returns True, False, or None, Django will display a pretty “yes”, “no”, or “unknown” icon if you wrap the method with the display() decorator passing the boolean argument with the value set to True: from django.contrib import admin
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
birthday = models.DateField()
@admin.display(boolean=True)
def born_in_fifties(self):
return 1950 <= self.birthday.year < 1960
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'born_in_fifties')
Changed in Django 3.2: The boolean argument to the display() decorator is equivalent to setting the boolean attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.
The __str__() method is just as valid in list_display as any other model method, so it’s perfectly OK to do this: list_display = ('__str__', 'some_other_field')
Usually, elements of list_display that aren’t actual database fields can’t be used in sorting (because Django does all the sorting at the database level). However, if an element of list_display represents a certain database field, you can indicate this fact by using the display() decorator on the method, passing the ordering argument: from django.contrib import admin
from django.db import models
from django.utils.html import format_html
class Person(models.Model):
first_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6)
@admin.display(ordering='first_name')
def colored_first_name(self):
return format_html(
'<span style="color: #{};">{}</span>',
self.color_code,
self.first_name,
)
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'colored_first_name')
The above will tell Django to order by the first_name field when trying to sort by colored_first_name in the admin. To indicate descending order with the ordering argument you can use a hyphen prefix on the field name. Using the above example, this would look like: @admin.display(ordering='-first_name')
The ordering argument supports query lookups to sort by values on related models. This example includes an “author first name” column in the list display and allows sorting it by first name: class Blog(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(Person, on_delete=models.CASCADE)
class BlogAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'author_first_name')
@admin.display(ordering='author__first_name')
def author_first_name(self, obj):
return obj.author.first_name
Query expressions may be used with the ordering argument: from django.db.models import Value
from django.db.models.functions import Concat
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@admin.display(ordering=Concat('first_name', Value(' '), 'last_name'))
def full_name(self):
return self.first_name + ' ' + self.last_name
Changed in Django 3.2: The ordering argument to the display() decorator is equivalent to setting the admin_order_field attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.
Elements of list_display can also be properties: class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@property
@admin.display(
ordering='last_name',
description='Full name of the person',
)
def full_name(self):
return self.first_name + ' ' + self.last_name
class PersonAdmin(admin.ModelAdmin):
list_display = ('full_name',)
Note that @property must be above @display. If you’re using the old way – setting the display-related attributes directly rather than using the display() decorator – be aware that the property() function and not the @property decorator must be used: def my_property(self):
return self.first_name + ' ' + self.last_name
my_property.short_description = "Full name of the person"
my_property.admin_order_field = 'last_name'
full_name = property(my_property)
The field names in list_display will also appear as CSS classes in the HTML output, in the form of column-<field_name> on each <th> element. This can be used to set column widths in a CSS file for example.
Django will try to interpret every element of list_display in this order: A field of the model. A callable. A string representing a ModelAdmin attribute. A string representing a model attribute. For example if you have first_name as a model field and as a ModelAdmin attribute, the model field will be used. | |
doc_2668 | Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the spec object as their spec. Functions or methods being mocked will have their arguments checked to ensure that they are called with the correct signature. If spec_set is True then attempting to set attributes that don’t exist on the spec object will raise an AttributeError. If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing instance=True. The returned mock will only be callable if instances of the mock are callable. create_autospec() also takes arbitrary keyword arguments that are passed to the constructor of the created mock. | |
doc_2669 |
Update this artist's properties from the dict props. Parameters
propsdict | |
doc_2670 | See Migration guide for more details. tf.compat.v1.raw_ops.TensorListScatter
tf.raw_ops.TensorListScatter(
tensor, indices, element_shape, name=None
)
Each member of the TensorList corresponds to one row of the input tensor, specified by the given index (see tf.gather). tensor: The input tensor. indices: The indices used to index into the list. element_shape: The shape of the elements in the list (can be less specified than the shape of the tensor). output_handle: The TensorList.
Args
tensor A Tensor.
indices A Tensor of type int32.
element_shape A Tensor. Must be one of the following types: int32, int64.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_2671 |
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_2672 | A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context. Example: import gevent
from flask import copy_current_request_context
@app.route('/')
def index():
@copy_current_request_context
def do_some_work():
# do some work here, it can access flask.request or
# flask.session like you would otherwise in the view function.
...
gevent.spawn(do_some_work)
return 'Regular response'
Changelog New in version 0.10. Parameters
f (Callable) – Return type
Callable | |
doc_2673 | See Migration guide for more details. tf.compat.v1.raw_ops.MaxIntraOpParallelismDataset
tf.raw_ops.MaxIntraOpParallelismDataset(
input_dataset, max_intra_op_parallelism, output_types, output_shapes, name=None
)
Args
input_dataset A Tensor of type variant.
max_intra_op_parallelism A Tensor of type int64. Identifies the maximum intra-op parallelism to use.
output_types A list of tf.DTypes that has length >= 1.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_2674 |
Return local geometric mean of an image. Parameters
image([P,] M, N) ndarray (uint8, uint16)
Input image.
selemndarray
The neighborhood expressed as an ndarray of 1’s and 0’s.
out([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
maskndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_zint
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns
out([P,] M, N) ndarray (same dtype as input image)
Output image. References
1
Gonzalez, R. C. and Wood, R. E. “Digital Image Processing (3rd Edition).” Prentice-Hall Inc, 2006. Examples >>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import mean
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> avg = geometric_mean(img, disk(5))
>>> avg_vol = geometric_mean(volume, ball(5)) | |
doc_2675 |
Immutable index of intervals that are closed on the same side. New in version 0.20.0. Parameters
data:array-like (1-dimensional)
Array-like containing Interval objects from which to build the IntervalIndex.
closed:{‘left’, ‘right’, ‘both’, ‘neither’}, default ‘right’
Whether the intervals are closed on the left-side, right-side, both or neither.
dtype:dtype or None, default None
If None, dtype will be inferred.
copy:bool, default False
Copy the input data.
name:object, optional
Name to be stored in the index.
verify_integrity:bool, default True
Verify that the IntervalIndex is valid. See also Index
The base pandas Index type. Interval
A bounded slice-like interval; the elements of an IntervalIndex. interval_range
Function to create a fixed frequency IntervalIndex. cut
Bin values into discrete Intervals. qcut
Bin values into equal-sized Intervals based on rank or sample quantiles. Notes See the user guide for more. Examples A new IntervalIndex is typically constructed using interval_range():
>>> pd.interval_range(start=0, end=5)
IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],
dtype='interval[int64, right]')
It may also be constructed using one of the constructor methods: IntervalIndex.from_arrays(), IntervalIndex.from_breaks(), and IntervalIndex.from_tuples(). See further examples in the doc strings of interval_range and the mentioned constructor methods. Attributes
closed Whether the intervals are closed on the left-side, right-side, both or neither.
is_empty Indicates if an interval is empty, meaning it contains no points.
is_non_overlapping_monotonic Return True if the IntervalArray is non-overlapping (no Intervals share points) and is either monotonic increasing or monotonic decreasing, else False.
is_overlapping Return True if the IntervalIndex has overlapping intervals, else False.
values Return an array representing the data in the Index.
left
right
mid
length Methods
from_arrays(left, right[, closed, name, ...]) Construct from two arrays defining the left and right bounds.
from_tuples(data[, closed, name, copy, dtype]) Construct an IntervalIndex from an array-like of tuples.
from_breaks(breaks[, closed, name, copy, dtype]) Construct an IntervalIndex from an array of splits.
contains(*args, **kwargs) Check elementwise if the Intervals contain the value.
overlaps(*args, **kwargs) Check elementwise if an Interval overlaps the values in the IntervalArray.
set_closed(*args, **kwargs) Return an IntervalArray identical to the current one, but closed on the specified side.
to_tuples(*args, **kwargs) Return an ndarray of tuples of the form (left, right). | |
doc_2676 |
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas. | |
doc_2677 | See Migration guide for more details. tf.compat.v1.raw_ops.UniqueV2
tf.raw_ops.UniqueV2(
x, axis, out_idx=tf.dtypes.int32, name=None
)
This operation either returns a tensor y containing unique elements along the axis of a tensor. The returned unique elements is sorted in the same order as they occur along axis in x. This operation also returns a tensor idx that is the same size as the number of the elements in x along the axis dimension. It contains the index in the unique output y. In other words, for an 1-D tensor x with `axis = None: y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1] For example: # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]
y, idx = unique(x)
y ==> [1, 2, 4, 7, 8]
idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]
For an 2-D tensor x with axis = 0: # tensor 'x' is [[1, 0, 0],
# [1, 0, 0],
# [2, 0, 0]]
y, idx = unique(x, axis=0)
y ==> [[1, 0, 0],
[2, 0, 0]]
idx ==> [0, 0, 1]
For an 2-D tensor x with axis = 1: # tensor 'x' is [[1, 0, 0],
# [1, 0, 0],
# [2, 0, 0]]
y, idx = unique(x, axis=1)
y ==> [[1, 0],
[1, 0],
[2, 0]]
idx ==> [0, 1, 1]
Args
x A Tensor. A Tensor.
axis A Tensor. Must be one of the following types: int32, int64. A Tensor of type int32 (default: None). The axis of the Tensor to find the unique elements.
out_idx An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int32.
name A name for the operation (optional).
Returns A tuple of Tensor objects (y, idx). y A Tensor. Has the same type as x.
idx A Tensor of type out_idx. | |
doc_2678 | Computes the eigenvalues and eigenvectors of a complex Hermitian (or real symmetric) matrix input, or of each such matrix in a batched input. For a single matrix input, the tensor of eigenvalues w and the tensor of eigenvectors V decompose the input such that input = V diag(w) Vᴴ, where Vᴴ is the transpose of V for real-valued input, or the conjugate transpose of V for complex-valued input. Since the matrix or matrices in input are assumed to be Hermitian, the imaginary part of their diagonals is always treated as zero. When UPLO is “L”, its default value, only the lower triangular part of each matrix is used in the computation. When UPLO is “U” only the upper triangular part of each matrix is used. Supports input of float, double, cfloat and cdouble dtypes. Note When given inputs on a CUDA device, this function synchronizes that device with the CPU. Note The eigenvalues/eigenvectors are computed using LAPACK’s syevd and heevd routines for CPU inputs, and MAGMA’s syevd and heevd routines for CUDA inputs. Note The eigenvalues of real symmetric or complex Hermitian matrices are always real. Note The eigenvectors of matrices are not unique, so any eigenvector multiplied by a constant remains a valid eigenvector. This function may compute different eigenvector representations on different device types. Usually the difference is only in the sign of the eigenvector. Note See torch.linalg.eigvalsh() for a related function that computes only eigenvalues. However, that function is not differentiable. Parameters
input (Tensor) – the Hermitian n times n matrix or the batch of such matrices of size (*, n, n) where * is one or more batch dimensions.
UPLO ('L', 'U', optional) – controls whether to use the upper-triangular or the lower-triangular part of input in the computations. Default is 'L'. Keyword Arguments
out (tuple, optional) – tuple of two tensors to write the output to. Default is None. Returns
A namedtuple (eigenvalues, eigenvectors) containing
eigenvalues (Tensor): Shape (*, m).
The eigenvalues in ascending order.
eigenvectors (Tensor): Shape (*, m, m).
The orthonormal eigenvectors of the input. Return type
(Tensor, Tensor) Examples: >>> a = torch.randn(2, 2, dtype=torch.complex128)
>>> a = a + a.t().conj() # creates a Hermitian matrix
>>> a
tensor([[2.9228+0.0000j, 0.2029-0.0862j],
[0.2029+0.0862j, 0.3464+0.0000j]], dtype=torch.complex128)
>>> w, v = torch.linalg.eigh(a)
>>> w
tensor([0.3277, 2.9415], dtype=torch.float64)
>>> v
tensor([[-0.0846+-0.0000j, -0.9964+0.0000j],
[ 0.9170+0.3898j, -0.0779-0.0331j]], dtype=torch.complex128)
>>> torch.allclose(torch.matmul(v, torch.matmul(w.to(v.dtype).diag_embed(), v.t().conj())), a)
True
>>> a = torch.randn(3, 2, 2, dtype=torch.float64)
>>> a = a + a.transpose(-2, -1) # creates a symmetric matrix
>>> w, v = torch.linalg.eigh(a)
>>> torch.allclose(torch.matmul(v, torch.matmul(w.diag_embed(), v.transpose(-2, -1))), a)
True | |
doc_2679 | Return a list of file names as returned by the NLST command. The optional argument is a directory to list (default is the current server directory). Multiple arguments can be used to pass non-standard options to the NLST command. Note If your server supports the command, mlsd() offers a better API. | |
doc_2680 |
Bases: matplotlib.patheffects.AbstractPathEffect The "identity" PathEffect. The Normal PathEffect's sole purpose is to draw the original artist with no special path effect. Parameters
offset(float, float), default: (0, 0)
The (x, y) offset to apply to the path, measured in points. | |
doc_2681 | Wait until a predicate becomes true. The predicate must be a callable which result will be interpreted as a boolean value. The final value is the return value. | |
doc_2682 | Raise ResourceDenied if resource is not available. msg is the argument to ResourceDenied if it is raised. Always returns True if called by a function whose __name__ is '__main__'. Used when tests are executed by test.regrtest. | |
doc_2683 |
Interpolate values according to different methods. Fill NaN values using an interpolation method. Please note that only method='linear' is supported for DataFrame/Series with a MultiIndex. Parameters
method:str, default ‘linear’
Interpolation technique to use. One of: ‘linear’: Ignore the index and treat the values as equally spaced. This is the only method supported on MultiIndexes. ‘time’: Works on daily and higher resolution data to interpolate given length of interval. ‘index’, ‘values’: use the actual numerical values of the index. ‘pad’: Fill in NaNs using existing values. ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘spline’, ‘barycentric’, ‘polynomial’: Passed to scipy.interpolate.interp1d. These methods use the numerical values of the index. Both ‘polynomial’ and ‘spline’ require that you also specify an order (int), e.g. df.interpolate(method='polynomial', order=5). ‘krogh’, ‘piecewise_polynomial’, ‘spline’, ‘pchip’, ‘akima’, ‘cubicspline’: Wrappers around the SciPy interpolation methods of similar names. See Notes. ‘from_derivatives’: Refers to scipy.interpolate.BPoly.from_derivatives which replaces ‘piecewise_polynomial’ interpolation method in scipy 0.18.
axis:{{0 or ‘index’, 1 or ‘columns’, None}}, default None
Axis to interpolate along.
limit:int, optional
Maximum number of consecutive NaNs to fill. Must be greater than 0.
inplace:bool, default False
Update the data in place if possible.
limit_direction:{{‘forward’, ‘backward’, ‘both’}}, Optional
Consecutive NaNs will be filled in this direction. If limit is specified:
If ‘method’ is ‘pad’ or ‘ffill’, ‘limit_direction’ must be ‘forward’. If ‘method’ is ‘backfill’ or ‘bfill’, ‘limit_direction’ must be ‘backwards’. If ‘limit’ is not specified:
If ‘method’ is ‘backfill’ or ‘bfill’, the default is ‘backward’ else the default is ‘forward’ Changed in version 1.1.0: raises ValueError if limit_direction is ‘forward’ or ‘both’ and method is ‘backfill’ or ‘bfill’. raises ValueError if limit_direction is ‘backward’ or ‘both’ and method is ‘pad’ or ‘ffill’.
limit_area:{{None, ‘inside’, ‘outside’}}, default None
If limit is specified, consecutive NaNs will be filled with this restriction. None: No fill restriction. ‘inside’: Only fill NaNs surrounded by valid values (interpolate). ‘outside’: Only fill NaNs outside valid values (extrapolate).
downcast:optional, ‘infer’ or None, defaults to None
Downcast dtypes if possible.
``**kwargs``:optional
Keyword arguments to pass on to the interpolating function. Returns
Series or DataFrame or None
Returns the same object type as the caller, interpolated at some or all NaN values or None if inplace=True. See also fillna
Fill missing values using different methods. scipy.interpolate.Akima1DInterpolator
Piecewise cubic polynomials (Akima interpolator). scipy.interpolate.BPoly.from_derivatives
Piecewise polynomial in the Bernstein basis. scipy.interpolate.interp1d
Interpolate a 1-D function. scipy.interpolate.KroghInterpolator
Interpolate polynomial (Krogh interpolator). scipy.interpolate.PchipInterpolator
PCHIP 1-d monotonic cubic interpolation. scipy.interpolate.CubicSpline
Cubic spline data interpolator. Notes The ‘krogh’, ‘piecewise_polynomial’, ‘spline’, ‘pchip’ and ‘akima’ methods are wrappers around the respective SciPy implementations of similar names. These use the actual numerical values of the index. For more information on their behavior, see the SciPy documentation and SciPy tutorial. Examples Filling in NaN in a Series via linear interpolation.
>>> s = pd.Series([0, 1, np.nan, 3])
>>> s
0 0.0
1 1.0
2 NaN
3 3.0
dtype: float64
>>> s.interpolate()
0 0.0
1 1.0
2 2.0
3 3.0
dtype: float64
Filling in NaN in a Series by padding, but filling at most two consecutive NaN at a time.
>>> s = pd.Series([np.nan, "single_one", np.nan,
... "fill_two_more", np.nan, np.nan, np.nan,
... 4.71, np.nan])
>>> s
0 NaN
1 single_one
2 NaN
3 fill_two_more
4 NaN
5 NaN
6 NaN
7 4.71
8 NaN
dtype: object
>>> s.interpolate(method='pad', limit=2)
0 NaN
1 single_one
2 single_one
3 fill_two_more
4 fill_two_more
5 fill_two_more
6 NaN
7 4.71
8 4.71
dtype: object
Filling in NaN in a Series via polynomial interpolation or splines: Both ‘polynomial’ and ‘spline’ methods require that you also specify an order (int).
>>> s = pd.Series([0, 2, np.nan, 8])
>>> s.interpolate(method='polynomial', order=2)
0 0.000000
1 2.000000
2 4.666667
3 8.000000
dtype: float64
Fill the DataFrame forward (that is, going down) along each column using linear interpolation. Note how the last entry in column ‘a’ is interpolated differently, because there is no entry after it to use for interpolation. Note how the first entry in column ‘b’ remains NaN, because there is no entry before it to use for interpolation.
>>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),
... (np.nan, 2.0, np.nan, np.nan),
... (2.0, 3.0, np.nan, 9.0),
... (np.nan, 4.0, -4.0, 16.0)],
... columns=list('abcd'))
>>> df
a b c d
0 0.0 NaN -1.0 1.0
1 NaN 2.0 NaN NaN
2 2.0 3.0 NaN 9.0
3 NaN 4.0 -4.0 16.0
>>> df.interpolate(method='linear', limit_direction='forward', axis=0)
a b c d
0 0.0 NaN -1.0 1.0
1 1.0 2.0 -2.0 5.0
2 2.0 3.0 -3.0 9.0
3 2.0 4.0 -4.0 16.0
Using polynomial interpolation.
>>> df['d'].interpolate(method='polynomial', order=2)
0 1.0
1 4.0
2 9.0
3 16.0
Name: d, dtype: float64 | |
doc_2684 |
Get the affine part of this transform. | |
doc_2685 |
Set the line width of the Figure rectangle. Parameters
linewidthnumber | |
doc_2686 |
Scale back the data to the original representation Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The rescaled data to be transformed back. Returns
X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)
Transformed array. | |
doc_2687 |
Returns a 1D version of self, as a view. Parameters
order{‘C’, ‘F’, ‘A’, ‘K’}, optional
The elements of a are read using this index order. ‘C’ means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. ‘A’ means to read the elements in Fortran-like index order if m is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used. Returns
MaskedArray
Output view is of shape (self.size,) (or (np.ma.product(self.shape),)). Examples >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> x
masked_array(
data=[[1, --, 3],
[--, 5, --],
[7, --, 9]],
mask=[[False, True, False],
[ True, False, True],
[False, True, False]],
fill_value=999999)
>>> x.ravel()
masked_array(data=[1, --, 3, --, 5, --, 7, --, 9],
mask=[False, True, False, True, False, True, False, True,
False],
fill_value=999999) | |
doc_2688 |
Vectorized string functions for Series and Index. NAs stay NA unless handled otherwise by a particular method. Patterned after Python’s string methods, with some inspiration from R’s stringr package. Examples
>>> s = pd.Series(["A_Str_Series"])
>>> s
0 A_Str_Series
dtype: object
>>> s.str.split("_")
0 [A, Str, Series]
dtype: object
>>> s.str.replace("_", "")
0 AStrSeries
dtype: object | |
doc_2689 | Return True if other refers to the same node as this node. This is especially useful for DOM implementations which use any sort of proxy architecture (because more than one object can refer to the same node). Note This is based on a proposed DOM Level 3 API which is still in the “working draft” stage, but this particular interface appears uncontroversial. Changes from the W3C will not necessarily affect this method in the Python DOM interface (though any new W3C API for this would also be supported). | |
doc_2690 |
Returns a bool array, where True if input element is real. If element has complex type with zero complex part, the return value for that element is True. Parameters
xarray_like
Input array. Returns
outndarray, bool
Boolean array of same shape as x. See also iscomplex
isrealobj
Return True if x is not a complex type. Notes isreal may behave unexpectedly for string or object arrays (see examples) Examples >>> a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j], dtype=complex)
>>> np.isreal(a)
array([False, True, True, True, True, False])
The function does not work on string arrays. >>> a = np.array([2j, "a"], dtype="U")
>>> np.isreal(a) # Warns about non-elementwise comparison
False
Returns True for all elements in input array of dtype=object even if any of the elements is complex. >>> a = np.array([1, "2", 3+4j], dtype=object)
>>> np.isreal(a)
array([ True, True, True])
isreal should not be used with object arrays >>> a = np.array([1+2j, 2+1j], dtype=object)
>>> np.isreal(a)
array([ True, True]) | |
doc_2691 |
Container for colormaps that are known to Matplotlib by name. Experimental While we expect the API to be final, we formally mark it as experimental for 3.5 because we want to keep the option to still adapt the API for 3.6 should the need arise. The universal registry instance is matplotlib.colormaps. There should be no need for users to instantiate ColormapRegistry themselves. Read access uses a dict-like interface mapping names to Colormaps: import matplotlib as mpl
cmap = mpl.colormaps['viridis']
Returned Colormaps are copies, so that their modification does not change the global definition of the colormap. Additional colormaps can be added via ColormapRegistry.register: mpl.colormaps.register(my_colormap) | |
doc_2692 | Convert a non-multipart or a multipart/related into a multipart/alternative, moving any existing Content- headers and payload into a (new) first part of the multipart. If boundary is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized). | |
doc_2693 | Same as ForeignKey.related_name. | |
doc_2694 | turtle.addshape(name, shape=None)
There are three different ways to call this function:
name is the name of a gif-file and shape is None: Install the corresponding image shape. >>> screen.register_shape("turtle.gif")
Note Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle!
name is an arbitrary string and shape is a tuple of pairs of coordinates: Install the corresponding polygon shape. >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
name is an arbitrary string and shape is a (compound) Shape object: Install the corresponding compound shape. Add a turtle shape to TurtleScreen’s shapelist. Only thusly registered shapes can be used by issuing the command shape(shapename). | |
doc_2695 | Return a floating point number constructed from a number or string x. If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:
sign ::= "+" | "-"
infinity ::= "Infinity" | "inf"
nan ::= "nan"
numeric_value ::= floatnumber | infinity | nan
numeric_string ::= [sign] numeric_value
Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity. Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised. For a general Python object x, float(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__(). If no argument is given, 0.0 is returned. Examples: >>> float('+1.23')
1.23
>>> float(' -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
The float type is described in Numeric Types — int, float, complex. Changed in version 3.6: Grouping digits with underscores as in code literals is allowed. Changed in version 3.7: x is now a positional-only parameter. Changed in version 3.8: Falls back to __index__() if __float__() is not defined. | |
doc_2696 | turtle.resetscreen()
Reset all Turtles on the Screen to their initial state. Note This TurtleScreen method is available as a global function only under the name resetscreen. The global function reset is another one derived from the Turtle method reset. | |
doc_2697 |
Return whether the artist uses clipping. | |
doc_2698 |
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description. | |
doc_2699 | Open an LZMA-compressed file in binary mode. An LZMAFile can wrap an already-open file object, or operate directly on a named file. The filename argument specifies either the file object to wrap, or the name of the file to open (as a str, bytes or path-like object). When wrapping an existing file object, the wrapped file will not be closed when the LZMAFile is closed. The mode argument can be either "r" for reading (default), "w" for overwriting, "x" for exclusive creation, or "a" for appending. These can equivalently be given as "rb", "wb", "xb" and "ab" respectively. If filename is a file object (rather than an actual file name), a mode of "w" does not truncate the file, and is instead equivalent to "a". When opening a file for reading, the input file may be the concatenation of multiple separate compressed streams. These are transparently decoded as a single logical stream. When opening a file for reading, the format and filters arguments have the same meanings as for LZMADecompressor. In this case, the check and preset arguments should not be used. When opening a file for writing, the format, check, preset and filters arguments have the same meanings as for LZMACompressor. LZMAFile supports all the members specified by io.BufferedIOBase, except for detach() and truncate(). Iteration and the with statement are supported. The following method is also provided:
peek(size=-1)
Return buffered data without advancing the file position. At least one byte of data will be returned, unless EOF has been reached. The exact number of bytes returned is unspecified (the size argument is ignored). Note While calling peek() does not change the file position of the LZMAFile, it may change the position of the underlying file object (e.g. if the LZMAFile was constructed by passing a file object for filename).
Changed in version 3.4: Added support for the "x" and "xb" modes. Changed in version 3.5: The read() method now accepts an argument of None. Changed in version 3.6: Accepts a path-like object. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.