_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_25900
Subclasses can override this method to disallow the access to certain files. However by providing disallow in the constructor this method is overwritten. Parameters filename (str) – Return type bool
doc_25901
See Migration guide for more details. tf.compat.v1.keras.layers.AdditiveAttention tf.keras.layers.AdditiveAttention( use_scale=True, **kwargs ) Inputs are query tensor of shape [batch_size, Tq, dim], value tensor of shape [batch_size, Tv, dim] and key tensor of shape [batch_size, Tv, dim]. The calculation follows the steps: Reshape query and value into shapes [batch_size, Tq, 1, dim] and [batch_size, 1, Tv, dim] respectively. Calculate scores with shape [batch_size, Tq, Tv] as a non-linear sum: scores = tf.reduce_sum(tf.tanh(query + value), axis=-1) Use scores to calculate a distribution with shape [batch_size, Tq, Tv]: distribution = tf.nn.softmax(scores). Use distribution to create a linear combination of value with shape batch_size, Tq, dim]: return tf.matmul(distribution, value). Args use_scale If True, will create a variable to scale the attention scores. causal Boolean. Set to True for decoder self-attention. Adds a mask such that position i cannot attend to positions j > i. This prevents the flow of information from the future towards the past. dropout Float between 0 and 1. Fraction of the units to drop for the attention scores. Call Arguments: inputs: List of the following tensors: query: Query Tensor of shape [batch_size, Tq, dim]. value: Value Tensor of shape [batch_size, Tv, dim]. key: Optional key Tensor of shape [batch_size, Tv, dim]. If not given, will use value for both key and value, which is the most common case. mask: List of the following tensors: query_mask: A boolean mask Tensor of shape [batch_size, Tq]. If given, the output will be zero at the positions where mask==False. value_mask: A boolean mask Tensor of shape [batch_size, Tv]. If given, will apply the mask such that values at positions where mask==False do not contribute to the result. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). return_attention_scores: bool, it True, returns the attention scores (after masking and softmax) as an additional output argument. Output: Attention outputs of shape [batch_size, Tq, dim]. [Optional] Attention scores after masking and softmax with shape [batch_size, Tq, Tv]. The meaning of query, value and key depend on the application. In the case of text similarity, for example, query is the sequence embeddings of the first piece of text and value is the sequence embeddings of the second piece of text. key is usually the same tensor as value. Here is a code example for using AdditiveAttention in a CNN+Attention network: # Variable-length int sequences. query_input = tf.keras.Input(shape=(None,), dtype='int32') value_input = tf.keras.Input(shape=(None,), dtype='int32') # Embedding lookup. token_embedding = tf.keras.layers.Embedding(max_tokens, dimension) # Query embeddings of shape [batch_size, Tq, dimension]. query_embeddings = token_embedding(query_input) # Value embeddings of shape [batch_size, Tv, dimension]. value_embeddings = token_embedding(value_input) # CNN layer. cnn_layer = tf.keras.layers.Conv1D( filters=100, kernel_size=4, # Use 'same' padding so outputs have the same shape as inputs. padding='same') # Query encoding of shape [batch_size, Tq, filters]. query_seq_encoding = cnn_layer(query_embeddings) # Value encoding of shape [batch_size, Tv, filters]. value_seq_encoding = cnn_layer(value_embeddings) # Query-value attention of shape [batch_size, Tq, filters]. query_value_attention_seq = tf.keras.layers.AdditiveAttention()( [query_seq_encoding, value_seq_encoding]) # Reduce over the sequence axis to produce encodings of shape # [batch_size, filters]. query_encoding = tf.keras.layers.GlobalAveragePooling1D()( query_seq_encoding) query_value_attention = tf.keras.layers.GlobalAveragePooling1D()( query_value_attention_seq) # Concatenate query and document encodings to produce a DNN input layer. input_layer = tf.keras.layers.Concatenate()( [query_encoding, query_value_attention]) # Add DNN layers, and create Model. # ...
doc_25902
Get or set the current tick locations and labels of the y-axis. Pass no arguments to return the current values without modifying them. Parameters ticksarray-like, optional The list of ytick locations. Passing an empty list removes all yticks. labelsarray-like, optional The labels to place at the given ticks locations. This argument can only be passed if ticks is passed as well. **kwargs Text properties can be used to control the appearance of the labels. Returns locs The list of ytick locations. labels The list of ylabel Text objects. Notes Calling this function with no arguments (e.g. yticks()) is the pyplot equivalent of calling get_yticks and get_yticklabels on the current axes. Calling this function with arguments is the pyplot equivalent of calling set_yticks and set_yticklabels on the current axes. Examples >>> locs, labels = yticks() # Get the current locations and labels. >>> yticks(np.arange(0, 1, step=0.2)) # Set label locations. >>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels. >>> yticks([0, 1, 2], ['January', 'February', 'March'], ... rotation=45) # Set text labels and properties. >>> yticks([]) # Disable yticks. Examples using matplotlib.pyplot.yticks Table Demo
doc_25903
alias of matplotlib.colorbar.Colorbar
doc_25904
Sets the default floating point dtype to d. This dtype is: The inferred dtype for python floats in torch.tensor(). Used to infer dtype for python complex numbers. The default complex dtype is set to torch.complex128 if default floating point dtype is torch.float64, otherwise it’s set to torch.complex64 The default floating point dtype is initially torch.float32. Parameters d (torch.dtype) – the floating point dtype to make the default Example >>> # initial default for floating point is torch.float32 >>> torch.tensor([1.2, 3]).dtype torch.float32 >>> # initial default for floating point is torch.complex64 >>> torch.tensor([1.2, 3j]).dtype torch.complex64 >>> torch.set_default_dtype(torch.float64) >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor torch.float64 >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor torch.complex128
doc_25905
Return the current local date. This is equivalent to date.fromtimestamp(time.time()).
doc_25906
draw all sprites in the right order onto the passed surface. draw(surface, bgd=None) -> Rect_list You can pass the background too. If a background is already set, then the bgd argument has no effect.
doc_25907
This is always True.
doc_25908
See torch.flipud()
doc_25909
Class that simulates a dictionary. The instance’s contents are kept in a regular dictionary, which is accessible via the data attribute of UserDict instances. If initialdata is provided, data is initialized with its contents; note that a reference to initialdata will not be kept, allowing it be used for other purposes. In addition to supporting the methods and operations of mappings, UserDict instances provide the following attribute: data A real dictionary used to store the contents of the UserDict class.
doc_25910
The keyword arguments that will be supplied when the partial object is called.
doc_25911
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
doc_25912
Define the picking behavior of the artist. Parameters pickerNone or bool or float or callable This can be one of the following: None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent) to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
doc_25913
Return whether the artist uses clipping.
doc_25914
Bases: torch.distributions.transformed_distribution.TransformedDistribution Samples from a two-parameter Weibull distribution. Example >>> m = Weibull(torch.tensor([1.0]), torch.tensor([1.0])) >>> m.sample() # sample from a Weibull distribution with scale=1, concentration=1 tensor([ 0.4784]) Parameters scale (float or Tensor) – Scale parameter of distribution (lambda). concentration (float or Tensor) – Concentration parameter of distribution (k/shape). arg_constraints: Dict[str, torch.distributions.constraints.Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)} entropy() [source] expand(batch_shape, _instance=None) [source] property mean support = GreaterThan(lower_bound=0.0) property variance
doc_25915
Return the number of bytes currently in the memory buffer.
doc_25916
A context manager to test that at least one message is logged on the logger or one of its children, with at least the given level. If given, logger should be a logging.Logger object or a str giving the name of a logger. The default is the root logger, which will catch all messages that were not blocked by a non-propagating descendent logger. If given, level should be either a numeric logging level or its string equivalent (for example either "ERROR" or logging.ERROR). The default is logging.INFO. The test passes if at least one message emitted inside the with block matches the logger and level conditions, otherwise it fails. The object returned by the context manager is a recording helper which keeps tracks of the matching log messages. It has two attributes: records A list of logging.LogRecord objects of the matching log messages. output A list of str objects with the formatted output of matching messages. Example: with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message']) New in version 3.4.
doc_25917
Resample an array with steps - 1 points between original point pairs. Along each column of a, (steps - 1) points are introduced between each original values; the values are linearly interpolated. Parameters aarray, shape (n, ...) stepsint Returns array shape ((n - 1) * steps + 1, ...)
doc_25918
Return an iterator of (key, value) pairs. Parameters multi – If set to True the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key.
doc_25919
Alias for get_linestyle.
doc_25920
sklearn.metrics.check_scoring(estimator, scoring=None, *, allow_none=False) [source] Determine scorer from user options. A TypeError will be thrown if the estimator cannot be scored. Parameters estimatorestimator object implementing ‘fit’ The object to use to fit the data. scoringstr or callable, default=None A string (see model evaluation documentation) or a scorer callable object / function with signature scorer(estimator, X, y). allow_nonebool, default=False If no scoring is specified and the estimator has no score function, we can either return None or raise an exception. Returns scoringcallable A scorer callable object / function with signature scorer(estimator, X, y).
doc_25921
Same as st2list(st, line_info, col_info).
doc_25922
Convert an image to 16-bit signed integer format. Parameters imagendarray Input image. force_copybool, optional Force a copy of the data, irrespective of its current dtype. Returns outndarray of int16 Output image. Notes The values are scaled between -32768 and 32767. If the input data-type is positive-only (e.g., uint8), then the output image will still only have positive values.
doc_25923
Return a fully qualified domain name for name. If name is omitted or empty, it is interpreted as the local host. To find the fully qualified name, the hostname returned by gethostbyaddr() is checked, followed by aliases for the host, if available. The first name which includes a period is selected. In case no fully qualified domain name is available, the hostname as returned by gethostname() is returned.
doc_25924
A keyword argument to a function call or class definition. arg is a raw string of the parameter name, value is a node to pass in.
doc_25925
Base observer Module. Any observer implementation should derive from this class. Concrete observers should follow the same API. In forward, they will update the statistics of the observed Tensor. And they should provide a calculate_qparams function that computes the quantization parameters given the collected statistics. Parameters dtype – Quantized data type classmethod with_args(**kwargs) Wrapper that allows creation of class factories. This can be useful when there is a need to create classes with the same constructor arguments, but different instances. Example: >>> Foo.with_args = classmethod(_with_args) >>> foo_builder = Foo.with_args(a=3, b=4).with_args(answer=42) >>> foo_instance1 = foo_builder() >>> foo_instance2 = foo_builder() >>> id(foo_instance1) == id(foo_instance2) False
doc_25926
It’s a relatively common task to check whether a user has a particular permission. For that reason, Django provides a shortcut for that case: the permission_required() decorator.: from django.contrib.auth.decorators import permission_required @permission_required('polls.add_choice') def my_view(request): ... Just like the has_perm() method, permission names take the form "<app label>.<permission codename>" (i.e. polls.add_choice for a permission on a model in the polls application). The decorator may also take an iterable of permissions, in which case the user must have all of the permissions in order to access the view. Note that permission_required() also takes an optional login_url parameter: from django.contrib.auth.decorators import permission_required @permission_required('polls.add_choice', login_url='/loginpage/') def my_view(request): ... As in the login_required() decorator, login_url defaults to settings.LOGIN_URL. If the raise_exception parameter is given, the decorator will raise PermissionDenied, prompting the 403 (HTTP Forbidden) view instead of redirecting to the login page. If you want to use raise_exception but also give your users a chance to login first, you can add the login_required() decorator: from django.contrib.auth.decorators import login_required, permission_required @login_required @permission_required('polls.add_choice', raise_exception=True) def my_view(request): ... This also avoids a redirect loop when LoginView’s redirect_authenticated_user=True and the logged-in user doesn’t have all of the required permissions.
doc_25927
See Migration guide for more details. tf.compat.v1.raw_ops.MatrixDiagPartV3 tf.raw_ops.MatrixDiagPartV3( input, k, padding_value, align='RIGHT_LEFT', name=None ) Returns a tensor with the k[0]-th to k[1]-th diagonals of the batched input. Assume input has r dimensions [I, J, ..., L, M, N]. Let max_diag_len be the maximum length among all diagonals to be extracted, max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0)) Let num_diags be the number of diagonals to extract, num_diags = k[1] - k[0] + 1. If num_diags == 1, the output tensor is of rank r - 1 with shape [I, J, ..., L, max_diag_len] and values: diagonal[i, j, ..., l, n] = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N, padding_value ; otherwise. where y = max(-k[1], 0), x = max(k[1], 0). Otherwise, the output tensor has rank r with dimensions [I, J, ..., L, num_diags, max_diag_len] with values: diagonal[i, j, ..., l, m, n] = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N, padding_value ; otherwise. where d = k[1] - m, y = max(-d, 0) - offset, and x = max(d, 0) - offset. offset is zero except when the alignment of the diagonal is to the right. offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT} and `d >= 0`) or (`align` in {LEFT_RIGHT, RIGHT_RIGHT} and `d <= 0`) 0 ; otherwise where diag_len(d) = min(cols - max(d, 0), rows + min(d, 0)). The input must be at least a matrix. For example: input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4) [5, 6, 7, 8], [9, 8, 7, 6]], [[5, 4, 3, 2], [1, 2, 3, 4], [5, 6, 7, 8]]]) # A main diagonal from each batch. tf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3) [5, 2, 7]] # A superdiagonal from each batch. tf.matrix_diag_part(input, k = 1) ==> [[2, 7, 6], # Output shape: (2, 3) [4, 3, 8]] # A band from each batch. tf.matrix_diag_part(input, k = (-1, 2)) ==> [[[0, 3, 8], # Output shape: (2, 4, 3) [2, 7, 6], [1, 6, 7], [5, 8, 0]], [[0, 3, 4], [4, 3, 8], [5, 2, 7], [1, 6, 0]]] # LEFT_RIGHT alignment. tf.matrix_diag_part(input, k = (-1, 2), align="LEFT_RIGHT") ==> [[[3, 8, 0], # Output shape: (2, 4, 3) [2, 7, 6], [1, 6, 7], [0, 5, 8]], [[3, 4, 0], [4, 3, 8], [5, 2, 7], [0, 1, 6]]] # max_diag_len can be shorter than the main diagonal. tf.matrix_diag_part(input, k = (-2, -1)) ==> [[[5, 8], [9, 0]], [[1, 6], [5, 0]]] # padding_value = 9 tf.matrix_diag_part(input, k = (1, 3), padding_value = 9) ==> [[[9, 9, 4], # Output shape: (2, 3, 3) [9, 3, 8], [2, 7, 6]], [[9, 9, 2], [9, 3, 4], [4, 3, 8]]] Args input A Tensor. Rank r tensor where r >= 2. k A Tensor of type int32. Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main diagonal, and negative value means subdiagonals. k can be a single integer (for a single diagonal) or a pair of integers specifying the low and high ends of a matrix band. k[0] must not be larger than k[1]. padding_value A Tensor. Must have the same type as input. The value to fill the area outside the specified diagonal band with. Default is 0. align An optional string from: "LEFT_RIGHT", "RIGHT_LEFT", "LEFT_LEFT", "RIGHT_RIGHT". Defaults to "RIGHT_LEFT". Some diagonals are shorter than max_diag_len and need to be padded. align is a string specifying how superdiagonals and subdiagonals should be aligned, respectively. There are four possible alignments: "RIGHT_LEFT" (default), "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" aligns superdiagonals to the right (left-pads the row) and subdiagonals to the left (right-pads the row). It is the packing format LAPACK uses. cuSPARSE uses "LEFT_RIGHT", which is the opposite alignment. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
doc_25928
Applies a 3D convolution over a quantized input signal composed of several quantized input planes. For details on input arguments, parameters, and implementation see Conv3d. Note Only zeros is supported for the padding_mode argument. Note Only torch.quint8 is supported for the input data type. Variables ~Conv3d.weight (Tensor) – packed tensor derived from the learnable weight parameter. ~Conv3d.scale (Tensor) – scalar for the output scale ~Conv3d.zero_point (Tensor) – scalar for the output zero point See Conv3d for other attributes. Examples: >>> # With square kernels and equal stride >>> m = nn.quantized.Conv3d(16, 33, 3, stride=2) >>> # non-square kernels and unequal stride and with padding >>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2)) >>> # non-square kernels and unequal stride and with padding and dilation >>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2), dilation=(1, 2, 2)) >>> input = torch.randn(20, 16, 56, 56, 56) >>> # quantize input to quint8 >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) >>> output = m(q_input) classmethod from_float(mod) [source] Creates a quantized module from a float module or qparams_dict. Parameters mod (Module) – a float module, either produced by torch.quantization utilities or provided by the user
doc_25929
Return unique values based on a hash table. Uniques are returned in order of appearance. This does NOT sort. Significantly faster than numpy.unique for long enough sequences. Includes NA values. Parameters values:1d array-like Returns numpy.ndarray or ExtensionArray The return can be: Index : when the input is an Index Categorical : when the input is a Categorical dtype ndarray : when the input is a Series/ndarray Return numpy.ndarray or ExtensionArray. See also Index.unique Return unique values from an Index. Series.unique Return unique values of Series object. Examples >>> pd.unique(pd.Series([2, 1, 3, 3])) array([2, 1, 3]) >>> pd.unique(pd.Series([2] + [1] * 5)) array([2, 1]) >>> pd.unique(pd.Series([pd.Timestamp("20160101"), pd.Timestamp("20160101")])) array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]') >>> pd.unique( ... pd.Series( ... [ ... pd.Timestamp("20160101", tz="US/Eastern"), ... pd.Timestamp("20160101", tz="US/Eastern"), ... ] ... ) ... ) <DatetimeArray> ['2016-01-01 00:00:00-05:00'] Length: 1, dtype: datetime64[ns, US/Eastern] >>> pd.unique( ... pd.Index( ... [ ... pd.Timestamp("20160101", tz="US/Eastern"), ... pd.Timestamp("20160101", tz="US/Eastern"), ... ] ... ) ... ) DatetimeIndex(['2016-01-01 00:00:00-05:00'], dtype='datetime64[ns, US/Eastern]', freq=None) >>> pd.unique(list("baabc")) array(['b', 'a', 'c'], dtype=object) An unordered Categorical will return categories in the order of appearance. >>> pd.unique(pd.Series(pd.Categorical(list("baabc")))) ['b', 'a', 'c'] Categories (3, object): ['a', 'b', 'c'] >>> pd.unique(pd.Series(pd.Categorical(list("baabc"), categories=list("abc")))) ['b', 'a', 'c'] Categories (3, object): ['a', 'b', 'c'] An ordered Categorical preserves the category ordering. >>> pd.unique( ... pd.Series( ... pd.Categorical(list("baabc"), categories=list("abc"), ordered=True) ... ) ... ) ['b', 'a', 'c'] Categories (3, object): ['a' < 'b' < 'c'] An array of tuples >>> pd.unique([("a", "b"), ("b", "a"), ("a", "c"), ("b", "a")]) array([('a', 'b'), ('b', 'a'), ('a', 'c')], dtype=object)
doc_25930
kind = 'hour'
doc_25931
A cache control for requests. This is immutable and gives access to all the request-relevant cache control headers. To get a header of the RequestCacheControl object again you can convert the object into a string or call the to_header() method. If you plan to subclass it and add your own items have a look at the sourcecode for that class. Changelog New in version 0.5: In previous versions a CacheControl class existed that was used both for request and response. no_cache accessor for ‘no-cache’ no_store accessor for ‘no-store’ max_age accessor for ‘max-age’ no_transform accessor for ‘no-transform’ property max_stale accessor for ‘max-stale’ property min_fresh accessor for ‘min-fresh’ property only_if_cached accessor for ‘only-if-cached’
doc_25932
Returns the current GPU memory managed by the caching allocator in bytes for a given device. Parameters device (torch.device or int, optional) – selected device. Returns statistic for the current device, given by current_device(), if device is None (default). Note See Memory management for more details about GPU memory management.
doc_25933
See Migration guide for more details. tf.compat.v1.ragged.segment_ids_to_row_splits tf.ragged.segment_ids_to_row_splits( segment_ids, num_segments=None, out_type=None, name=None ) Returns an integer vector splits, where splits[0] = 0 and splits[i] = splits[i-1] + count(segment_ids==i). Example: print(tf.ragged.segment_ids_to_row_splits([0, 0, 0, 2, 2, 3, 4, 4, 4])) tf.Tensor([0 3 3 5 6 9], shape=(6,), dtype=int64) Args segment_ids A 1-D integer Tensor. num_segments A scalar integer indicating the number of segments. Defaults to max(segment_ids) + 1 (or zero if segment_ids is empty). out_type The dtype for the return value. Defaults to segment_ids.dtype, or tf.int64 if segment_ids does not have a dtype. name A name prefix for the returned tensor (optional). Returns A sorted 1-D integer Tensor, with shape=[num_segments + 1].
doc_25934
Size of the compressed data.
doc_25935
See Migration guide for more details. tf.compat.v1.raw_ops.Prod tf.raw_ops.Prod( input, axis, keep_dims=False, name=None ) Reduces input along the dimensions given in axis. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in axis. If keep_dims is true, the reduced dimensions are retained with length 1. Args input 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. The tensor to reduce. axis A Tensor. Must be one of the following types: int32, int64. The dimensions to reduce. Must be in the range [-rank(input), rank(input)). keep_dims An optional bool. Defaults to False. If true, retain reduced dimensions with length 1. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
doc_25936
Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
doc_25937
Reverse the transformation operation Parameters Xarray of shape [n_samples, n_selected_features] The input samples. Returns X_rarray of shape [n_samples, n_original_features] X with columns of zeros inserted where features would have been removed by transform.
doc_25938
tf.compat.v1.nn.softmax_cross_entropy_with_logits( _sentinel=None, labels=None, logits=None, dim=-1, name=None, axis=None ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Future major versions of TensorFlow will allow gradients to flow into the labels input on backprop by default. See tf.nn.softmax_cross_entropy_with_logits_v2. Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both. Note: While the classes are mutually exclusive, their probabilities need not be. All that is required is that each row of labels is a valid probability distribution. If they are not, the computation of the gradient will be incorrect. If using exclusive labels (wherein one and only one class is true at a time), see sparse_softmax_cross_entropy_with_logits. Warning: This op expects unscaled logits, since it performs a softmax on logits internally for efficiency. Do not call this op with the output of softmax, as it will produce incorrect results. A common use case is to have logits and labels of shape [batch_size, num_classes], but higher dimensions are supported, with the dim argument specifying the class dimension. Backpropagation will happen only into logits. To calculate a cross entropy loss that allows backpropagation into both logits and labels, see tf.nn.softmax_cross_entropy_with_logits_v2. Note that to avoid confusion, it is required to pass only named arguments to this function. Args _sentinel Used to prevent positional parameters. Internal, do not use. labels Each vector along the class dimension should hold a valid probability distribution e.g. for the case in which labels are of shape [batch_size, num_classes], each row of labels[i] must be a valid probability distribution. logits Per-label activations, typically a linear output. These activation energies are interpreted as unnormalized log probabilities. dim The class dimension. Defaulted to -1 which is the last dimension. name A name for the operation (optional). axis Alias for dim. Returns A Tensor that contains the softmax cross entropy loss. Its type is the same as logits and its shape is the same as labels except that it does not have the last dimension of labels.
doc_25939
Create a C runtime file descriptor from the file handle handle. The flags parameter should be a bitwise OR of os.O_APPEND, os.O_RDONLY, and os.O_TEXT. The returned file descriptor may be used as a parameter to os.fdopen() to create a file object. Raises an auditing event msvcrt.open_osfhandle with arguments handle, flags.
doc_25940
tf.experimental.numpy.power( x1, x2 ) Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.power.
doc_25941
Create a shallow copy of the deque. New in version 3.5.
doc_25942
tf.optimizers.Adadelta Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.optimizers.Adadelta tf.keras.optimizers.Adadelta( learning_rate=0.001, rho=0.95, epsilon=1e-07, name='Adadelta', **kwargs ) Adadelta optimization is a stochastic gradient descent method that is based on adaptive learning rate per dimension to address two drawbacks: The continual decay of learning rates throughout training The need for a manually selected global learning rate Adadelta is a more robust extension of Adagrad that adapts learning rates based on a moving window of gradient updates, instead of accumulating all past gradients. This way, Adadelta continues learning even when many updates have been done. Compared to Adagrad, in the original version of Adadelta you don't have to set an initial learning rate. In this version, initial learning rate can be set, as in most other Keras optimizers. According to section 4.3 ("Effective Learning rates"), near the end of training step sizes converge to 1 which is effectively a high learning rate which would cause divergence. This occurs only near the end of the training as gradients and step sizes are small, and the epsilon constant in the numerator and denominator dominate past gradients and parameter updates which converge the learning rate to 1. According to section 4.4("Speech Data"),where a large neural network with 4 hidden layers was trained on a corpus of US English data, ADADELTA was used with 100 network replicas.The epsilon used is 1e-6 with rho=0.95 which converged faster than ADAGRAD, by the following construction: def init(self, lr=1.0, rho=0.95, epsilon=1e-6, decay=0., **kwargs): Args learning_rate A Tensor, floating point value, or a schedule that is a tf.keras.optimizers.schedules.LearningRateSchedule. The learning rate. To match the exact form in the original paper use 1.0. rho A Tensor or a floating point value. The decay rate. epsilon A Tensor or a floating point value. A constant epsilon used to better conditioning the grad update. name Optional name prefix for the operations created when applying gradients. Defaults to "Adadelta". **kwargs Keyword arguments. Allowed to be one of "clipnorm" or "clipvalue". "clipnorm" (float) clips gradients by norm; "clipvalue" (float) clips gradients by value. Reference: Zeiler, 2012 Raises ValueError in case of any invalid argument.
doc_25943
Set the CapStyle for the collection (for all its elements). Parameters csCapStyle or {'butt', 'projecting', 'round'}
doc_25944
See Migration guide for more details. tf.compat.v1.raw_ops.FloorMod tf.raw_ops.FloorMod( x, y, name=None ) true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x. Note: math.floormod supports broadcasting. More about broadcasting here Args x A Tensor. Must be one of the following types: int32, int64, uint64, bfloat16, half, float32, float64. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x.
doc_25945
See Migration guide for more details. tf.compat.v1.signal.ifftshift tf.signal.ifftshift( x, axes=None, name=None ) Although identical for even-length x, the functions differ by one sample for odd-length x. For example: x = tf.signal.ifftshift([[ 0., 1., 2.],[ 3., 4., -4.],[-3., -2., -1.]]) x.numpy() # array([[ 4., -4., 3.],[-2., -1., -3.],[ 1., 2., 0.]]) Args x Tensor, input tensor. axes int or shape tuple Axes over which to calculate. Defaults to None, which shifts all axes. name An optional name for the operation. Returns A Tensor, The shifted tensor. Numpy Compatibility Equivalent to numpy.fft.ifftshift. https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.ifftshift.html
doc_25946
Return True if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.
doc_25947
See Migration guide for more details. tf.compat.v1.raw_ops.TPUReplicatedInput tf.raw_ops.TPUReplicatedInput( inputs, is_mirrored_variable=False, index=-1, is_packed=False, name=None ) This operation holds a replicated input to a tpu.replicate() computation subgraph. Each replicated input has the same shape and type alongside the output. For example: %a = "tf.opA"() %b = "tf.opB"() %replicated_input = "tf.TPUReplicatedInput"(%a, %b) %computation = "tf.Computation"(%replicated_input) The above computation has a replicated input of two replicas. Args inputs A list of at least 1 Tensor objects with the same type. is_mirrored_variable An optional bool. Defaults to False. index An optional int. Defaults to -1. is_packed An optional bool. Defaults to False. name A name for the operation (optional). Returns A Tensor. Has the same type as inputs.
doc_25948
Offset Length Contents 0 4 Chunk ID 4 4 Size of chunk in big-endian byte order, not including the header 8 n Data bytes, where n is the size given in the preceding field 8 + n 0 or 1 Pad byte needed if n is odd and chunk alignment is used The ID is a 4-byte string which identifies the type of chunk. The size field (a 32-bit value, encoded using big-endian byte order) gives the size of the chunk data, not including the 8-byte header. Usually an IFF-type file consists of one or more chunks. The proposed usage of the Chunk class defined here is to instantiate an instance at the start of each chunk and read from the instance until it reaches the end, after which a new instance can be instantiated. At the end of the file, creating a new instance will fail with an EOFError exception. class chunk.Chunk(file, align=True, bigendian=True, inclheader=False) Class which represents a chunk. The file argument is expected to be a file-like object. An instance of this class is specifically allowed. The only method that is needed is read(). If the methods seek() and tell() are present and don’t raise an exception, they are also used. If these methods are present and raise an exception, they are expected to not have altered the object. If the optional argument align is true, chunks are assumed to be aligned on 2-byte boundaries. If align is false, no alignment is assumed. The default value is true. If the optional argument bigendian is false, the chunk size is assumed to be in little-endian order. This is needed for WAVE audio files. The default value is true. If the optional argument inclheader is true, the size given in the chunk header includes the size of the header. The default value is false. A Chunk object supports the following methods: getname() Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk. getsize() Returns the size of the chunk. close() Close and skip to the end of the chunk. This does not close the underlying file. The remaining methods will raise OSError if called after the close() method has been called. Before Python 3.3, they used to raise IOError, now an alias of OSError. isatty() Returns False. seek(pos, whence=0) Set the chunk’s current position. The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file’s end). There is no return value. If the underlying file does not allow seek, only forward seeks are allowed. tell() Return the current position into the chunk. read(size=-1) Read at most size bytes from the chunk (less if the read hits the end of the chunk before obtaining size bytes). If the size argument is negative or omitted, read all data until the end of the chunk. An empty bytes object is returned when the end of the chunk is encountered immediately. skip() Skip to the end of the chunk. All further calls to read() for the chunk will return b''. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk. Footnotes 1 “EA IFF 85” Standard for Interchange Format Files, Jerry Morrison, Electronic Arts, January 1985.
doc_25949
See Migration guide for more details. tf.compat.v1.raw_ops.RandomPoissonV2 tf.raw_ops.RandomPoissonV2( shape, rate, seed=0, seed2=0, dtype=tf.dtypes.int64, name=None ) This op uses two algorithms, depending on rate. If rate >= 10, then the algorithm by Hormann is used to acquire samples via transformation-rejection. See http://www.sciencedirect.com/science/article/pii/0167668793909974 Otherwise, Knuth's algorithm is used to acquire samples via multiplying uniform random variables. See Donald E. Knuth (1969). Seminumerical Algorithms. The Art of Computer Programming, Volume 2. Addison Wesley Args shape A Tensor. Must be one of the following types: int32, int64. 1-D integer tensor. Shape of independent samples to draw from each distribution described by the shape parameters given in rate. rate A Tensor. Must be one of the following types: half, float32, float64, int32, int64. A tensor in which each scalar is a "rate" parameter describing the associated poisson distribution. seed An optional int. Defaults to 0. If either seed or seed2 are set to be non-zero, the random number generator is seeded by the given seed. Otherwise, it is seeded by a random seed. seed2 An optional int. Defaults to 0. A second seed to avoid seed collision. dtype An optional tf.DType from: tf.half, tf.float32, tf.float64, tf.int32, tf.int64. Defaults to tf.int64. name A name for the operation (optional). Returns A Tensor of type dtype.
doc_25950
Set the pick radius used for containment tests. Parameters prfloat Pick radius, in points.
doc_25951
Compute Foerstner corner measure response image. This corner detector uses information from the auto-correlation matrix A: A = [(imx**2) (imx*imy)] = [Axx Axy] [(imx*imy) (imy**2)] [Axy Ayy] Where imx and imy are first derivatives, averaged with a gaussian filter. The corner measure is then defined as: w = det(A) / trace(A) (size of error ellipse) q = 4 * det(A) / trace(A)**2 (roundness of error ellipse) Parameters imagendarray Input image. sigmafloat, optional Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix. Returns wndarray Error ellipse sizes. qndarray Roundness of error ellipse. References 1 Förstner, W., & Gülch, E. (1987, June). A fast operator for detection and precise location of distinct points, corners and centres of circular features. In Proc. ISPRS intercommission conference on fast processing of photogrammetric data (pp. 281-305). https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf 2 https://en.wikipedia.org/wiki/Corner_detection Examples >>> from skimage.feature import corner_foerstner, corner_peaks >>> square = np.zeros([10, 10]) >>> square[2:8, 2:8] = 1 >>> square.astype(int) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> w, q = corner_foerstner(square) >>> accuracy_thresh = 0.5 >>> roundness_thresh = 0.3 >>> foerstner = (q > roundness_thresh) * (w > accuracy_thresh) * w >>> corner_peaks(foerstner, min_distance=1) array([[2, 2], [2, 7], [7, 2], [7, 7]])
doc_25952
Constructor for an unbounded FIFO queue. Simple queues lack advanced functionality such as task tracking. New in version 3.7.
doc_25953
make custom user event type custom_type() -> int Reserves a pygame.USEREVENT for a custom use. If too many events are made a pygame.error is raised. New in pygame 2.0.0.dev3.
doc_25954
exception xml.parsers.expat.ExpatError The exception raised when Expat reports an error. See section ExpatError Exceptions for more information on interpreting Expat errors. exception xml.parsers.expat.error Alias for ExpatError. xml.parsers.expat.XMLParserType The type of the return values from the ParserCreate() function. The xml.parsers.expat module contains two functions: xml.parsers.expat.ErrorString(errno) Returns an explanatory string for a given error number errno. xml.parsers.expat.ParserCreate(encoding=None, namespace_separator=None) Creates and returns a new xmlparser object. encoding, if specified, must be a string naming the encoding used by the XML data. Expat doesn’t support as many encodings as Python does, and its repertoire of encodings can’t be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII. If encoding 1 is given it will override the implicit or explicit encoding of the document. Expat can optionally do XML namespace processing for you, enabled by providing a value for namespace_separator. The value must be a one-character string; a ValueError will be raised if the string has an illegal length (None is considered the same as omission). When namespace processing is enabled, element type names and attribute names that belong to a namespace will be expanded. The element name passed to the element handlers StartElementHandler and EndElementHandler will be the concatenation of the namespace URI, the namespace separator character, and the local part of the name. If the namespace separator is a zero byte (chr(0)) then the namespace URI and the local part will be concatenated without any separator. For example, if namespace_separator is set to a space character (' ') and the following document is parsed: <?xml version="1.0"?> <root xmlns = "http://default-namespace.org/" xmlns:py = "http://www.python.org/ns/"> <py:elem1 /> <elem2 xmlns="" /> </root> StartElementHandler will receive the following strings for each element: http://default-namespace.org/ root http://www.python.org/ns/ elem1 elem2 Due to limitations in the Expat library used by pyexpat, the xmlparser instance returned can only be used to parse a single XML document. Call ParserCreate for each document to provide unique parser instances. See also The Expat XML Parser Home page of the Expat project. XMLParser Objects xmlparser objects have the following methods: xmlparser.Parse(data[, isfinal]) Parses the contents of the string data, calling the appropriate handler functions to process the parsed data. isfinal must be true on the final call to this method; it allows the parsing of a single file in fragments, not the submission of multiple files. data can be the empty string at any time. xmlparser.ParseFile(file) Parse XML data reading from the object file. file only needs to provide the read(nbytes) method, returning the empty string when there’s no more data. xmlparser.SetBase(base) Sets the base to be used for resolving relative URIs in system identifiers in declarations. Resolving relative identifiers is left to the application: this value will be passed through as the base argument to the ExternalEntityRefHandler(), NotationDeclHandler(), and UnparsedEntityDeclHandler() functions. xmlparser.GetBase() Returns a string containing the base set by a previous call to SetBase(), or None if SetBase() hasn’t been called. xmlparser.GetInputContext() Returns the input data that generated the current event as a string. The data is in the encoding of the entity which contains the text. When called while an event handler is not active, the return value is None. xmlparser.ExternalEntityParserCreate(context[, encoding]) Create a “child” parser which can be used to parse an external parsed entity referred to by content parsed by the parent parser. The context parameter should be the string passed to the ExternalEntityRefHandler() handler function, described below. The child parser is created with the ordered_attributes and specified_attributes set to the values of this parser. xmlparser.SetParamEntityParsing(flag) Control parsing of parameter entities (including the external DTD subset). Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER, XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and XML_PARAM_ENTITY_PARSING_ALWAYS. Return true if setting the flag was successful. xmlparser.UseForeignDTD([flag]) Calling this with a true value for flag (the default) will cause Expat to call the ExternalEntityRefHandler with None for all arguments to allow an alternate DTD to be loaded. If the document does not contain a document type declaration, the ExternalEntityRefHandler will still be called, but the StartDoctypeDeclHandler and EndDoctypeDeclHandler will not be called. Passing a false value for flag will cancel a previous call that passed a true value, but otherwise has no effect. This method can only be called before the Parse() or ParseFile() methods are called; calling it after either of those have been called causes ExpatError to be raised with the code attribute set to errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]. xmlparser objects have the following attributes: xmlparser.buffer_size The size of the buffer used when buffer_text is true. A new buffer size can be set by assigning a new integer value to this attribute. When the size is changed, the buffer will be flushed. xmlparser.buffer_text Setting this to true causes the xmlparser object to buffer textual content returned by Expat to avoid multiple calls to the CharacterDataHandler() callback whenever possible. This can improve performance substantially since Expat normally breaks character data into chunks at every line ending. This attribute is false by default, and may be changed at any time. xmlparser.buffer_used If buffer_text is enabled, the number of bytes stored in the buffer. These bytes represent UTF-8 encoded text. This attribute has no meaningful interpretation when buffer_text is false. xmlparser.ordered_attributes Setting this attribute to a non-zero integer causes the attributes to be reported as a list rather than a dictionary. The attributes are presented in the order found in the document text. For each attribute, two list entries are presented: the attribute name and the attribute value. (Older versions of this module also used this format.) By default, this attribute is false; it may be changed at any time. xmlparser.specified_attributes If set to a non-zero integer, the parser will report only those attributes which were specified in the document instance and not those which were derived from attribute declarations. Applications which set this need to be especially careful to use what additional information is available from the declarations as needed to comply with the standards for the behavior of XML processors. By default, this attribute is false; it may be changed at any time. The following attributes contain values relating to the most recent error encountered by an xmlparser object, and will only have correct values once a call to Parse() or ParseFile() has raised an xml.parsers.expat.ExpatError exception. xmlparser.ErrorByteIndex Byte index at which an error occurred. xmlparser.ErrorCode Numeric code specifying the problem. This value can be passed to the ErrorString() function, or compared to one of the constants defined in the errors object. xmlparser.ErrorColumnNumber Column number at which an error occurred. xmlparser.ErrorLineNumber Line number at which an error occurred. The following attributes contain values relating to the current parse location in an xmlparser object. During a callback reporting a parse event they indicate the location of the first of the sequence of characters that generated the event. When called outside of a callback, the position indicated will be just past the last parse event (regardless of whether there was an associated callback). xmlparser.CurrentByteIndex Current byte index in the parser input. xmlparser.CurrentColumnNumber Current column number in the parser input. xmlparser.CurrentLineNumber Current line number in the parser input. Here is the list of handlers that can be set. To set a handler on an xmlparser object o, use o.handlername = func. handlername must be taken from the following list, and func must be a callable object accepting the correct number of arguments. The arguments are all strings, unless otherwise stated. xmlparser.XmlDeclHandler(version, encoding, standalone) Called when the XML declaration is parsed. The XML declaration is the (optional) declaration of the applicable version of the XML recommendation, the encoding of the document text, and an optional “standalone” declaration. version and encoding will be strings, and standalone will be 1 if the document is declared standalone, 0 if it is declared not to be standalone, or -1 if the standalone clause was omitted. This is only available with Expat version 1.95.0 or newer. xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset) Called when Expat begins parsing the document type declaration (<!DOCTYPE ...). The doctypeName is provided exactly as presented. The systemId and publicId parameters give the system and public identifiers if specified, or None if omitted. has_internal_subset will be true if the document contains and internal document declaration subset. This requires Expat version 1.2 or newer. xmlparser.EndDoctypeDeclHandler() Called when Expat is done parsing the document type declaration. This requires Expat version 1.2 or newer. xmlparser.ElementDeclHandler(name, model) Called once for each element type declaration. name is the name of the element type, and model is a representation of the content model. xmlparser.AttlistDeclHandler(elname, attname, type, default, required) Called for each declared attribute for an element type. If an attribute list declaration declares three attributes, this handler is called three times, once for each attribute. elname is the name of the element to which the declaration applies and attname is the name of the attribute declared. The attribute type is a string passed as type; the possible values are 'CDATA', 'ID', 'IDREF', … default gives the default value for the attribute used when the attribute is not specified by the document instance, or None if there is no default value (#IMPLIED values). If the attribute is required to be given in the document instance, required will be true. This requires Expat version 1.95.0 or newer. xmlparser.StartElementHandler(name, attributes) Called for the start of every element. name is a string containing the element name, and attributes is the element attributes. If ordered_attributes is true, this is a list (see ordered_attributes for a full description). Otherwise it’s a dictionary mapping names to values. xmlparser.EndElementHandler(name) Called for the end of every element. xmlparser.ProcessingInstructionHandler(target, data) Called for every processing instruction. xmlparser.CharacterDataHandler(data) Called for character data. This will be called for normal character data, CDATA marked content, and ignorable whitespace. Applications which must distinguish these cases can use the StartCdataSectionHandler, EndCdataSectionHandler, and ElementDeclHandler callbacks to collect the required information. xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName) Called for unparsed (NDATA) entity declarations. This is only present for version 1.2 of the Expat library; for more recent versions, use EntityDeclHandler instead. (The underlying function in the Expat library has been declared obsolete.) xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName) Called for all entity declarations. For parameter and internal entities, value will be a string giving the declared contents of the entity; this will be None for external entities. The notationName parameter will be None for parsed entities, and the name of the notation for unparsed entities. is_parameter_entity will be true if the entity is a parameter entity or false for general entities (most applications only need to be concerned with general entities). This is only available starting with version 1.95.0 of the Expat library. xmlparser.NotationDeclHandler(notationName, base, systemId, publicId) Called for notation declarations. notationName, base, and systemId, and publicId are strings if given. If the public identifier is omitted, publicId will be None. xmlparser.StartNamespaceDeclHandler(prefix, uri) Called when an element contains a namespace declaration. Namespace declarations are processed before the StartElementHandler is called for the element on which declarations are placed. xmlparser.EndNamespaceDeclHandler(prefix) Called when the closing tag is reached for an element that contained a namespace declaration. This is called once for each namespace declaration on the element in the reverse of the order for which the StartNamespaceDeclHandler was called to indicate the start of each namespace declaration’s scope. Calls to this handler are made after the corresponding EndElementHandler for the end of the element. xmlparser.CommentHandler(data) Called for comments. data is the text of the comment, excluding the leading '<!--' and trailing '-->'. xmlparser.StartCdataSectionHandler() Called at the start of a CDATA section. This and EndCdataSectionHandler are needed to be able to identify the syntactical start and end for CDATA sections. xmlparser.EndCdataSectionHandler() Called at the end of a CDATA section. xmlparser.DefaultHandler(data) Called for any characters in the XML document for which no applicable handler has been specified. This means characters that are part of a construct which could be reported, but for which no handler has been supplied. xmlparser.DefaultHandlerExpand(data) This is the same as the DefaultHandler(), but doesn’t inhibit expansion of internal entities. The entity reference will not be passed to the default handler. xmlparser.NotStandaloneHandler() Called if the XML document hasn’t been declared as being a standalone document. This happens when there is an external subset or a reference to a parameter entity, but the XML declaration does not set standalone to yes in an XML declaration. If this handler returns 0, then the parser will raise an XML_ERROR_NOT_STANDALONE error. If this handler is not set, no exception is raised by the parser for this condition. xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId) Called for references to external entities. base is the current base, as set by a previous call to SetBase(). The public and system identifiers, systemId and publicId, are strings if given; if the public identifier is not given, publicId will be None. The context value is opaque and should only be used as described below. For external entities to be parsed, this handler must be implemented. It is responsible for creating the sub-parser using ExternalEntityParserCreate(context), initializing it with the appropriate callbacks, and parsing the entity. This handler should return an integer; if it returns 0, the parser will raise an XML_ERROR_EXTERNAL_ENTITY_HANDLING error, otherwise parsing will continue. If this handler is not provided, external entities are reported by the DefaultHandler callback, if provided. ExpatError Exceptions ExpatError exceptions have a number of interesting attributes: ExpatError.code Expat’s internal error number for the specific error. The errors.messages dictionary maps these error numbers to Expat’s error messages. For example: from xml.parsers.expat import ParserCreate, ExpatError, errors p = ParserCreate() try: p.Parse(some_xml_document) except ExpatError as err: print("Error:", errors.messages[err.code]) The errors module also provides error message constants and a dictionary codes mapping these messages back to the error codes, see below. ExpatError.lineno Line number on which the error was detected. The first line is numbered 1. ExpatError.offset Character offset into the line where the error occurred. The first column is numbered 0. Example The following program defines three handlers that just print out their arguments. import xml.parsers.expat # 3 handler functions def start_element(name, attrs): print('Start element:', name, attrs) def end_element(name): print('End element:', name) def char_data(data): print('Character data:', repr(data)) p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data p.Parse("""<?xml version="1.0"?> <parent id="top"><child1 name="paul">Text goes here</child1> <child2 name="fred">More text</child2> </parent>""", 1) The output from this program is: Start element: parent {'id': 'top'} Start element: child1 {'name': 'paul'} Character data: 'Text goes here' End element: child1 Character data: '\n' Start element: child2 {'name': 'fred'} Character data: 'More text' End element: child2 Character data: '\n' End element: parent Content Model Descriptions Content models are described using nested tuples. Each tuple contains four values: the type, the quantifier, the name, and a tuple of children. Children are simply additional content model descriptions. The values of the first two fields are constants defined in the xml.parsers.expat.model module. These constants can be collected in two groups: the model type group and the quantifier group. The constants in the model type group are: xml.parsers.expat.model.XML_CTYPE_ANY The element named by the model name was declared to have a content model of ANY. xml.parsers.expat.model.XML_CTYPE_CHOICE The named element allows a choice from a number of options; this is used for content models such as (A | B | C). xml.parsers.expat.model.XML_CTYPE_EMPTY Elements which are declared to be EMPTY have this model type. xml.parsers.expat.model.XML_CTYPE_MIXED xml.parsers.expat.model.XML_CTYPE_NAME xml.parsers.expat.model.XML_CTYPE_SEQ Models which represent a series of models which follow one after the other are indicated with this model type. This is used for models such as (A, B, C). The constants in the quantifier group are: xml.parsers.expat.model.XML_CQUANT_NONE No modifier is given, so it can appear exactly once, as for A. xml.parsers.expat.model.XML_CQUANT_OPT The model is optional: it can appear once or not at all, as for A?. xml.parsers.expat.model.XML_CQUANT_PLUS The model must occur one or more times (like A+). xml.parsers.expat.model.XML_CQUANT_REP The model must occur zero or more times, as for A*. Expat error constants The following constants are provided in the xml.parsers.expat.errors module. These constants are useful in interpreting some of the attributes of the ExpatError exception objects raised when an error has occurred. Since for backwards compatibility reasons, the constants’ value is the error message and not the numeric error code, you do this by comparing its code attribute with errors.codes[errors.XML_ERROR_CONSTANT_NAME]. The errors module has the following attributes: xml.parsers.expat.errors.codes A dictionary mapping string descriptions to their error codes. New in version 3.2. xml.parsers.expat.errors.messages A dictionary mapping numeric error codes to their string descriptions. New in version 3.2. xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF An entity reference in an attribute value referred to an external entity instead of an internal entity. xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF A character reference referred to a character which is illegal in XML (for example, character 0, or ‘&#0;’). xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF An entity reference referred to an entity which was declared with a notation, so cannot be parsed. xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE An attribute was used more than once in a start tag. xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN Raised when an input byte could not properly be assigned to a character; for example, a NUL byte (value 0) in a UTF-8 input stream. xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT Something other than whitespace occurred after the document element. xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI An XML declaration was found somewhere other than the start of the input data. xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS The document contains no elements (XML requires all documents to contain exactly one top-level element).. xml.parsers.expat.errors.XML_ERROR_NO_MEMORY Expat was not able to allocate memory internally. xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF A parameter entity reference was found where it was not allowed. xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR An incomplete character was found in the input. xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF An entity reference contained another reference to the same entity; possibly via a different name, and possibly indirectly. xml.parsers.expat.errors.XML_ERROR_SYNTAX Some unspecified syntax error was encountered. xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH An end tag did not match the innermost open start tag. xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN Some token (such as a start tag) was not closed before the end of the stream or the next token was encountered. xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY A reference was made to an entity which was not defined. xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING The document encoding is not supported by Expat. xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION A CDATA marked section was not closed. xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE The parser determined that the document was not “standalone” though it declared itself to be in the XML declaration, and the NotStandaloneHandler was set and returned 0. xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD An operation was requested that requires DTD support to be compiled in, but Expat was configured without DTD support. This should never be reported by a standard build of the xml.parsers.expat module. xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING A behavioral change was requested after parsing started that can only be changed before parsing has started. This is (currently) only raised by UseForeignDTD(). xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX An undeclared prefix was found when namespace processing was enabled. xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX The document attempted to remove the namespace declaration associated with a prefix. xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE A parameter entity contained incomplete markup. xml.parsers.expat.errors.XML_ERROR_XML_DECL The document contained no document element at all. xml.parsers.expat.errors.XML_ERROR_TEXT_DECL There was an error parsing a text declaration in an external entity. xml.parsers.expat.errors.XML_ERROR_PUBLICID Characters were found in the public id that are not allowed. xml.parsers.expat.errors.XML_ERROR_SUSPENDED The requested operation was made on a suspended parser, but isn’t allowed. This includes attempts to provide additional input or to stop the parser. xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED An attempt to resume the parser was made when the parser had not been suspended. xml.parsers.expat.errors.XML_ERROR_ABORTED This should not be reported to Python applications. xml.parsers.expat.errors.XML_ERROR_FINISHED The requested operation was made on a parser which was finished parsing input, but isn’t allowed. This includes attempts to provide additional input or to stop the parser. xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE Footnotes 1 The encoding string included in XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl and https://www.iana.org/assignments/character-sets/character-sets.xhtml.
doc_25955
Subclass of xml.sax.handler.ContentHandler.
doc_25956
Equalize image using local histogram. 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. Examples >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import equalize >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> equ = equalize(img, disk(5)) >>> equ_vol = equalize(volume, ball(5))
doc_25957
See Migration guide for more details. tf.compat.v1.raw_ops.ReaderRead tf.raw_ops.ReaderRead( reader_handle, queue_handle, name=None ) Will dequeue from the input queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file). Args reader_handle A Tensor of type mutable string. Handle to a Reader. queue_handle A Tensor of type mutable string. Handle to a Queue, with string work items. name A name for the operation (optional). Returns A tuple of Tensor objects (key, value). key A Tensor of type string. value A Tensor of type string.
doc_25958
See Migration guide for more details. tf.compat.v1.raw_ops.RequantizePerChannel tf.raw_ops.RequantizePerChannel( input, input_min, input_max, requested_output_min, requested_output_max, out_type=tf.dtypes.quint8, name=None ) Args input A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. The original input tensor. input_min A Tensor of type float32. The minimum value of the input tensor input_max A Tensor of type float32. The maximum value of the input tensor. requested_output_min A Tensor of type float32. The minimum value of the output tensor requested. requested_output_max A Tensor of type float32. The maximum value of the output tensor requested. out_type An optional tf.DType from: tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16. Defaults to tf.quint8. The quantized type of output tensor that needs to be converted. name A name for the operation (optional). Returns A tuple of Tensor objects (output, output_min, output_max). output A Tensor of type out_type. output_min A Tensor of type float32. output_max A Tensor of type float32.
doc_25959
Restore the terminal to “shell” mode, as previously saved by def_shell_mode().
doc_25960
Call the function (a function or method object, not a string) with the given arguments. When runcall() returns, it returns whatever the function call returned. The debugger prompt appears as soon as the function is entered.
doc_25961
Remove the event from the queue. If event is not an event currently in the queue, this method will raise a ValueError.
doc_25962
Set an ACL for mailbox. The method is non-standard, but is supported by the Cyrus server.
doc_25963
See Migration guide for more details. tf.compat.v1.raw_ops.Tan tf.raw_ops.Tan( x, name=None ) Given an input tensor, this function computes tangent of every element in the tensor. Input range is (-inf, inf) and output range is (-inf, inf). If input lies outside the boundary, nan is returned. x = tf.constant([-float("inf"), -9, -0.5, 1, 1.2, 200, 10000, float("inf")]) tf.math.tan(x) ==> [nan 0.45231566 -0.5463025 1.5574077 2.572152 -1.7925274 0.32097113 nan] Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, int8, int16, int32, int64, complex64, complex128. name A name for the operation (optional). Returns A Tensor. Has the same type as x.
doc_25964
Applies a multi-layer Elman RNN with tanh⁡\tanh or ReLU\text{ReLU} non-linearity to an input sequence. For each element in the input sequence, each layer computes the following function: ht=tanh⁡(Wihxt+bih+Whhh(t−1)+bhh)h_t = \tanh(W_{ih} x_t + b_{ih} + W_{hh} h_{(t-1)} + b_{hh}) where hth_t is the hidden state at time t, xtx_t is the input at time t, and h(t−1)h_{(t-1)} is the hidden state of the previous layer at time t-1 or the initial hidden state at time 0. If nonlinearity is 'relu', then ReLU\text{ReLU} is used instead of tanh⁡\tanh . Parameters input_size – The number of expected features in the input x hidden_size – The number of features in the hidden state h num_layers – Number of recurrent layers. E.g., setting num_layers=2 would mean stacking two RNNs together to form a stacked RNN, with the second RNN taking in outputs of the first RNN and computing the final results. Default: 1 nonlinearity – The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh' bias – If False, then the layer does not use bias weights b_ih and b_hh. Default: True batch_first – If True, then the input and output tensors are provided as (batch, seq, feature). Default: False dropout – If non-zero, introduces a Dropout layer on the outputs of each RNN layer except the last layer, with dropout probability equal to dropout. Default: 0 bidirectional – If True, becomes a bidirectional RNN. Default: False Inputs: input, h_0 input of shape (seq_len, batch, input_size): tensor containing the features of the input sequence. The input can also be a packed variable length sequence. See torch.nn.utils.rnn.pack_padded_sequence() or torch.nn.utils.rnn.pack_sequence() for details. h_0 of shape (num_layers * num_directions, batch, hidden_size): tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1. Outputs: output, h_n output of shape (seq_len, batch, num_directions * hidden_size): tensor containing the output features (h_t) from the last layer of the RNN, for each t. If a torch.nn.utils.rnn.PackedSequence has been given as the input, the output will also be a packed sequence. For the unpacked case, the directions can be separated using output.view(seq_len, batch, num_directions, hidden_size), with forward and backward being direction 0 and 1 respectively. Similarly, the directions can be separated in the packed case. h_n of shape (num_layers * num_directions, batch, hidden_size): tensor containing the hidden state for t = seq_len. Like output, the layers can be separated using h_n.view(num_layers, num_directions, batch, hidden_size). Shape: Input1: (L,N,Hin)(L, N, H_{in}) tensor containing input features where Hin=input_sizeH_{in}=\text{input\_size} and L represents a sequence length. Input2: (S,N,Hout)(S, N, H_{out}) tensor containing the initial hidden state for each element in the batch. Hout=hidden_sizeH_{out}=\text{hidden\_size} Defaults to zero if not provided. where S=num_layers∗num_directionsS=\text{num\_layers} * \text{num\_directions} If the RNN is bidirectional, num_directions should be 2, else it should be 1. Output1: (L,N,Hall)(L, N, H_{all}) where Hall=num_directions∗hidden_sizeH_{all}=\text{num\_directions} * \text{hidden\_size} Output2: (S,N,Hout)(S, N, H_{out}) tensor containing the next hidden state for each element in the batch Variables ~RNN.weight_ih_l[k] – the learnable input-hidden weights of the k-th layer, of shape (hidden_size, input_size) for k = 0. Otherwise, the shape is (hidden_size, num_directions * hidden_size) ~RNN.weight_hh_l[k] – the learnable hidden-hidden weights of the k-th layer, of shape (hidden_size, hidden_size) ~RNN.bias_ih_l[k] – the learnable input-hidden bias of the k-th layer, of shape (hidden_size) ~RNN.bias_hh_l[k] – the learnable hidden-hidden bias of the k-th layer, of shape (hidden_size) Note All the weights and biases are initialized from U(−k,k)\mathcal{U}(-\sqrt{k}, \sqrt{k}) where k=1hidden_sizek = \frac{1}{\text{hidden\_size}} Warning There are known non-determinism issues for RNN functions on some versions of cuDNN and CUDA. You can enforce deterministic behavior by setting the following environment variables: On CUDA 10.1, set environment variable CUDA_LAUNCH_BLOCKING=1. This may affect performance. On CUDA 10.2 or later, set environment variable (note the leading colon symbol) CUBLAS_WORKSPACE_CONFIG=:16:8 or CUBLAS_WORKSPACE_CONFIG=:4096:2. See the cuDNN 8 Release Notes for more information. Orphan Note If the following conditions are satisfied: 1) cudnn is enabled, 2) input data is on the GPU 3) input data has dtype torch.float16 4) V100 GPU is used, 5) input data is not in PackedSequence format persistent algorithm can be selected to improve performance. Examples: >>> rnn = nn.RNN(10, 20, 2) >>> input = torch.randn(5, 3, 10) >>> h0 = torch.randn(2, 3, 20) >>> output, hn = rnn(input, h0)
doc_25965
Applies the logical operation or between each operand’s digits.
doc_25966
tf.compat.v1.profiler.profile( graph=None, run_meta=None, op_log=None, cmd='scope', options=_DEFAULT_PROFILE_OPTIONS ) Tutorials and examples can be found in: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/profiler/g3doc/python_api.md Args graph tf.Graph. If None and eager execution is not enabled, use default graph. run_meta optional tensorflow.RunMetadata proto. It is necessary to to support run time information profiling, such as time and memory. op_log tensorflow.tfprof.OpLogProto proto. User can assign "types" to graph nodes with op_log. "types" allow user to flexibly group and account profiles using options['accounted_type_regexes']. cmd string. Either 'op', 'scope', 'graph' or 'code'. 'op' view organizes profile using operation type. (e.g. MatMul) 'scope' view organizes profile using graph node name scope. 'graph' view organizes profile using graph node inputs/outputs. 'code' view organizes profile using Python call stack. options A dict of options. See core/profiler/g3doc/options.md. Returns If cmd is 'scope' or 'graph', returns GraphNodeProto proto. If cmd is 'op' or 'code', returns MultiGraphNodeProto proto. Side effect: stdout/file/timeline.json depending on options['output']
doc_25967
Returns float The inner radial limit.
doc_25968
A string denoting the charset in which the response will be encoded. If not given at HttpResponse instantiation time, it will be extracted from content_type and if that is unsuccessful, the DEFAULT_CHARSET setting will be used.
doc_25969
Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as an optional, short, human readable description of the error. The explain argument can be used to provide more detailed information about the error; it will be formatted using the error_message_format attribute and emitted, after a complete set of headers, as the response body. The responses attribute holds the default values for message and explain that will be used if no value is provided; for unknown codes the default value for both is the string ???. The body will be empty if the method is HEAD or the response code is one of the following: 1xx, 204 No Content, 205 Reset Content, 304 Not Modified. Changed in version 3.4: The error response includes a Content-Length header. Added the explain argument.
doc_25970
tf.compat.v1.nn.xw_plus_b( x, weights, biases, name=None ) Args x a 2D tensor. Dimensions typically: batch, in_units weights a 2D tensor. Dimensions typically: in_units, out_units biases a 1D tensor. Dimensions: out_units name A name for the operation (optional). If not specified "xw_plus_b" is used. Returns A 2-D Tensor computing matmul(x, weights) + biases. Dimensions typically: batch, out_units.
doc_25971
Create a code object from Python source. The data argument can be whatever the compile() function supports (i.e. string or bytes). The path argument should be the “path” to where the source code originated from, which can be an abstract concept (e.g. location in a zip file). With the subsequent code object one can execute it in a module by running exec(code, module.__dict__). New in version 3.4. Changed in version 3.5: Made the method static.
doc_25972
Return the lower and upper x-axis bounds, in increasing order. See also set_xbound get_xlim, set_xlim invert_xaxis, xaxis_inverted
doc_25973
Natural logarithm, element-wise. The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e. Parameters xarray_like Input value. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray The natural logarithm of x, element-wise. This is a scalar if x is a scalar. See also log10, log2, log1p, emath.log Notes Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, log is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. References 1 M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 67. https://personal.math.ubc.ca/~cbm/aands/page_67.htm 2 Wikipedia, “Logarithm”. https://en.wikipedia.org/wiki/Logarithm Examples >>> np.log([1, np.e, np.e**2, 0]) array([ 0., 1., 2., -Inf])
doc_25974
Alias for set_antialiased.
doc_25975
Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the feature_namespaces feature is enabled (the default). There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the startPrefixMapping() and endPrefixMapping() events supply the information to the application to expand prefixes in those contexts itself, if necessary. Note that startPrefixMapping() and endPrefixMapping() events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping() events will occur before the corresponding startElement() event, and all endPrefixMapping() events will occur after the corresponding endElement() event, but their order is not guaranteed.
doc_25976
Return the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function. If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar. Parameters none Returns yobject, or list of object, or list of list of object, or … The possibly nested list of array elements. Notes The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision. Examples For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2]) >>> a_list = list(a) >>> a_list [1, 2] >>> type(a_list[0]) <class 'numpy.uint32'> >>> a_tolist = a.tolist() >>> a_tolist [1, 2] >>> type(a_tolist[0]) <class 'int'> Additionally, for a 2D array, tolist applies recursively: >>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]] The base case for this recursion is a 0D array: >>> a = np.array(1) >>> list(a) Traceback (most recent call last): ... TypeError: iteration over a 0-d array >>> a.tolist() 1
doc_25977
See Migration guide for more details. tf.compat.v1.errors.DeadlineExceededError tf.errors.DeadlineExceededError( node_def, op, message ) This exception is not currently used. Attributes error_code The integer error code that describes the error. message The error message that describes the error. node_def The NodeDef proto representing the op that failed. op The operation that failed, if known. Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.
doc_25978
Tests if all elements in input evaluate to True. Note This function matches the behaviour of NumPy in returning output of dtype bool for all supported dtypes except uint8. For uint8 the dtype of output is uint8 itself. Example: >>> a = torch.rand(1, 2).bool() >>> a tensor([[False, True]], dtype=torch.bool) >>> torch.all(a) tensor(False, dtype=torch.bool) >>> a = torch.arange(0, 3) >>> a tensor([0, 1, 2]) >>> torch.all(a) tensor(False) torch.all(input, dim, keepdim=False, *, out=None) → Tensor For each row of input in the given dimension dim, returns True if all elements in the row evaluate to True and False otherwise. If keepdim is True, the output tensor is of the same size as input except in the dimension dim where it is of size 1. Otherwise, dim is squeezed (see torch.squeeze()), resulting in the output tensor having 1 fewer dimension than input. Parameters input (Tensor) – the input tensor. dim (int) – the dimension to reduce. keepdim (bool) – whether the output tensor has dim retained or not. Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a = torch.rand(4, 2).bool() >>> a tensor([[True, True], [True, False], [True, True], [True, True]], dtype=torch.bool) >>> torch.all(a, dim=1) tensor([ True, False, True, True], dtype=torch.bool) >>> torch.all(a, dim=0) tensor([ True, False], dtype=torch.bool)
doc_25979
alias of matplotlib.backends.backend_agg.FigureCanvasAgg
doc_25980
get the color index palette for an 8-bit Surface get_palette() -> [RGB, RGB, RGB, ...] Return a list of up to 256 color elements that represent the indexed colors used in an 8-bit Surface. The returned list is a copy of the palette, and changes will have no effect on the Surface. Returning a list of Color(with length 3) instances instead of tuples. New in pygame 1.9.
doc_25981
Return the scaled companion matrix of c. The basis polynomials are scaled so that the companion matrix is symmetric when c is an Hermite basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if numpy.linalg.eigvalsh is used to obtain them. Parameters carray_like 1-D array of Hermite series coefficients ordered from low to high degree. Returns matndarray Scaled companion matrix of dimensions (deg, deg). Notes New in version 1.7.0.
doc_25982
The same as http_error_301(), but called for the ‘temporary redirect’ response.
doc_25983
See Migration guide for more details. tf.compat.v1.raw_ops.StatelessParameterizedTruncatedNormal tf.raw_ops.StatelessParameterizedTruncatedNormal( shape, seed, means, stddevs, minvals, maxvals, name=None ) Args shape A Tensor. Must be one of the following types: int32, int64. The shape of the output tensor. seed A Tensor. Must be one of the following types: int32, int64. 2 seeds (shape [2]). means A Tensor. Must be one of the following types: half, float32, float64. The mean parameter of each batch. stddevs A Tensor. Must have the same type as means. The standard deviation parameter of each batch. Must be greater than 0. minvals A Tensor. Must have the same type as means. The minimum cutoff. May be -infinity. maxvals A Tensor. Must have the same type as means. The maximum cutoff. May be +infinity, and must be more than the minval for each batch. name A name for the operation (optional). Returns A Tensor. Has the same type as means.
doc_25984
Set list_max_show_all to control how many items can appear on a “Show all” admin change list page. The admin will display a “Show all” link on the change list only if the total result count is less than or equal to this setting. By default, this is set to 200.
doc_25985
Data loader. Combines a dataset and a sampler, and provides an iterable over the given dataset. The DataLoader supports both map-style and iterable-style datasets with single- or multi-process loading, customizing loading order and optional automatic batching (collation) and memory pinning. See torch.utils.data documentation page for more details. Parameters dataset (Dataset) – dataset from which to load the data. batch_size (int, optional) – how many samples per batch to load (default: 1). shuffle (bool, optional) – set to True to have the data reshuffled at every epoch (default: False). sampler (Sampler or Iterable, optional) – defines the strategy to draw samples from the dataset. Can be any Iterable with __len__ implemented. If specified, shuffle must not be specified. batch_sampler (Sampler or Iterable, optional) – like sampler, but returns a batch of indices at a time. Mutually exclusive with batch_size, shuffle, sampler, and drop_last. num_workers (int, optional) – how many subprocesses to use for data loading. 0 means that the data will be loaded in the main process. (default: 0) collate_fn (callable, optional) – merges a list of samples to form a mini-batch of Tensor(s). Used when using batched loading from a map-style dataset. pin_memory (bool, optional) – If True, the data loader will copy Tensors into CUDA pinned memory before returning them. If your data elements are a custom type, or your collate_fn returns a batch that is a custom type, see the example below. drop_last (bool, optional) – set to True to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If False and the size of dataset is not divisible by the batch size, then the last batch will be smaller. (default: False) timeout (numeric, optional) – if positive, the timeout value for collecting a batch from workers. Should always be non-negative. (default: 0) worker_init_fn (callable, optional) – If not None, this will be called on each worker subprocess with the worker id (an int in [0, num_workers - 1]) as input, after seeding and before data loading. (default: None) prefetch_factor (int, optional, keyword-only arg) – Number of samples loaded in advance by each worker. 2 means there will be a total of 2 * num_workers samples prefetched across all workers. (default: 2) persistent_workers (bool, optional) – If True, the data loader will not shutdown the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. (default: False) Warning If the spawn start method is used, worker_init_fn cannot be an unpicklable object, e.g., a lambda function. See Multiprocessing best practices on more details related to multiprocessing in PyTorch. Warning len(dataloader) heuristic is based on the length of the sampler used. When dataset is an IterableDataset, it instead returns an estimate based on len(dataset) / batch_size, with proper rounding depending on drop_last, regardless of multi-process loading configurations. This represents the best guess PyTorch can make because PyTorch trusts user dataset code in correctly handling multi-process loading to avoid duplicate data. However, if sharding results in multiple workers having incomplete last batches, this estimate can still be inaccurate, because (1) an otherwise complete batch can be broken into multiple ones and (2) more than one batch worth of samples can be dropped when drop_last is set. Unfortunately, PyTorch can not detect such cases in general. See Dataset Types for more details on these two types of datasets and how IterableDataset interacts with Multi-process data loading. Warning See Reproducibility, and My data loader workers return identical random numbers, and Randomness in multi-process data loading notes for random seed related questions.
doc_25986
Set the current rcParams. group is the grouping for the rc, e.g., for lines.linewidth the group is lines, for axes.facecolor, the group is axes, and so on. Group may also be a list or tuple of group names, e.g., (xtick, ytick). kwargs is a dictionary attribute name/value pairs, e.g.,: rc('lines', linewidth=2, color='r') sets the current rcParams and is equivalent to: rcParams['lines.linewidth'] = 2 rcParams['lines.color'] = 'r' The following aliases are available to save typing for interactive users: Alias Property 'lw' 'linewidth' 'ls' 'linestyle' 'c' 'color' 'fc' 'facecolor' 'ec' 'edgecolor' 'mew' 'markeredgewidth' 'aa' 'antialiased' Thus you could abbreviate the above call as: rc('lines', lw=2, c='r') Note you can use python's kwargs dictionary facility to store dictionaries of default parameters. e.g., you can customize the font rc as follows: font = {'family' : 'monospace', 'weight' : 'bold', 'size' : 'larger'} rc('font', **font) # pass in the font dict as kwargs This enables you to easily switch between several configurations. Use matplotlib.style.use('default') or rcdefaults() to restore the default rcParams after changes. Notes Similar functionality is available by using the normal dict interface, i.e. rcParams.update({"lines.linewidth": 2, ...}) (but rcParams.update does not support abbreviations or grouping). Examples using matplotlib.pyplot.rc Styling with cycler
doc_25987
Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
doc_25988
Returns a 4-tuple with enough information to recreate the field: The name of the field on the model. The import path of the field (e.g. "django.db.models.IntegerField"). This should be the most portable version, so less specific may be better. A list of positional arguments. A dict of keyword arguments. This method must be added to fields prior to 1.7 to migrate its data using Migrations.
doc_25989
Bayesian information criterion for the current model on the input X. Parameters Xarray of shape (n_samples, n_dimensions) Returns bicfloat The lower the better.
doc_25990
class sklearn.model_selection.RandomizedSearchCV(estimator, param_distributions, *, n_iter=10, scoring=None, n_jobs=None, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score=nan, return_train_score=False) [source] Randomized search on hyper parameters. RandomizedSearchCV implements a “fit” and a “score” method. It also implements “score_samples”, “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used. The parameters of the estimator used to apply these methods are optimized by cross-validated search over parameter settings. In contrast to GridSearchCV, not all parameter values are tried out, but rather a fixed number of parameter settings is sampled from the specified distributions. The number of parameter settings that are tried is given by n_iter. If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribution, sampling with replacement is used. It is highly recommended to use continuous distributions for continuous parameters. Read more in the User Guide. New in version 0.14. Parameters estimatorestimator object. A object of that type is instantiated for each grid point. This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a score function, or scoring must be passed. param_distributionsdict or list of dicts Dictionary with parameters names (str) as keys and distributions or lists of parameters to try. Distributions must provide a rvs method for sampling (such as those from scipy.stats.distributions). If a list is given, it is sampled uniformly. If a list of dicts is given, first a dict is sampled uniformly, and then a parameter is sampled using that dict as above. n_iterint, default=10 Number of parameter settings that are sampled. n_iter trades off runtime vs quality of the solution. scoringstr, callable, list, tuple or dict, default=None Strategy to evaluate the performance of the cross-validated model on the test set. If scoring represents a single score, one can use: a single string (see The scoring parameter: defining model evaluation rules); a callable (see Defining your scoring strategy from metric functions) that returns a single value. If scoring reprents multiple scores, one can use: a list or tuple of unique strings; a callable returning a dictionary where the keys are the metric names and the values are the metric scores; a dictionary with metric names as keys and callables a values. See Specifying multiple metrics for evaluation for an example. If None, the estimator’s score method is used. n_jobsint, default=None Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Changed in version v0.20: n_jobs default changed from 1 to None pre_dispatchint, or str, default=None Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs An int, giving the exact number of total jobs that are spawned A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’ cvint, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross validation, integer, to specify the number of folds in a (Stratified)KFold, CV splitter, An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here. Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold. refitbool, str, or callable, default=True Refit an estimator using the best found parameters on the whole dataset. For multiple metric evaluation, this needs to be a str denoting the scorer that would be used to find the best parameters for refitting the estimator at the end. Where there are considerations other than maximum score in choosing a best estimator, refit can be set to a function which returns the selected best_index_ given the cv_results. In that case, the best_estimator_ and best_params_ will be set according to the returned best_index_ while the best_score_ attribute will not be available. The refitted estimator is made available at the best_estimator_ attribute and permits using predict directly on this RandomizedSearchCV instance. Also for multiple metric evaluation, the attributes best_index_, best_score_ and best_params_ will only be available if refit is set and all of them will be determined w.r.t this specific scorer. See scoring parameter to know more about multiple metric evaluation. Changed in version 0.20: Support for callable added. verboseint Controls the verbosity: the higher, the more messages. random_stateint, RandomState instance or None, default=None Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions. Pass an int for reproducible output across multiple function calls. See Glossary. error_score‘raise’ or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error. return_train_scorebool, default=False If False, the cv_results_ attribute will not include training scores. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting trade-off. However computing the scores on the training set can be computationally expensive and is not strictly required to select the parameters that yield the best generalization performance. New in version 0.19. Changed in version 0.21: Default value was changed from True to False Attributes cv_results_dict of numpy (masked) ndarrays A dict with keys as column headers and values as columns, that can be imported into a pandas DataFrame. For instance the below given table param_kernel param_gamma split0_test_score … rank_test_score ‘rbf’ 0.1 0.80 … 1 ‘rbf’ 0.2 0.84 … 3 ‘rbf’ 0.3 0.70 … 2 will be represented by a cv_results_ dict of: { 'param_kernel' : masked_array(data = ['rbf', 'rbf', 'rbf'], mask = False), 'param_gamma' : masked_array(data = [0.1 0.2 0.3], mask = False), 'split0_test_score' : [0.80, 0.84, 0.70], 'split1_test_score' : [0.82, 0.50, 0.70], 'mean_test_score' : [0.81, 0.67, 0.70], 'std_test_score' : [0.01, 0.24, 0.00], 'rank_test_score' : [1, 3, 2], 'split0_train_score' : [0.80, 0.92, 0.70], 'split1_train_score' : [0.82, 0.55, 0.70], 'mean_train_score' : [0.81, 0.74, 0.70], 'std_train_score' : [0.01, 0.19, 0.00], 'mean_fit_time' : [0.73, 0.63, 0.43], 'std_fit_time' : [0.01, 0.02, 0.01], 'mean_score_time' : [0.01, 0.06, 0.04], 'std_score_time' : [0.00, 0.00, 0.00], 'params' : [{'kernel' : 'rbf', 'gamma' : 0.1}, ...], } NOTE The key 'params' is used to store a list of parameter settings dicts for all the parameter candidates. The mean_fit_time, std_fit_time, mean_score_time and std_score_time are all in seconds. For multi-metric evaluation, the scores for all the scorers are available in the cv_results_ dict at the keys ending with that scorer’s name ('_<scorer_name>') instead of '_score' shown above. (‘split0_test_precision’, ‘mean_train_precision’ etc.) best_estimator_estimator Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False. For multi-metric evaluation, this attribute is present only if refit is specified. See refit parameter for more information on allowed values. best_score_float Mean cross-validated score of the best_estimator. For multi-metric evaluation, this is not available if refit is False. See refit parameter for more information. This attribute is not available if refit is a function. best_params_dict Parameter setting that gave the best results on the hold out data. For multi-metric evaluation, this is not available if refit is False. See refit parameter for more information. best_index_int The index (of the cv_results_ arrays) which corresponds to the best candidate parameter setting. The dict at search.cv_results_['params'][search.best_index_] gives the parameter setting for the best model, that gives the highest mean score (search.best_score_). For multi-metric evaluation, this is not available if refit is False. See refit parameter for more information. scorer_function or a dict Scorer function used on the held out data to choose the best parameters for the model. For multi-metric evaluation, this attribute holds the validated scoring dict which maps the scorer key to the scorer callable. n_splits_int The number of cross-validation splits (folds/iterations). refit_time_float Seconds used for refitting the best model on the whole dataset. This is present only if refit is not False. New in version 0.20. multimetric_bool Whether or not the scorers compute several metrics. See also GridSearchCV Does exhaustive search over a grid of parameters. ParameterSampler A generator over parameter settings, constructed from param_distributions. Notes The parameters selected are those that maximize the score of the held-out data, according to the scoring parameter. If n_jobs was set to a value higher than one, the data is copied for each parameter setting(and not n_jobs times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set pre_dispatch. Then, the memory is copied only pre_dispatch many times. A reasonable value for pre_dispatch is 2 * n_jobs. Examples >>> from sklearn.datasets import load_iris >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.model_selection import RandomizedSearchCV >>> from scipy.stats import uniform >>> iris = load_iris() >>> logistic = LogisticRegression(solver='saga', tol=1e-2, max_iter=200, ... random_state=0) >>> distributions = dict(C=uniform(loc=0, scale=4), ... penalty=['l2', 'l1']) >>> clf = RandomizedSearchCV(logistic, distributions, random_state=0) >>> search = clf.fit(iris.data, iris.target) >>> search.best_params_ {'C': 2..., 'penalty': 'l1'} Methods decision_function(X) Call decision_function on the estimator with the best found parameters. fit(X[, y, groups]) Run fit with all sets of parameters. get_params([deep]) Get parameters for this estimator. inverse_transform(Xt) Call inverse_transform on the estimator with the best found params. predict(X) Call predict on the estimator with the best found parameters. predict_log_proba(X) Call predict_log_proba on the estimator with the best found parameters. predict_proba(X) Call predict_proba on the estimator with the best found parameters. score(X[, y]) Returns the score on the given data, if the estimator has been refit. score_samples(X) Call score_samples on the estimator with the best found parameters. set_params(**params) Set the parameters of this estimator. transform(X) Call transform on the estimator with the best found parameters. decision_function(X) [source] Call decision_function on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports decision_function. Parameters Xindexable, length n_samples Must fulfill the input assumptions of the underlying estimator. fit(X, y=None, *, groups=None, **fit_params) [source] Run fit with all sets of parameters. Parameters Xarray-like of shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples, n_output) or (n_samples,), default=None Target relative to X for classification or regression; None for unsupervised learning. groupsarray-like of shape (n_samples,), default=None Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold). **fit_paramsdict of str -> object Parameters passed to the fit method of the estimator get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. inverse_transform(Xt) [source] Call inverse_transform on the estimator with the best found params. Only available if the underlying estimator implements inverse_transform and refit=True. Parameters Xtindexable, length n_samples Must fulfill the input assumptions of the underlying estimator. predict(X) [source] Call predict on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict. Parameters Xindexable, length n_samples Must fulfill the input assumptions of the underlying estimator. predict_log_proba(X) [source] Call predict_log_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_log_proba. Parameters Xindexable, length n_samples Must fulfill the input assumptions of the underlying estimator. predict_proba(X) [source] Call predict_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_proba. Parameters Xindexable, length n_samples Must fulfill the input assumptions of the underlying estimator. score(X, y=None) [source] Returns the score on the given data, if the estimator has been refit. This uses the score defined by scoring where provided, and the best_estimator_.score method otherwise. Parameters Xarray-like of shape (n_samples, n_features) Input data, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples, n_output) or (n_samples,), default=None Target relative to X for classification or regression; None for unsupervised learning. Returns scorefloat score_samples(X) [source] Call score_samples on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports score_samples. New in version 0.24. Parameters Xiterable Data to predict on. Must fulfill input requirements of the underlying estimator. Returns y_scorendarray of shape (n_samples,) set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. transform(X) [source] Call transform on the estimator with the best found parameters. Only available if the underlying estimator supports transform and refit=True. Parameters Xindexable, length n_samples Must fulfill the input assumptions of the underlying estimator. Examples using sklearn.model_selection.RandomizedSearchCV Release Highlights for scikit-learn 0.24 Comparing randomized search and grid search for hyperparameter estimation
doc_25991
Return the datetime corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= datetime.max.toordinal(). The hour, minute, second and microsecond of the result are all 0, and tzinfo is None.
doc_25992
class sklearn.calibration.CalibratedClassifierCV(base_estimator=None, *, method='sigmoid', cv=None, n_jobs=None, ensemble=True) [source] Probability calibration with isotonic regression or logistic regression. This class uses cross-validation to both estimate the parameters of a classifier and subsequently calibrate a classifier. With default ensemble=True, for each cv split it fits a copy of the base estimator to the training subset, and calibrates it using the testing subset. For prediction, predicted probabilities are averaged across these individual calibrated classifiers. When ensemble=False, cross-validation is used to obtain unbiased predictions, via cross_val_predict, which are then used for calibration. For prediction, the base estimator, trained using all the data, is used. This is the method implemented when probabilities=True for sklearn.svm estimators. Already fitted classifiers can be calibrated via the parameter cv="prefit". In this case, no cross-validation is used and all provided data is used for calibration. The user has to take care manually that data for model fitting and calibration are disjoint. The calibration is based on the decision_function method of the base_estimator if it exists, else on predict_proba. Read more in the User Guide. Parameters base_estimatorestimator instance, default=None The classifier whose output need to be calibrated to provide more accurate predict_proba outputs. The default classifier is a LinearSVC. method{‘sigmoid’, ‘isotonic’}, default=’sigmoid’ The method to use for calibration. Can be ‘sigmoid’ which corresponds to Platt’s method (i.e. a logistic regression model) or ‘isotonic’ which is a non-parametric approach. It is not advised to use isotonic calibration with too few calibration samples (<<1000) since it tends to overfit. cvint, cross-validation generator, iterable or “prefit”, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross-validation, integer, to specify the number of folds. CV splitter, An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if y is binary or multiclass, StratifiedKFold is used. If y is neither binary nor multiclass, KFold is used. Refer to the User Guide for the various cross-validation strategies that can be used here. If “prefit” is passed, it is assumed that base_estimator has been fitted already and all data is used for calibration. Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold. n_jobsint, default=None Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. Base estimator clones are fitted in parallel across cross-validation iterations. Therefore parallelism happens only when cv != "prefit". See Glossary for more details. New in version 0.24. ensemblebool, default=True Determines how the calibrator is fitted when cv is not 'prefit'. Ignored if cv='prefit'. If True, the base_estimator is fitted using training data and calibrated using testing data, for each cv fold. The final estimator is an ensemble of n_cv fitted classifer and calibrator pairs, where n_cv is the number of cross-validation folds. The output is the average predicted probabilities of all pairs. If False, cv is used to compute unbiased predictions, via cross_val_predict, which are then used for calibration. At prediction time, the classifier used is the base_estimator trained on all the data. Note that this method is also internally implemented in sklearn.svm estimators with the probabilities=True parameter. New in version 0.24. Attributes classes_ndarray of shape (n_classes,) The class labels. calibrated_classifiers_list (len() equal to cv or 1 if cv="prefit" or ensemble=False) The list of classifier and calibrator pairs. When cv="prefit", the fitted base_estimator and fitted calibrator. When cv is not “prefit” and ensemble=True, n_cv fitted base_estimator and calibrator pairs. n_cv is the number of cross-validation folds. When cv is not “prefit” and ensemble=False, the base_estimator, fitted on all the data, and fitted calibrator. Changed in version 0.24: Single calibrated classifier case when ensemble=False. References 1 Obtaining calibrated probability estimates from decision trees and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001 2 Transforming Classifier Scores into Accurate Multiclass Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002) 3 Probabilistic Outputs for Support Vector Machines and Comparisons to Regularized Likelihood Methods, J. Platt, (1999) 4 Predicting Good Probabilities with Supervised Learning, A. Niculescu-Mizil & R. Caruana, ICML 2005 Examples >>> from sklearn.datasets import make_classification >>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.calibration import CalibratedClassifierCV >>> X, y = make_classification(n_samples=100, n_features=2, ... n_redundant=0, random_state=42) >>> base_clf = GaussianNB() >>> calibrated_clf = CalibratedClassifierCV(base_estimator=base_clf, cv=3) >>> calibrated_clf.fit(X, y) CalibratedClassifierCV(base_estimator=GaussianNB(), cv=3) >>> len(calibrated_clf.calibrated_classifiers_) 3 >>> calibrated_clf.predict_proba(X)[:5, :] array([[0.110..., 0.889...], [0.072..., 0.927...], [0.928..., 0.071...], [0.928..., 0.071...], [0.071..., 0.928...]]) >>> from sklearn.model_selection import train_test_split >>> X, y = make_classification(n_samples=100, n_features=2, ... n_redundant=0, random_state=42) >>> X_train, X_calib, y_train, y_calib = train_test_split( ... X, y, random_state=42 ... ) >>> base_clf = GaussianNB() >>> base_clf.fit(X_train, y_train) GaussianNB() >>> calibrated_clf = CalibratedClassifierCV( ... base_estimator=base_clf, ... cv="prefit" ... ) >>> calibrated_clf.fit(X_calib, y_calib) CalibratedClassifierCV(base_estimator=GaussianNB(), cv='prefit') >>> len(calibrated_clf.calibrated_classifiers_) 1 >>> calibrated_clf.predict_proba([[-0.5, 0.5]]) array([[0.936..., 0.063...]]) Methods fit(X, y[, sample_weight]) Fit the calibrated model. get_params([deep]) Get parameters for this estimator. predict(X) Predict the target of new samples. predict_proba(X) Calibrated probabilities of classification. score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels. set_params(**params) Set the parameters of this estimator. fit(X, y, sample_weight=None) [source] Fit the calibrated model. Parameters Xarray-like of shape (n_samples, n_features) Training data. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Returns selfobject Returns an instance of self. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. predict(X) [source] Predict the target of new samples. The predicted class is the class that has the highest probability, and can thus be different from the prediction of the uncalibrated classifier. Parameters Xarray-like of shape (n_samples, n_features) The samples. Returns Cndarray of shape (n_samples,) The predicted class. predict_proba(X) [source] Calibrated probabilities of classification. This function returns calibrated probabilities of classification according to each class on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) The samples. Returns Cndarray of shape (n_samples, n_classes) The predicted probas. score(X, y, sample_weight=None) [source] Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. Examples using sklearn.calibration.CalibratedClassifierCV Probability Calibration curves Probability calibration of classifiers Probability Calibration for 3-class classification
doc_25993
Toggle the pan/zoom tool. Pan with left button, zoom with right.
doc_25994
Bases: object A class which, when called, linearly normalizes data into the [0.0, 1.0] interval. Parameters vmin, vmaxfloat or None If vmin and/or vmax is not given, they are initialized from the minimum and maximum value, respectively, of the first input processed; i.e., __call__(A) calls autoscale_None(A). clipbool, default: False If True values falling outside the range [vmin, vmax], are mapped to 0 or 1, whichever is closer, and masked values are set to 1. If False masked values remain masked. Clipping silently defeats the purpose of setting the over, under, and masked colors in a colormap, so it is likely to lead to surprises; therefore the default is clip=False. Notes Returns 0 if vmin == vmax. __call__(value, clip=None)[source] Normalize value data in the [vmin, vmax] interval into the [0.0, 1.0] interval and return it. Parameters value Data to normalize. clipbool If None, defaults to self.clip (which defaults to False). Notes If not already initialized, self.vmin and self.vmax are initialized using self.autoscale_None(value). autoscale(A)[source] Set vmin, vmax to min, max of A. autoscale_None(A)[source] If vmin or vmax are not set, use the min/max of A to set them. propertyclip inverse(value)[source] staticprocess_value(value)[source] Homogenize the input value for easy and efficient normalization. value can be a scalar or sequence. Returns resultmasked array Masked array with the same shape as value. is_scalarbool Whether value is a scalar. Notes Float dtypes are preserved; integer types with two bytes or smaller are converted to np.float32, and larger types are converted to np.float64. Preserving float32 when possible, and using in-place operations, greatly improves speed for large arrays. scaled()[source] Return whether vmin and vmax are set. propertyvmax propertyvmin Examples using matplotlib.colors.Normalize Multicolored lines Contour Image Creating annotated heatmaps Image Masked Blend transparency with color in 2D images Multi Image Pcolor Demo pcolormesh Histograms Time Series Histogram Axes Grid2 Shaded & power normalized rendering Frontpage contour example Exploring normalizations Hillshading Left ventricle bullseye Colormap Normalizations Colormap Normalizations Symlognorm Basic Usage Constrained Layout Guide Customized Colorbars Tutorial Colormap Normalization
doc_25995
Set the title text of the window containing the figure. This has no effect for non-GUI (e.g., PS) backends.
doc_25996
Class that implements the default pseudo-random number generator used by the random module. Deprecated since version 3.9: In the future, the seed must be one of the following types: NoneType, int, float, str, bytes, or bytearray.
doc_25997
Provide exponentially weighted (EW) calculations. Exactly one parameter: com, span, halflife, or alpha must be provided. Parameters com:float, optional Specify decay in terms of center of mass \(\alpha = 1 / (1 + com)\), for \(com \geq 0\). span:float, optional Specify decay in terms of span \(\alpha = 2 / (span + 1)\), for \(span \geq 1\). halflife:float, str, timedelta, optional Specify decay in terms of half-life \(\alpha = 1 - \exp\left(-\ln(2) / halflife\right)\), for \(halflife > 0\). If times is specified, the time unit (str or timedelta) over which an observation decays to half its value. Only applicable to mean(), and halflife value will not apply to the other functions. New in version 1.1.0. alpha:float, optional Specify smoothing factor \(\alpha\) directly \(0 < \alpha \leq 1\). min_periods:int, default 0 Minimum number of observations in window required to have a value; otherwise, result is np.nan. adjust:bool, default True Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average). When adjust=True (default), the EW function is calculated using weights \(w_i = (1 - \alpha)^i\). For example, the EW moving average of the series [\(x_0, x_1, ..., x_t\)] would be: \[y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ... + (1 - \alpha)^t x_0}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... + (1 - \alpha)^t}\] When adjust=False, the exponentially weighted function is calculated recursively: \[\begin{split}\begin{split} y_0 &= x_0\\ y_t &= (1 - \alpha) y_{t-1} + \alpha x_t, \end{split}\end{split}\] ignore_na:bool, default False Ignore missing values when calculating weights. When ignore_na=False (default), weights are based on absolute positions. For example, the weights of \(x_0\) and \(x_2\) used in calculating the final weighted average of [\(x_0\), None, \(x_2\)] are \((1-\alpha)^2\) and \(1\) if adjust=True, and \((1-\alpha)^2\) and \(\alpha\) if adjust=False. When ignore_na=True, weights are based on relative positions. For example, the weights of \(x_0\) and \(x_2\) used in calculating the final weighted average of [\(x_0\), None, \(x_2\)] are \(1-\alpha\) and \(1\) if adjust=True, and \(1-\alpha\) and \(\alpha\) if adjust=False. axis:{0, 1}, default 0 If 0 or 'index', calculate across the rows. If 1 or 'columns', calculate across the columns. times:str, np.ndarray, Series, default None New in version 1.1.0. Only applicable to mean(). Times corresponding to the observations. Must be monotonically increasing and datetime64[ns] dtype. If 1-D array like, a sequence with the same shape as the observations. Deprecated since version 1.4.0: If str, the name of the column in the DataFrame representing the times. method:str {‘single’, ‘table’}, default ‘single’ New in version 1.4.0. Execute the rolling operation per single column or row ('single') or over the entire object ('table'). This argument is only implemented when specifying engine='numba' in the method call. Only applicable to mean() Returns ExponentialMovingWindow subclass See also rolling Provides rolling window calculations. expanding Provides expanding transformations. Notes See Windowing Operations for further usage details and examples. Examples >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}) >>> df B 0 0.0 1 1.0 2 2.0 3 NaN 4 4.0 >>> df.ewm(com=0.5).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 >>> df.ewm(alpha=2 / 3).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 adjust >>> df.ewm(com=0.5, adjust=True).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 >>> df.ewm(com=0.5, adjust=False).mean() B 0 0.000000 1 0.666667 2 1.555556 3 1.555556 4 3.650794 ignore_na >>> df.ewm(com=0.5, ignore_na=True).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.225000 >>> df.ewm(com=0.5, ignore_na=False).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 times Exponentially weighted mean with weights calculated with a timedelta halflife relative to times. >>> times = ['2020-01-01', '2020-01-03', '2020-01-10', '2020-01-15', '2020-01-17'] >>> df.ewm(halflife='4 days', times=pd.DatetimeIndex(times)).mean() B 0 0.000000 1 0.585786 2 1.523889 3 1.523889 4 3.233686
doc_25998
Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal SESSION_COOKIE_AGE. This function accepts two optional keyword arguments: modification: last modification of the session, as a datetime object. Defaults to the current time. expiry: expiry information for the session, as a datetime object, an int (in seconds), or None. Defaults to the value stored in the session by set_expiry(), if there is one, or None.
doc_25999
turtle.seth(to_angle) Parameters to_angle – a number (integer or float) Set the orientation of the turtle to to_angle. Here are some common directions in degrees: standard mode logo mode 0 - east 0 - north 90 - north 90 - east 180 - west 180 - south 270 - south 270 - west >>> turtle.setheading(90) >>> turtle.heading() 90.0