_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_200 | Deprecated since version 3.9: Deprecated in favor of url. | |
doc_201 |
Project data to maximize class separation. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
X_newndarray of shape (n_samples, n_components)
Transformed data. | |
doc_202 |
Return an array with the elements of self right-justified in a string of length width. See also char.rjust | |
doc_203 |
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_204 |
Compute standard deviation of groups, excluding missing values. Parameters
ddof:int, default 1
Degrees of freedom. Returns
DataFrame or Series
Standard deviation of values within each group. | |
doc_205 |
Initialize self. See help(type(self)) for accurate signature. | |
doc_206 | This decorator adds a Cache-Control: max-age=0, no-cache, no-store,
must-revalidate, private header to a response to indicate that a page should never be cached. | |
doc_207 | This class implements semaphore objects. A semaphore manages an atomic counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. The optional argument gives the initial value for the internal counter; it defaults to 1. If the value given is less than 0, ValueError is raised. Changed in version 3.3: changed from a factory function to a class.
acquire(blocking=True, timeout=None)
Acquire a semaphore. When invoked without arguments: If the internal counter is larger than zero on entry, decrement it by one and return True immediately. If the internal counter is zero on entry, block until awoken by a call to release(). Once awoken (and the counter is greater than 0), decrement the counter by 1 and return True. Exactly one thread will be awoken by each call to release(). The order in which threads are awoken should not be relied on. When invoked with blocking set to false, do not block. If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True. When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return False. Return True otherwise. Changed in version 3.2: The timeout parameter is new.
release(n=1)
Release a semaphore, incrementing the internal counter by n. When it was zero on entry and other threads are waiting for it to become larger than zero again, wake up n of those threads. Changed in version 3.9: Added the n parameter to release multiple waiting threads at once. | |
doc_208 |
Set parameters within this locator. | |
doc_209 | See Migration guide for more details. tf.compat.v1.raw_ops.ResourceAccumulatorNumAccumulated
tf.raw_ops.ResourceAccumulatorNumAccumulated(
handle, name=None
)
Args
handle A Tensor of type resource. The handle to an accumulator.
name A name for the operation (optional).
Returns A Tensor of type int32. | |
doc_210 |
Return self|value. | |
doc_211 | tf.compat.v1.train.Scaffold(
init_op=None, init_feed_dict=None, init_fn=None, ready_op=None,
ready_for_local_init_op=None, local_init_op=None, summary_op=None, saver=None,
copy_from_scaffold=None, local_init_feed_dict=None
)
When you build a model for training you usually need ops to initialize variables, a Saver to checkpoint them, an op to collect summaries for the visualizer, and so on. Various libraries built on top of the core TensorFlow library take care of creating some or all of these pieces and storing them in well known collections in the graph. The Scaffold class helps pick these pieces from the graph collections, creating and adding them to the collections if needed. If you call the scaffold constructor without any arguments, it will pick pieces from the collections, creating default ones if needed when scaffold.finalize() is called. You can pass arguments to the constructor to provide your own pieces. Pieces that you pass to the constructor are not added to the graph collections. The following pieces are directly accessible as attributes of the Scaffold object:
saver: A tf.compat.v1.train.Saver object taking care of saving the variables. Picked from and stored into the SAVERS collection in the graph by default.
init_op: An op to run to initialize the variables. Picked from and stored into the INIT_OP collection in the graph by default.
ready_op: An op to verify that the variables are initialized. Picked from and stored into the READY_OP collection in the graph by default.
ready_for_local_init_op: An op to verify that global state has been initialized and it is alright to run local_init_op. Picked from and stored into the READY_FOR_LOCAL_INIT_OP collection in the graph by default. This is needed when the initialization of local variables depends on the values of global variables.
local_init_op: An op to initialize the local variables. Picked from and stored into the LOCAL_INIT_OP collection in the graph by default.
summary_op: An op to run and merge the summaries in the graph. Picked from and stored into the SUMMARY_OP collection in the graph by default. You can also pass the following additional pieces to the constructor:
init_feed_dict: A session feed dictionary that should be used when running the init op.
init_fn: A callable to run after the init op to perform additional initializations. The callable will be called as init_fn(scaffold, session).
Args
init_op Optional op for initializing variables.
init_feed_dict Optional session feed dictionary to use when running the init_op.
init_fn Optional function to use to initialize the model after running the init_op. Will be called as init_fn(scaffold, session).
ready_op Optional op to verify that the variables are initialized. Must return an empty 1D string tensor when the variables are initialized, or a non-empty 1D string tensor listing the names of the non-initialized variables.
ready_for_local_init_op Optional op to verify that the global variables are initialized and local_init_op can be run. Must return an empty 1D string tensor when the global variables are initialized, or a non-empty 1D string tensor listing the names of the non-initialized global variables.
local_init_op Optional op to initialize local variables.
summary_op Optional op to gather all summaries. Must return a scalar string tensor containing a serialized Summary proto.
saver Optional tf.compat.v1.train.Saver object to use to save and restore variables. May also be a tf.train.Checkpoint object, in which case object-based checkpoints are saved. This will also load some object-based checkpoints saved from elsewhere, but that loading may be fragile since it uses fixed keys rather than performing a full graph-based match. For example if a variable has two paths from the Checkpoint object because two Model objects share the Layer object that owns it, removing one Model may change the keys and break checkpoint loading through this API, whereas a graph-based match would match the variable through the other Model.
copy_from_scaffold Optional scaffold object to copy fields from. Its fields will be overwritten by the provided fields in this function.
local_init_feed_dict Optional session feed dictionary to use when running the local_init_op.
Attributes
init_feed_dict
init_fn
init_op
local_init_feed_dict
local_init_op
ready_for_local_init_op
ready_op
saver
summary_op
Methods default_local_init_op View source
@staticmethod
default_local_init_op()
Returns an op that groups the default local init ops. This op is used during session initialization when a Scaffold is initialized without specifying the local_init_op arg. It includes tf.compat.v1.local_variables_initializer, tf.compat.v1.tables_initializer, and also initializes local session resources.
Returns The default Scaffold local init op.
finalize View source
finalize()
Creates operations if needed and finalizes the graph. get_or_default View source
@staticmethod
get_or_default(
arg_name, collection_key, default_constructor
)
Get from cache or create a default operation. | |
doc_212 | Files and subdirectories only in a. | |
doc_213 |
Set the position of the spine. Spine position is specified by a 2 tuple of (position type, amount). The position types are: 'outward': place the spine out from the data area by the specified number of points. (Negative values place the spine inwards.) 'axes': place the spine at the specified Axes coordinate (0 to 1). 'data': place the spine at the specified data coordinate. Additionally, shorthand notations define a special positions: 'center' -> ('axes', 0.5) 'zero' -> ('data', 0.0) | |
doc_214 | Use BoundField.initial to retrieve initial data for a form field. It retrieves the data from Form.initial if present, otherwise trying Field.initial. Callable values are evaluated. See Initial form values for more examples. BoundField.initial caches its return value, which is useful especially when dealing with callables whose return values can change (e.g. datetime.now or uuid.uuid4): >>> from datetime import datetime
>>> class DatedCommentForm(CommentForm):
... created = forms.DateTimeField(initial=datetime.now)
>>> f = DatedCommentForm()
>>> f['created'].initial
datetime.datetime(2021, 7, 27, 9, 5, 54)
>>> f['created'].initial
datetime.datetime(2021, 7, 27, 9, 5, 54)
Using BoundField.initial is recommended over get_initial_for_field(). | |
doc_215 | Same as ModelChoiceField.to_field_name. | |
doc_216 |
Set the artist transform. Parameters
tTransform | |
doc_217 | Access the fitted transformer by name. Read-only attribute to access any transformer by given name. Keys are transformer names and values are the fitted transformer objects. | |
doc_218 |
Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of x, y0, y1 tuples, forming rows in a table. Entries for alpha are optional. Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use: cdict = {'red': [(0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'green': [(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0)]}
Each row in the table for a given color is a sequence of x, y0, y1 tuples. In each sequence, x must increase monotonically from 0 to 1. For any input value z falling between x[i] and x[i+1], the output value of a given color will be linearly interpolated between y1[i] and y0[i+1]: row i: x y0 y1
/
/
row i+1: x y0 y1
Hence y0 in the first row and y1 in the last row are never used. See also
LinearSegmentedColormap.from_list
Static method; factory function for generating a smoothly-varying LinearSegmentedColormap.
makeMappingArray
For information about making a mapping array. | |
doc_219 | tf.compat.v1.feature_column.categorical_column_with_vocabulary_file(
key, vocabulary_file, vocabulary_size=None, num_oov_buckets=0,
default_value=None, dtype=tf.dtypes.string
)
Use this when your inputs are in string or integer format, and you have a vocabulary file that maps each value to an integer ID. By default, out-of-vocabulary values are ignored. Use either (but not both) of num_oov_buckets and default_value to specify how to include out-of-vocabulary values. For input dictionary features, features[key] is either Tensor or SparseTensor. If Tensor, missing values can be represented by -1 for int and '' for string, which will be dropped by this feature column. Example with num_oov_buckets: File '/us/states.txt' contains 50 lines, each with a 2-character U.S. state abbreviation. All inputs with values in that file are assigned an ID 0-49, corresponding to its line number. All other values are hashed and assigned an ID 50-54. states = categorical_column_with_vocabulary_file(
key='states', vocabulary_file='/us/states.txt', vocabulary_size=50,
num_oov_buckets=5)
columns = [states, ...]
features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
linear_prediction = linear_model(features, columns)
Example with default_value: File '/us/states.txt' contains 51 lines - the first line is 'XX', and the other 50 each have a 2-character U.S. state abbreviation. Both a literal 'XX' in input, and other values missing from the file, will be assigned ID 0. All others are assigned the corresponding line number 1-50. states = categorical_column_with_vocabulary_file(
key='states', vocabulary_file='/us/states.txt', vocabulary_size=51,
default_value=0)
columns = [states, ...]
features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
linear_prediction, _, _ = linear_model(features, columns)
And to make an embedding with either: columns = [embedding_column(states, 3),...]
features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
dense_tensor = input_layer(features, columns)
Args
key A unique string identifying the input feature. It is used as the column name and the dictionary key for feature parsing configs, feature Tensor objects, and feature columns.
vocabulary_file The vocabulary file name.
vocabulary_size Number of the elements in the vocabulary. This must be no greater than length of vocabulary_file, if less than length, later values are ignored. If None, it is set to the length of vocabulary_file.
num_oov_buckets Non-negative integer, the number of out-of-vocabulary buckets. All out-of-vocabulary inputs will be assigned IDs in the range [vocabulary_size, vocabulary_size+num_oov_buckets) based on a hash of the input value. A positive num_oov_buckets can not be specified with default_value.
default_value The integer ID value to return for out-of-vocabulary feature values, defaults to -1. This can not be specified with a positive num_oov_buckets.
dtype The type of features. Only string and integer types are supported.
Returns A CategoricalColumn with a vocabulary file.
Raises
ValueError vocabulary_file is missing or cannot be opened.
ValueError vocabulary_size is missing or < 1.
ValueError num_oov_buckets is a negative integer.
ValueError num_oov_buckets and default_value are both specified.
ValueError dtype is neither string nor integer. | |
doc_220 | Return the thread stack size used when creating new threads. The optional size argument specifies the stack size to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32 KiB). If size is not specified, 0 is used. If changing the thread stack size is unsupported, a RuntimeError is raised. If the specified stack size is invalid, a ValueError is raised and the stack size is unmodified. 32 KiB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself. Note that some platforms may have particular restrictions on values for the stack size, such as requiring a minimum stack size > 32 KiB or requiring allocation in multiples of the system memory page size - platform documentation should be referred to for more information (4 KiB pages are common; using multiples of 4096 for the stack size is the suggested approach in the absence of more specific information). Availability: Windows, systems with POSIX threads. | |
doc_221 | from django.utils.translation import gettext_lazy as _
def validate_even(value):
if value % 2 != 0:
raise ValidationError(
_('%(value)s is not an even number'),
params={'value': value},
)
You can add this to a model field via the field’s validators argument: from django.db import models
class MyModel(models.Model):
even_field = models.IntegerField(validators=[validate_even])
Because values are converted to Python before validators are run, you can even use the same validator with forms: from django import forms
class MyForm(forms.Form):
even_field = forms.IntegerField(validators=[validate_even])
You can also use a class with a __call__() method for more complex or configurable validators. RegexValidator, for example, uses this technique. If a class-based validator is used in the validators model field option, you should make sure it is serializable by the migration framework by adding deconstruct() and __eq__() methods. How validators are run See the form validation for more information on how validators are run in forms, and Validating objects for how they’re run in models. Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form. See the ModelForm documentation for information on how model validation interacts with forms. Built-in validators The django.core.validators module contains a collection of callable validators for use with model and form fields. They’re used internally but are available for use with your own fields, too. They can be used in addition to, or in lieu of custom field.clean() methods. RegexValidator
class RegexValidator(regex=None, message=None, code=None, inverse_match=None, flags=0)
Parameters:
regex – If not None, overrides regex. Can be a regular expression string or a pre-compiled regular expression.
message – If not None, overrides message.
code – If not None, overrides code.
inverse_match – If not None, overrides inverse_match.
flags – If not None, overrides flags. In that case, regex must be a regular expression string, or TypeError is raised. A RegexValidator searches the provided value for a given regular expression with re.search(). By default, raises a ValidationError with message and code if a match is not found. Its behavior can be inverted by setting inverse_match to True, in which case the ValidationError is raised when a match is found.
regex
The regular expression pattern to search for within the provided value, using re.search(). This may be a string or a pre-compiled regular expression created with re.compile(). Defaults to the empty string, which will be found in every possible value.
message
The error message used by ValidationError if validation fails. Defaults to "Enter a valid value".
code
The error code used by ValidationError if validation fails. Defaults to "invalid".
inverse_match
The match mode for regex. Defaults to False.
flags
The regex flags used when compiling the regular expression string regex. If regex is a pre-compiled regular expression, and flags is overridden, TypeError is raised. Defaults to 0.
EmailValidator
class EmailValidator(message=None, code=None, allowlist=None)
Parameters:
message – If not None, overrides message.
code – If not None, overrides code.
allowlist – If not None, overrides allowlist.
message
The error message used by ValidationError if validation fails. Defaults to "Enter a valid email address".
code
The error code used by ValidationError if validation fails. Defaults to "invalid".
allowlist
Allowlist of email domains. By default, a regular expression (the domain_regex attribute) is used to validate whatever appears after the @ sign. However, if that string appears in the allowlist, this validation is bypassed. If not provided, the default allowlist is ['localhost']. Other domains that don’t contain a dot won’t pass validation, so you’d need to add them to the allowlist as necessary.
Deprecated since version 3.2: The whitelist parameter is deprecated. Use allowlist instead. The undocumented domain_whitelist attribute is deprecated. Use domain_allowlist instead.
URLValidator
class URLValidator(schemes=None, regex=None, message=None, code=None)
A RegexValidator subclass that ensures a value looks like a URL, and raises an error code of 'invalid' if it doesn’t. Loopback addresses and reserved IP spaces are considered valid. Literal IPv6 addresses (RFC 3986#section-3.2.2) and Unicode domains are both supported. In addition to the optional arguments of its parent RegexValidator class, URLValidator accepts an extra optional attribute:
schemes
URL/URI scheme list to validate against. If not provided, the default list is ['http', 'https', 'ftp', 'ftps']. As a reference, the IANA website provides a full list of valid URI schemes.
validate_email
validate_email
An EmailValidator instance without any customizations.
validate_slug
validate_slug
A RegexValidator instance that ensures a value consists of only letters, numbers, underscores or hyphens.
validate_unicode_slug
validate_unicode_slug
A RegexValidator instance that ensures a value consists of only Unicode letters, numbers, underscores, or hyphens.
validate_ipv4_address
validate_ipv4_address
A RegexValidator instance that ensures a value looks like an IPv4 address.
validate_ipv6_address
validate_ipv6_address
Uses django.utils.ipv6 to check the validity of an IPv6 address.
validate_ipv46_address
validate_ipv46_address
Uses both validate_ipv4_address and validate_ipv6_address to ensure a value is either a valid IPv4 or IPv6 address.
validate_comma_separated_integer_list
validate_comma_separated_integer_list
A RegexValidator instance that ensures a value is a comma-separated list of integers.
int_list_validator
int_list_validator(sep=', ', message=None, code='invalid', allow_negative=False)
Returns a RegexValidator instance that ensures a string consists of integers separated by sep. It allows negative integers when allow_negative is True.
MaxValueValidator
class MaxValueValidator(limit_value, message=None)
Raises a ValidationError with a code of 'max_value' if value is greater than limit_value, which may be a callable.
MinValueValidator
class MinValueValidator(limit_value, message=None)
Raises a ValidationError with a code of 'min_value' if value is less than limit_value, which may be a callable.
MaxLengthValidator
class MaxLengthValidator(limit_value, message=None)
Raises a ValidationError with a code of 'max_length' if the length of value is greater than limit_value, which may be a callable.
MinLengthValidator
class MinLengthValidator(limit_value, message=None)
Raises a ValidationError with a code of 'min_length' if the length of value is less than limit_value, which may be a callable.
DecimalValidator
class DecimalValidator(max_digits, decimal_places)
Raises ValidationError with the following codes:
'max_digits' if the number of digits is larger than max_digits.
'max_decimal_places' if the number of decimals is larger than decimal_places.
'max_whole_digits' if the number of whole digits is larger than the difference between max_digits and decimal_places.
FileExtensionValidator
class FileExtensionValidator(allowed_extensions, message, code)
Raises a ValidationError with a code of 'invalid_extension' if the extension of value.name (value is a File) isn’t found in allowed_extensions. The extension is compared case-insensitively with allowed_extensions. Warning Don’t rely on validation of the file extension to determine a file’s type. Files can be renamed to have any extension no matter what data they contain.
validate_image_file_extension
validate_image_file_extension
Uses Pillow to ensure that value.name (value is a File) has a valid image extension.
ProhibitNullCharactersValidator
class ProhibitNullCharactersValidator(message=None, code=None)
Raises a ValidationError if str(value) contains one or more nulls characters ('\x00').
Parameters:
message – If not None, overrides message.
code – If not None, overrides code.
message
The error message used by ValidationError if validation fails. Defaults to "Null characters are not allowed.".
code
The error code used by ValidationError if validation fails. Defaults to "null_characters_not_allowed". | |
doc_222 | os.O_DIRECT
os.O_DIRECTORY
os.O_NOFOLLOW
os.O_NOATIME
os.O_PATH
os.O_TMPFILE
os.O_SHLOCK
os.O_EXLOCK
The above constants are extensions and not present if they are not defined by the C library. Changed in version 3.4: Add O_PATH on systems that support it. Add O_TMPFILE, only available on Linux Kernel 3.11 or newer. | |
doc_223 |
Broadcast any number of arrays against each other. Parameters
`*args`array_likes
The arrays to broadcast.
subokbool, optional
If True, then sub-classes will be passed-through, otherwise the returned arrays will be forced to be a base-class array (default). Returns
broadcastedlist of arrays
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. While you can set the writable flag True, writing to a single output value may end up changing more than one location in the output array. Deprecated since version 1.17: The output is currently marked so that if written to, a deprecation warning will be emitted. A future version will set the writable flag False so writing to it will raise an error. See also broadcast
broadcast_to
broadcast_shapes
Examples >>> x = np.array([[1,2,3]])
>>> y = np.array([[4],[5]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
[1, 2, 3]]), array([[4, 4, 4],
[5, 5, 5]])]
Here is a useful idiom for getting contiguous copies instead of non-contiguous views. >>> [np.array(a) for a in np.broadcast_arrays(x, y)]
[array([[1, 2, 3],
[1, 2, 3]]), array([[4, 4, 4],
[5, 5, 5]])] | |
doc_224 | sklearn.linear_model.ridge_regression(X, y, alpha, *, sample_weight=None, solver='auto', max_iter=None, tol=0.001, verbose=0, random_state=None, return_n_iter=False, return_intercept=False, check_input=True) [source]
Solve the ridge equation by the method of normal equations. Read more in the User Guide. Parameters
X{ndarray, sparse matrix, LinearOperator} of shape (n_samples, n_features)
Training data
yndarray of shape (n_samples,) or (n_samples, n_targets)
Target values
alphafloat or array-like of shape (n_targets,)
Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to 1 / (2C) in other linear models such as LogisticRegression or LinearSVC. If an array is passed, penalties are assumed to be specific to the targets. Hence they must correspond in number.
sample_weightfloat or array-like of shape (n_samples,), default=None
Individual weights for each sample. If given a float, every sample will have the same weight. If sample_weight is not None and solver=’auto’, the solver will be set to ‘cholesky’. New in version 0.17.
solver{‘auto’, ‘svd’, ‘cholesky’, ‘lsqr’, ‘sparse_cg’, ‘sag’, ‘saga’}, default=’auto’
Solver to use in the computational routines: ‘auto’ chooses the solver automatically based on the type of data. ‘svd’ uses a Singular Value Decomposition of X to compute the Ridge coefficients. More stable for singular matrices than ‘cholesky’. ‘cholesky’ uses the standard scipy.linalg.solve function to obtain a closed-form solution via a Cholesky decomposition of dot(X.T, X) ‘sparse_cg’ uses the conjugate gradient solver as found in scipy.sparse.linalg.cg. As an iterative algorithm, this solver is more appropriate than ‘cholesky’ for large-scale data (possibility to set tol and max_iter). ‘lsqr’ uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr. It is the fastest and uses an iterative procedure. ‘sag’ uses a Stochastic Average Gradient descent, and ‘saga’ uses its improved, unbiased version named SAGA. Both methods also use an iterative procedure, and are often faster than other solvers when both n_samples and n_features are large. Note that ‘sag’ and ‘saga’ fast convergence is only guaranteed on features with approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing. All last five solvers support both dense and sparse data. However, only ‘sag’ and ‘sparse_cg’ supports sparse input when fit_intercept is True. New in version 0.17: Stochastic Average Gradient descent solver. New in version 0.19: SAGA solver.
max_iterint, default=None
Maximum number of iterations for conjugate gradient solver. For the ‘sparse_cg’ and ‘lsqr’ solvers, the default value is determined by scipy.sparse.linalg. For ‘sag’ and saga solver, the default value is 1000.
tolfloat, default=1e-3
Precision of the solution.
verboseint, default=0
Verbosity level. Setting verbose > 0 will display additional information depending on the solver used.
random_stateint, RandomState instance, default=None
Used when solver == ‘sag’ or ‘saga’ to shuffle the data. See Glossary for details.
return_n_iterbool, default=False
If True, the method also returns n_iter, the actual number of iteration performed by the solver. New in version 0.17.
return_interceptbool, default=False
If True and if X is sparse, the method also returns the intercept, and the solver is automatically changed to ‘sag’. This is only a temporary fix for fitting the intercept with sparse data. For dense data, use sklearn.linear_model._preprocess_data before your regression. New in version 0.17.
check_inputbool, default=True
If False, the input arrays X and y will not be checked. New in version 0.21. Returns
coefndarray of shape (n_features,) or (n_targets, n_features)
Weight vector(s).
n_iterint, optional
The actual number of iteration performed by the solver. Only returned if return_n_iter is True.
interceptfloat or ndarray of shape (n_targets,)
The intercept of the model. Only returned if return_intercept is True and if X is a scipy sparse array. Notes This function won’t compute the intercept. | |
doc_225 |
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
cmap Colormap or str or None
color color or list of rgba tuples
edgecolor or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
paths unknown
picker None or bool or float or callable
pickradius float
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
urls list of str or None
visible bool
zorder float | |
doc_226 |
Iterate over DataFrame rows as (index, Series) pairs. Yields
index:label or tuple of label
The index of the row. A tuple for a MultiIndex.
data:Series
The data of the row as a Series. See also DataFrame.itertuples
Iterate over DataFrame rows as namedtuples of the values. DataFrame.items
Iterate over (column name, Series) pairs. Notes
Because iterrows returns a Series for each row, it does not preserve dtypes across the rows (dtypes are preserved across columns for DataFrames). For example,
>>> df = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])
>>> row = next(df.iterrows())[1]
>>> row
int 1.0
float 1.5
Name: 0, dtype: float64
>>> print(row['int'].dtype)
float64
>>> print(df['int'].dtype)
int64
To preserve dtypes while iterating over the rows, it is better to use itertuples() which returns namedtuples of the values and which is generally faster than iterrows. You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect. | |
doc_227 |
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_228 | Implements the 'backslashreplace' error handling (for text encodings only): malformed data is replaced by a backslashed escape sequence. | |
doc_229 |
Truncate series to length size. Reduce the series to length size by discarding the high degree terms. The value of size must be a positive integer. This can be useful in least squares where the coefficients of the high degree terms may be very small. Parameters
sizepositive int
The series is reduced to length size by discarding the high degree terms. The value of size must be a positive integer. Returns
new_seriesseries
New instance of series with truncated coefficients. | |
doc_230 | Unescape '&', '<', and '>' in a string of data. You can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. '&', '<', and '>' are always unescaped, even if entities is provided. | |
doc_231 |
Autoscale the scalar limits on the norm instance using the current array | |
doc_232 | Gathers values along an axis specified by dim. For a 3-D tensor the output is specified by: out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
input and index must have the same number of dimensions. It is also required that index.size(d) <= input.size(d) for all dimensions d != dim. out will have the same shape as index. Note that input and index do not broadcast against each other. Parameters
input (Tensor) – the source tensor
dim (int) – the axis along which to index
index (LongTensor) – the indices of elements to gather Keyword Arguments
sparse_grad (bool, optional) – If True, gradient w.r.t. input will be a sparse tensor.
out (Tensor, optional) – the destination tensor Example: >>> t = torch.tensor([[1, 2], [3, 4]])
>>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]]))
tensor([[ 1, 1],
[ 4, 3]]) | |
doc_233 |
Compute the histogram of a dataset. Parameters
aarray_like
Input data. The histogram is computed over the flattened array.
binsint or sequence of scalars or str, optional
If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform bin widths. New in version 1.11.0. If bins is a string, it defines the method used to calculate the optimal bin width, as defined by histogram_bin_edges.
range(float, float), optional
The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. The first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data.
normedbool, optional
Deprecated since version 1.6.0. This is equivalent to the density argument, but produces incorrect results for unequal bin widths. It should not be used. Changed in version 1.15.0: DeprecationWarnings are actually emitted.
weightsarray_like, optional
An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1.
densitybool, optional
If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function. Overrides the normed keyword if given. Returns
histarray
The values of the histogram. See density and weights for a description of the possible semantics.
bin_edgesarray of dtype float
Return the bin edges (length(hist)+1). See also
histogramdd, bincount, searchsorted, digitize, histogram_bin_edges
Notes All but the last (righthand-most) bin is half-open. In other words, if bins is: [1, 2, 3, 4]
then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4. Examples >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]))
>>> np.histogram(np.arange(4), bins=np.arange(5), density=True)
(array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4]))
>>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3])
(array([1, 4, 1]), array([0, 1, 2, 3]))
>>> a = np.arange(5)
>>> hist, bin_edges = np.histogram(a, density=True)
>>> hist
array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5])
>>> hist.sum()
2.4999999999999996
>>> np.sum(hist * np.diff(bin_edges))
1.0
New in version 1.11.0. Automated Bin Selection Methods example, using 2 peak random data with 2000 points: >>> import matplotlib.pyplot as plt
>>> rng = np.random.RandomState(10) # deterministic random data
>>> a = np.hstack((rng.normal(size=1000),
... rng.normal(loc=5, scale=2, size=1000)))
>>> _ = plt.hist(a, bins='auto') # arguments are passed to np.histogram
>>> plt.title("Histogram with 'auto' bins")
Text(0.5, 1.0, "Histogram with 'auto' bins")
>>> plt.show() | |
doc_234 |
Attributes
key int32 key
value TensorShapeProto value | |
doc_235 |
Return variable labels as a dict, associating each variable name with corresponding label. Returns
dict | |
doc_236 | The part of the name preceding the colon if there is one, else the empty string. | |
doc_237 |
Marks a middleware as synchronous-only. (The default in Django, but this allows you to future-proof if the default ever changes in a future release.) | |
doc_238 | from django.utils.translation import gettext as _
def my_view(request):
output = _("Welcome to my site.")
return HttpResponse(output)
You could code this without using the alias. This example is identical to the previous one: from django.http import HttpResponse
from django.utils.translation import gettext
def my_view(request):
output = gettext("Welcome to my site.")
return HttpResponse(output)
Translation works on computed values. This example is identical to the previous two: def my_view(request):
words = ['Welcome', 'to', 'my', 'site.']
output = _(' '.join(words))
return HttpResponse(output)
Translation works on variables. Again, here’s an identical example: def my_view(request):
sentence = 'Welcome to my site.'
output = _(sentence)
return HttpResponse(output)
(The caveat with using variables or computed values, as in the previous two examples, is that Django’s translation-string-detecting utility, django-admin makemessages, won’t be able to find these strings. More on makemessages later.) The strings you pass to _() or gettext() can take placeholders, specified with Python’s standard named-string interpolation syntax. Example: def my_view(request, m, d):
output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
return HttpResponse(output)
This technique lets language-specific translations reorder the placeholder text. For example, an English translation may be "Today is November 26.", while a Spanish translation may be "Hoy es 26 de noviembre." – with the month and the day placeholders swapped. For this reason, you should use named-string interpolation (e.g., %(day)s) instead of positional interpolation (e.g., %s or %d) whenever you have more than a single parameter. If you used positional interpolation, translations wouldn’t be able to reorder placeholder text. Since string extraction is done by the xgettext command, only syntaxes supported by gettext are supported by Django. In particular, Python f-strings are not yet supported by xgettext, and JavaScript template strings need gettext 0.21+. Comments for translators If you would like to give translators hints about a translatable string, you can add a comment prefixed with the Translators keyword on the line preceding the string, e.g.: def my_view(request):
# Translators: This message appears on the home page only
output = gettext("Welcome to my site.")
The comment will then appear in the resulting .po file associated with the translatable construct located below it and should also be displayed by most translation tools. Note Just for completeness, this is the corresponding fragment of the resulting .po file: #. Translators: This message appears on the home page only
# path/to/python/file.py:123
msgid "Welcome to my site."
msgstr ""
This also works in templates. See Comments for translators in templates for more details. Marking strings as no-op Use the function django.utils.translation.gettext_noop() to mark a string as a translation string without translating it. The string is later translated from a variable. Use this if you have constant strings that should be stored in the source language because they are exchanged over systems or users – such as strings in a database – but should be translated at the last possible point in time, such as when the string is presented to the user. Pluralization Use the function django.utils.translation.ngettext() to specify pluralized messages. ngettext() takes three arguments: the singular translation string, the plural translation string and the number of objects. This function is useful when you need your Django application to be localizable to languages where the number and complexity of plural forms is greater than the two forms used in English (‘object’ for the singular and ‘objects’ for all the cases where count is different from one, irrespective of its value.) For example: from django.http import HttpResponse
from django.utils.translation import ngettext
def hello_world(request, count):
page = ngettext(
'there is %(count)d object',
'there are %(count)d objects',
count,
) % {
'count': count,
}
return HttpResponse(page)
In this example the number of objects is passed to the translation languages as the count variable. Note that pluralization is complicated and works differently in each language. Comparing count to 1 isn’t always the correct rule. This code looks sophisticated, but will produce incorrect results for some languages: from django.utils.translation import ngettext
from myapp.models import Report
count = Report.objects.count()
if count == 1:
name = Report._meta.verbose_name
else:
name = Report._meta.verbose_name_plural
text = ngettext(
'There is %(count)d %(name)s available.',
'There are %(count)d %(name)s available.',
count,
) % {
'count': count,
'name': name
}
Don’t try to implement your own singular-or-plural logic; it won’t be correct. In a case like this, consider something like the following: text = ngettext(
'There is %(count)d %(name)s object available.',
'There are %(count)d %(name)s objects available.',
count,
) % {
'count': count,
'name': Report._meta.verbose_name,
}
Note When using ngettext(), make sure you use a single name for every extrapolated variable included in the literal. In the examples above, note how we used the name Python variable in both translation strings. This example, besides being incorrect in some languages as noted above, would fail: text = ngettext(
'There is %(count)d %(name)s available.',
'There are %(count)d %(plural_name)s available.',
count,
) % {
'count': Report.objects.count(),
'name': Report._meta.verbose_name,
'plural_name': Report._meta.verbose_name_plural,
}
You would get an error when running django-admin
compilemessages: a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'
Contextual markers Sometimes words have several meanings, such as "May" in English, which refers to a month name and to a verb. To enable translators to translate these words correctly in different contexts, you can use the django.utils.translation.pgettext() function, or the django.utils.translation.npgettext() function if the string needs pluralization. Both take a context string as the first variable. In the resulting .po file, the string will then appear as often as there are different contextual markers for the same string (the context will appear on the msgctxt line), allowing the translator to give a different translation for each of them. For example: from django.utils.translation import pgettext
month = pgettext("month name", "May")
or: from django.db import models
from django.utils.translation import pgettext_lazy
class MyThing(models.Model):
name = models.CharField(help_text=pgettext_lazy(
'help text for MyThing model', 'This is the help text'))
will appear in the .po file as: msgctxt "month name"
msgid "May"
msgstr ""
Contextual markers are also supported by the translate and blocktranslate template tags. Lazy translation Use the lazy versions of translation functions in django.utils.translation (easily recognizable by the lazy suffix in their names) to translate strings lazily – when the value is accessed rather than when they’re called. These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering. This is essential when calls to these functions are located in code paths that are executed at module load time. This is something that can easily happen when defining models, forms and model forms, because Django implements these such that their fields are actually class-level attributes. For that reason, make sure to use lazy translations in the following cases: Model fields and relationships verbose_name and help_text option values For example, to translate the help text of the name field in the following model, do the following: from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
You can mark names of ForeignKey, ManyToManyField or OneToOneField relationship as translatable by using their verbose_name options: class MyThing(models.Model):
kind = models.ForeignKey(
ThingKind,
on_delete=models.CASCADE,
related_name='kinds',
verbose_name=_('kind'),
)
Just like you would do in verbose_name you should provide a lowercase verbose name text for the relation as Django will automatically titlecase it when required. Model verbose names values It is recommended to always provide explicit verbose_name and verbose_name_plural options rather than relying on the fallback English-centric and somewhat naïve determination of verbose names Django performs by looking at the model’s class name: from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(_('name'), help_text=_('This is the help text'))
class Meta:
verbose_name = _('my thing')
verbose_name_plural = _('my things')
Model methods description argument to the @display decorator For model methods, you can provide translations to Django and the admin site with the description argument to the display() decorator: from django.contrib import admin
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
kind = models.ForeignKey(
ThingKind,
on_delete=models.CASCADE,
related_name='kinds',
verbose_name=_('kind'),
)
@admin.display(description=_('Is it a mouse?'))
def is_mouse(self):
return self.kind.type == MOUSE_TYPE
Working with lazy translation objects The result of a gettext_lazy() call can be used wherever you would use a string (a str object) in other Django code, but it may not work with arbitrary Python code. For example, the following won’t work because the requests library doesn’t handle gettext_lazy objects: body = gettext_lazy("I \u2764 Django") # (Unicode :heart:)
requests.post('https://example.com/send', data={'body': body})
You can avoid such problems by casting gettext_lazy() objects to text strings before passing them to non-Django code: requests.post('https://example.com/send', data={'body': str(body)})
If you don’t like the long gettext_lazy name, you can alias it as _ (underscore), like so: from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
Using gettext_lazy() and ngettext_lazy() to mark strings in models and utility functions is a common operation. When you’re working with these objects elsewhere in your code, you should ensure that you don’t accidentally convert them to strings, because they should be converted as late as possible (so that the correct locale is in effect). This necessitates the use of the helper function described next. Lazy translations and plural When using lazy translation for a plural string (n[p]gettext_lazy), you generally don’t know the number argument at the time of the string definition. Therefore, you are authorized to pass a key name instead of an integer as the number argument. Then number will be looked up in the dictionary under that key during string interpolation. Here’s example: from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ngettext_lazy
class MyForm(forms.Form):
error_message = ngettext_lazy("You only provided %(num)d argument",
"You only provided %(num)d arguments", 'num')
def clean(self):
# ...
if error:
raise ValidationError(self.error_message % {'num': number})
If the string contains exactly one unnamed placeholder, you can interpolate directly with the number argument: class MyForm(forms.Form):
error_message = ngettext_lazy(
"You provided %d argument",
"You provided %d arguments",
)
def clean(self):
# ...
if error:
raise ValidationError(self.error_message % number)
Formatting strings: format_lazy()
Python’s str.format() method will not work when either the format_string or any of the arguments to str.format() contains lazy translation objects. Instead, you can use django.utils.text.format_lazy(), which creates a lazy object that runs the str.format() method only when the result is included in a string. For example: from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy
...
name = gettext_lazy('John Lennon')
instrument = gettext_lazy('guitar')
result = format_lazy('{name}: {instrument}', name=name, instrument=instrument)
In this case, the lazy translations in result will only be converted to strings when result itself is used in a string (usually at template rendering time). Other uses of lazy in delayed translations For any other case where you would like to delay the translation, but have to pass the translatable string as argument to another function, you can wrap this function inside a lazy call yourself. For example: from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
mark_safe_lazy = lazy(mark_safe, str)
And then later: lazy_string = mark_safe_lazy(_("<p>My <strong>string!</strong></p>"))
Localized names of languages
get_language_info()
The get_language_info() function provides detailed information about languages: >>> from django.utils.translation import activate, get_language_info
>>> activate('fr')
>>> li = get_language_info('de')
>>> print(li['name'], li['name_local'], li['name_translated'], li['bidi'])
German Deutsch Allemand False
The name, name_local, and name_translated attributes of the dictionary contain the name of the language in English, in the language itself, and in your current active language respectively. The bidi attribute is True only for bi-directional languages. The source of the language information is the django.conf.locale module. Similar access to this information is available for template code. See below. Internationalization: in template code Translations in Django templates uses two template tags and a slightly different syntax than in Python code. To give your template access to these tags, put {% load i18n %} toward the top of your template. As with all template tags, this tag needs to be loaded in all templates which use translations, even those templates that extend from other templates which have already loaded the i18n tag. Warning Translated strings will not be escaped when rendered in a template. This allows you to include HTML in translations, for example for emphasis, but potentially dangerous characters (e.g. ") will also be rendered unchanged.
translate template tag The {% translate %} template tag translates either a constant string (enclosed in single or double quotes) or variable content: <title>{% translate "This is the title." %}</title>
<title>{% translate myvar %}</title>
If the noop option is present, variable lookup still takes place but the translation is skipped. This is useful when “stubbing out” content that will require translation in the future: <title>{% translate "myvar" noop %}</title>
Internally, inline translations use an gettext() call. In case a template var (myvar above) is passed to the tag, the tag will first resolve such variable to a string at run-time and then look up that string in the message catalogs. It’s not possible to mix a template variable inside a string within {% translate %}. If your translations require strings with variables (placeholders), use {% blocktranslate %} instead. If you’d like to retrieve a translated string without displaying it, you can use the following syntax: {% translate "This is the title" as the_title %}
<title>{{ the_title }}</title>
<meta name="description" content="{{ the_title }}">
In practice you’ll use this to get a string you can use in multiple places in a template or so you can use the output as an argument for other template tags or filters: {% translate "starting point" as start %}
{% translate "end point" as end %}
{% translate "La Grande Boucle" as race %}
<h1>
<a href="/" title="{% blocktranslate %}Back to '{{ race }}' homepage{% endblocktranslate %}">{{ race }}</a>
</h1>
<p>
{% for stage in tour_stages %}
{% cycle start end %}: {{ stage }}{% if forloop.counter|divisibleby:2 %}<br>{% else %}, {% endif %}
{% endfor %}
</p>
{% translate %} also supports contextual markers using the context keyword: {% translate "May" context "month name" %}
blocktranslate template tag Contrarily to the translate tag, the blocktranslate tag allows you to mark complex sentences consisting of literals and variable content for translation by making use of placeholders: {% blocktranslate %}This string will have {{ value }} inside.{% endblocktranslate %}
To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. Examples: {% blocktranslate with amount=article.price %}
That will cost $ {{ amount }}.
{% endblocktranslate %}
{% blocktranslate with myvar=value|filter %}
This will have {{ myvar }} inside.
{% endblocktranslate %}
You can use multiple expressions inside a single blocktranslate tag: {% blocktranslate with book_t=book|title author_t=author|title %}
This is {{ book_t }} by {{ author_t }}
{% endblocktranslate %}
Note The previous more verbose format is still supported: {% blocktranslate with book|title as book_t and author|title as author_t %} Other block tags (for example {% for %} or {% if %}) are not allowed inside a blocktranslate tag. If resolving one of the block arguments fails, blocktranslate will fall back to the default language by deactivating the currently active language temporarily with the deactivate_all() function. This tag also provides for pluralization. To use it: Designate and bind a counter value with the name count. This value will be the one used to select the right plural form. Specify both the singular and plural forms separating them with the {% plural %} tag within the {% blocktranslate %} and {% endblocktranslate %} tags. An example: {% blocktranslate count counter=list|length %}
There is only one {{ name }} object.
{% plural %}
There are {{ counter }} {{ name }} objects.
{% endblocktranslate %}
A more complex example: {% blocktranslate with amount=article.price count years=i.length %}
That will cost $ {{ amount }} per year.
{% plural %}
That will cost $ {{ amount }} per {{ years }} years.
{% endblocktranslate %}
When you use both the pluralization feature and bind values to local variables in addition to the counter value, keep in mind that the blocktranslate construct is internally converted to an ngettext call. This means the same notes regarding ngettext variables apply. Reverse URL lookups cannot be carried out within the blocktranslate and should be retrieved (and stored) beforehand: {% url 'path.to.view' arg arg2 as the_url %}
{% blocktranslate %}
This is a URL: {{ the_url }}
{% endblocktranslate %}
If you’d like to retrieve a translated string without displaying it, you can use the following syntax: {% blocktranslate asvar the_title %}The title is {{ title }}.{% endblocktranslate %}
<title>{{ the_title }}</title>
<meta name="description" content="{{ the_title }}">
In practice you’ll use this to get a string you can use in multiple places in a template or so you can use the output as an argument for other template tags or filters. {% blocktranslate %} also supports contextual markers using the context keyword: {% blocktranslate with name=user.username context "greeting" %}Hi {{ name }}{% endblocktranslate %}
Another feature {% blocktranslate %} supports is the trimmed option. This option will remove newline characters from the beginning and the end of the content of the {% blocktranslate %} tag, replace any whitespace at the beginning and end of a line and merge all lines into one using a space character to separate them. This is quite useful for indenting the content of a {% blocktranslate %} tag without having the indentation characters end up in the corresponding entry in the PO file, which makes the translation process easier. For instance, the following {% blocktranslate %} tag: {% blocktranslate trimmed %}
First sentence.
Second paragraph.
{% endblocktranslate %}
will result in the entry "First sentence. Second paragraph." in the PO file, compared to "\n First sentence.\n Second paragraph.\n", if the trimmed option had not been specified. String literals passed to tags and filters You can translate string literals passed as arguments to tags and filters by using the familiar _() syntax: {% some_tag _("Page not found") value|yesno:_("yes,no") %}
In this case, both the tag and the filter will see the translated string, so they don’t need to be aware of translations. Note In this example, the translation infrastructure will be passed the string "yes,no", not the individual strings "yes" and "no". The translated string will need to contain the comma so that the filter parsing code knows how to split up the arguments. For example, a German translator might translate the string "yes,no" as "ja,nein" (keeping the comma intact). Comments for translators in templates Just like with Python code, these notes for translators can be specified using comments, either with the comment tag: {% comment %}Translators: View verb{% endcomment %}
{% translate "View" %}
{% comment %}Translators: Short intro blurb{% endcomment %}
<p>{% blocktranslate %}A multiline translatable
literal.{% endblocktranslate %}</p>
or with the {# … #} one-line comment constructs: {# Translators: Label of a button that triggers search #}
<button type="submit">{% translate "Go" %}</button>
{# Translators: This is a text of the base template #}
{% blocktranslate %}Ambiguous translatable block of text{% endblocktranslate %}
Note Just for completeness, these are the corresponding fragments of the resulting .po file: #. Translators: View verb
# path/to/template/file.html:10
msgid "View"
msgstr ""
#. Translators: Short intro blurb
# path/to/template/file.html:13
msgid ""
"A multiline translatable"
"literal."
msgstr ""
# ...
#. Translators: Label of a button that triggers search
# path/to/template/file.html:100
msgid "Go"
msgstr ""
#. Translators: This is a text of the base template
# path/to/template/file.html:103
msgid "Ambiguous translatable block of text"
msgstr ""
Switching language in templates If you want to select a language within a template, you can use the language template tag: {% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<p>{% translate "Welcome to our page" %}</p>
{% language 'en' %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<p>{% translate "Welcome to our page" %}</p>
{% endlanguage %}
While the first occurrence of “Welcome to our page” uses the current language, the second will always be in English. Other tags These tags also require a {% load i18n %}. get_available_languages {% get_available_languages as LANGUAGES %} returns a list of tuples in which the first element is the language code and the second is the language name (translated into the currently active locale). get_current_language {% get_current_language as LANGUAGE_CODE %} returns the current user’s preferred language as a string. Example: en-us. See How Django discovers language preference. get_current_language_bidi {% get_current_language_bidi as LANGUAGE_BIDI %} returns the current locale’s direction. If True, it’s a right-to-left language, e.g. Hebrew, Arabic. If False it’s a left-to-right language, e.g. English, French, German, etc.
i18n context processor If you enable the django.template.context_processors.i18n context processor, then each RequestContext will have access to LANGUAGES, LANGUAGE_CODE, and LANGUAGE_BIDI as defined above. get_language_info You can also retrieve information about any of the available languages using provided template tags and filters. To get information about a single language, use the {% get_language_info %} tag: {% get_language_info for LANGUAGE_CODE as lang %}
{% get_language_info for "pl" as lang %}
You can then access the information: Language code: {{ lang.code }}<br>
Name of language: {{ lang.name_local }}<br>
Name in English: {{ lang.name }}<br>
Bi-directional: {{ lang.bidi }}
Name in the active language: {{ lang.name_translated }}
get_language_info_list You can also use the {% get_language_info_list %} template tag to retrieve information for a list of languages (e.g. active languages as specified in LANGUAGES). See the section about the set_language redirect view for an example of how to display a language selector using {% get_language_info_list %}. In addition to LANGUAGES style list of tuples, {% get_language_info_list %} supports lists of language codes. If you do this in your view: context = {'available_languages': ['en', 'es', 'fr']}
return render(request, 'mytemplate.html', context)
you can iterate over those languages in the template: {% get_language_info_list for available_languages as langs %}
{% for lang in langs %} ... {% endfor %}
Template filters There are also some filters available for convenience:
{{ LANGUAGE_CODE|language_name }} (“German”)
{{ LANGUAGE_CODE|language_name_local }} (“Deutsch”)
{{ LANGUAGE_CODE|language_bidi }} (False)
{{ LANGUAGE_CODE|language_name_translated }} (“německy”, when active language is Czech) Internationalization: in JavaScript code Adding translations to JavaScript poses some problems: JavaScript code doesn’t have access to a gettext implementation. JavaScript code doesn’t have access to .po or .mo files; they need to be delivered by the server. The translation catalogs for JavaScript should be kept as small as possible. Django provides an integrated solution for these problems: It passes the translations into JavaScript, so you can call gettext, etc., from within JavaScript. The main solution to these problems is the following JavaScriptCatalog view, which generates a JavaScript code library with functions that mimic the gettext interface, plus an array of translation strings. The JavaScriptCatalog view
class JavaScriptCatalog
A view that produces a JavaScript code library with functions that mimic the gettext interface, plus an array of translation strings. Attributes
domain
Translation domain containing strings to add in the view output. Defaults to 'djangojs'.
packages
A list of application names among installed applications. Those apps should contain a locale directory. All those catalogs plus all catalogs found in LOCALE_PATHS (which are always included) are merged into one catalog. Defaults to None, which means that all available translations from all INSTALLED_APPS are provided in the JavaScript output.
Example with default values: from django.views.i18n import JavaScriptCatalog
urlpatterns = [
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]
Example with custom packages: urlpatterns = [
path('jsi18n/myapp/',
JavaScriptCatalog.as_view(packages=['your.app.label']),
name='javascript-catalog'),
]
If your root URLconf uses i18n_patterns(), JavaScriptCatalog must also be wrapped by i18n_patterns() for the catalog to be correctly generated. Example with i18n_patterns(): from django.conf.urls.i18n import i18n_patterns
urlpatterns = i18n_patterns(
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
)
The precedence of translations is such that the packages appearing later in the packages argument have higher precedence than the ones appearing at the beginning. This is important in the case of clashing translations for the same literal. If you use more than one JavaScriptCatalog view on a site and some of them define the same strings, the strings in the catalog that was loaded last take precedence. Using the JavaScript translation catalog To use the catalog, pull in the dynamically generated script like this: <script src="{% url 'javascript-catalog' %}"></script>
This uses reverse URL lookup to find the URL of the JavaScript catalog view. When the catalog is loaded, your JavaScript code can use the following methods: gettext ngettext interpolate get_format gettext_noop pgettext npgettext pluralidx gettext The gettext function behaves similarly to the standard gettext interface within your Python code: document.write(gettext('this is to be translated'));
ngettext The ngettext function provides an interface to pluralize words and phrases: const objectCount = 1 // or 0, or 2, or 3, ...
const string = ngettext(
'literal for the singular case',
'literal for the plural case',
objectCount
);
interpolate The interpolate function supports dynamically populating a format string. The interpolation syntax is borrowed from Python, so the interpolate function supports both positional and named interpolation:
Positional interpolation: obj contains a JavaScript Array object whose elements values are then sequentially interpolated in their corresponding fmt placeholders in the same order they appear. For example: const formats = ngettext(
'There is %s object. Remaining: %s',
'There are %s objects. Remaining: %s',
11
);
const string = interpolate(formats, [11, 20]);
// string is 'There are 11 objects. Remaining: 20'
Named interpolation: This mode is selected by passing the optional boolean named parameter as true. obj contains a JavaScript object or associative array. For example: const data = {
count: 10,
total: 50
};
const formats = ngettext(
'Total: %(total)s, there is %(count)s object',
'there are %(count)s of a total of %(total)s objects',
data.count
);
const string = interpolate(formats, data, true);
You shouldn’t go over the top with string interpolation, though: this is still JavaScript, so the code has to make repeated regular-expression substitutions. This isn’t as fast as string interpolation in Python, so keep it to those cases where you really need it (for example, in conjunction with ngettext to produce proper pluralizations). get_format The get_format function has access to the configured i18n formatting settings and can retrieve the format string for a given setting name: document.write(get_format('DATE_FORMAT'));
// 'N j, Y'
It has access to the following settings: DATE_FORMAT DATE_INPUT_FORMATS DATETIME_FORMAT DATETIME_INPUT_FORMATS DECIMAL_SEPARATOR FIRST_DAY_OF_WEEK MONTH_DAY_FORMAT NUMBER_GROUPING SHORT_DATE_FORMAT SHORT_DATETIME_FORMAT THOUSAND_SEPARATOR TIME_FORMAT TIME_INPUT_FORMATS YEAR_MONTH_FORMAT This is useful for maintaining formatting consistency with the Python-rendered values. gettext_noop This emulates the gettext function but does nothing, returning whatever is passed to it: document.write(gettext_noop('this will not be translated'));
This is useful for stubbing out portions of the code that will need translation in the future. pgettext The pgettext function behaves like the Python variant (pgettext()), providing a contextually translated word: document.write(pgettext('month name', 'May'));
npgettext The npgettext function also behaves like the Python variant (npgettext()), providing a pluralized contextually translated word: document.write(npgettext('group', 'party', 1));
// party
document.write(npgettext('group', 'party', 2));
// parties
pluralidx The pluralidx function works in a similar way to the pluralize template filter, determining if a given count should use a plural form of a word or not: document.write(pluralidx(0));
// true
document.write(pluralidx(1));
// false
document.write(pluralidx(2));
// true
In the simplest case, if no custom pluralization is needed, this returns false for the integer 1 and true for all other numbers. However, pluralization is not this simple in all languages. If the language does not support pluralization, an empty value is provided. Additionally, if there are complex rules around pluralization, the catalog view will render a conditional expression. This will evaluate to either a true (should pluralize) or false (should not pluralize) value. The JSONCatalog view
class JSONCatalog
In order to use another client-side library to handle translations, you may want to take advantage of the JSONCatalog view. It’s similar to JavaScriptCatalog but returns a JSON response. See the documentation for JavaScriptCatalog to learn about possible values and use of the domain and packages attributes. The response format is as follows: {
"catalog": {
# Translations catalog
},
"formats": {
# Language formats for date, time, etc.
},
"plural": "..." # Expression for plural forms, or null.
}
Note on performance The various JavaScript/JSON i18n views generate the catalog from .mo files on every request. Since its output is constant, at least for a given version of a site, it’s a good candidate for caching. Server-side caching will reduce CPU load. It’s easily implemented with the cache_page() decorator. To trigger cache invalidation when your translations change, provide a version-dependent key prefix, as shown in the example below, or map the view at a version-dependent URL: from django.views.decorators.cache import cache_page
from django.views.i18n import JavaScriptCatalog
# The value returned by get_version() must change when translations change.
urlpatterns = [
path('jsi18n/',
cache_page(86400, key_prefix='js18n-%s' % get_version())(JavaScriptCatalog.as_view()),
name='javascript-catalog'),
]
Client-side caching will save bandwidth and make your site load faster. If you’re using ETags (ConditionalGetMiddleware), you’re already covered. Otherwise, you can apply conditional decorators. In the following example, the cache is invalidated whenever you restart your application server: from django.utils import timezone
from django.views.decorators.http import last_modified
from django.views.i18n import JavaScriptCatalog
last_modified_date = timezone.now()
urlpatterns = [
path('jsi18n/',
last_modified(lambda req, **kw: last_modified_date)(JavaScriptCatalog.as_view()),
name='javascript-catalog'),
]
You can even pre-generate the JavaScript catalog as part of your deployment procedure and serve it as a static file. This radical technique is implemented in django-statici18n. Internationalization: in URL patterns Django provides two mechanisms to internationalize URL patterns: Adding the language prefix to the root of the URL patterns to make it possible for LocaleMiddleware to detect the language to activate from the requested URL. Making URL patterns themselves translatable via the django.utils.translation.gettext_lazy() function. Warning Using either one of these features requires that an active language be set for each request; in other words, you need to have django.middleware.locale.LocaleMiddleware in your MIDDLEWARE setting. Language prefix in URL patterns
i18n_patterns(*urls, prefix_default_language=True)
This function can be used in a root URLconf and Django will automatically prepend the current active language code to all URL patterns defined within i18n_patterns(). Setting prefix_default_language to False removes the prefix from the default language (LANGUAGE_CODE). This can be useful when adding translations to existing site so that the current URLs won’t change. Example URL patterns: from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path
from about import views as about_views
from news import views as news_views
from sitemap.views import sitemap
urlpatterns = [
path('sitemap.xml', sitemap, name='sitemap-xml'),
]
news_patterns = ([
path('', news_views.index, name='index'),
path('category/<slug:slug>/', news_views.category, name='category'),
path('<slug:slug>/', news_views.details, name='detail'),
], 'news')
urlpatterns += i18n_patterns(
path('about/', about_views.main, name='about'),
path('news/', include(news_patterns, namespace='news')),
)
After defining these URL patterns, Django will automatically add the language prefix to the URL patterns that were added by the i18n_patterns function. Example: >>> from django.urls import reverse
>>> from django.utils.translation import activate
>>> activate('en')
>>> reverse('sitemap-xml')
'/sitemap.xml'
>>> reverse('news:index')
'/en/news/'
>>> activate('nl')
>>> reverse('news:detail', kwargs={'slug': 'news-slug'})
'/nl/news/news-slug/'
With prefix_default_language=False and LANGUAGE_CODE='en', the URLs will be: >>> activate('en')
>>> reverse('news:index')
'/news/'
>>> activate('nl')
>>> reverse('news:index')
'/nl/news/'
Warning i18n_patterns() is only allowed in a root URLconf. Using it within an included URLconf will throw an ImproperlyConfigured exception. Warning Ensure that you don’t have non-prefixed URL patterns that might collide with an automatically-added language prefix. Translating URL patterns URL patterns can also be marked translatable using the gettext_lazy() function. Example: from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path
from django.utils.translation import gettext_lazy as _
from about import views as about_views
from news import views as news_views
from sitemaps.views import sitemap
urlpatterns = [
path('sitemap.xml', sitemap, name='sitemap-xml'),
]
news_patterns = ([
path('', news_views.index, name='index'),
path(_('category/<slug:slug>/'), news_views.category, name='category'),
path('<slug:slug>/', news_views.details, name='detail'),
], 'news')
urlpatterns += i18n_patterns(
path(_('about/'), about_views.main, name='about'),
path(_('news/'), include(news_patterns, namespace='news')),
)
After you’ve created the translations, the reverse() function will return the URL in the active language. Example: >>> from django.urls import reverse
>>> from django.utils.translation import activate
>>> activate('en')
>>> reverse('news:category', kwargs={'slug': 'recent'})
'/en/news/category/recent/'
>>> activate('nl')
>>> reverse('news:category', kwargs={'slug': 'recent'})
'/nl/nieuws/categorie/recent/'
Warning In most cases, it’s best to use translated URLs only within a language code prefixed block of patterns (using i18n_patterns()), to avoid the possibility that a carelessly translated URL causes a collision with a non-translated URL pattern. Reversing in templates If localized URLs get reversed in templates they always use the current language. To link to a URL in another language use the language template tag. It enables the given language in the enclosed template section: {% load i18n %}
{% get_available_languages as languages %}
{% translate "View this category in:" %}
{% for lang_code, lang_name in languages %}
{% language lang_code %}
<a href="{% url 'category' slug=category.slug %}">{{ lang_name }}</a>
{% endlanguage %}
{% endfor %}
The language tag expects the language code as the only argument. Localization: how to create language files Once the string literals of an application have been tagged for later translation, the translation themselves need to be written (or obtained). Here’s how that works. Message files The first step is to create a message file for a new language. A message file is a plain-text file, representing a single language, that contains all available translation strings and how they should be represented in the given language. Message files have a .po file extension. Django comes with a tool, django-admin makemessages, that automates the creation and upkeep of these files. Gettext utilities The makemessages command (and compilemessages discussed later) use commands from the GNU gettext toolset: xgettext, msgfmt, msgmerge and msguniq. The minimum version of the gettext utilities supported is 0.15. To create or update a message file, run this command: django-admin makemessages -l de
…where de is the locale name for the message file you want to create. For example, pt_BR for Brazilian Portuguese, de_AT for Austrian German or id for Indonesian. The script should be run from one of two places: The root directory of your Django project (the one that contains manage.py). The root directory of one of your Django apps. The script runs over your project source tree or your application source tree and pulls out all strings marked for translation (see How Django discovers translations and be sure LOCALE_PATHS is configured correctly). It creates (or updates) a message file in the directory locale/LANG/LC_MESSAGES. In the de example, the file will be locale/de/LC_MESSAGES/django.po. When you run makemessages from the root directory of your project, the extracted strings will be automatically distributed to the proper message files. That is, a string extracted from a file of an app containing a locale directory will go in a message file under that directory. A string extracted from a file of an app without any locale directory will either go in a message file under the directory listed first in LOCALE_PATHS or will generate an error if LOCALE_PATHS is empty. By default django-admin makemessages examines every file that has the .html, .txt or .py file extension. If you want to override that default, use the --extension or -e option to specify the file extensions to examine: django-admin makemessages -l de -e txt
Separate multiple extensions with commas and/or use -e or --extension multiple times: django-admin makemessages -l de -e html,txt -e xml
Warning When creating message files from JavaScript source code you need to use the special djangojs domain, not -e js. Using Jinja2 templates? makemessages doesn’t understand the syntax of Jinja2 templates. To extract strings from a project containing Jinja2 templates, use Message Extracting from Babel instead. Here’s an example babel.cfg configuration file: # Extraction from Python source files
[python: **.py]
# Extraction from Jinja2 templates
[jinja2: **.jinja]
extensions = jinja2.ext.with_
Make sure you list all extensions you’re using! Otherwise Babel won’t recognize the tags defined by these extensions and will ignore Jinja2 templates containing them entirely. Babel provides similar features to makemessages, can replace it in general, and doesn’t depend on gettext. For more information, read its documentation about working with message catalogs. No gettext? If you don’t have the gettext utilities installed, makemessages will create empty files. If that’s the case, either install the gettext utilities or copy the English message file (locale/en/LC_MESSAGES/django.po) if available and use it as a starting point, which is an empty translation file. Working on Windows? If you’re using Windows and need to install the GNU gettext utilities so makemessages works, see gettext on Windows for more information. Each .po file contains a small bit of metadata, such as the translation maintainer’s contact information, but the bulk of the file is a list of messages – mappings between translation strings and the actual translated text for the particular language. For example, if your Django app contained a translation string for the text "Welcome to my site.", like so: _("Welcome to my site.")
…then django-admin makemessages will have created a .po file containing the following snippet – a message: #: path/to/python/module.py:23
msgid "Welcome to my site."
msgstr ""
A quick explanation:
msgid is the translation string, which appears in the source. Don’t change it.
msgstr is where you put the language-specific translation. It starts out empty, so it’s your responsibility to change it. Make sure you keep the quotes around your translation. As a convenience, each message includes, in the form of a comment line prefixed with # and located above the msgid line, the filename and line number from which the translation string was gleaned. Long messages are a special case. There, the first string directly after the msgstr (or msgid) is an empty string. Then the content itself will be written over the next few lines as one string per line. Those strings are directly concatenated. Don’t forget trailing spaces within the strings; otherwise, they’ll be tacked together without whitespace! Mind your charset Due to the way the gettext tools work internally and because we want to allow non-ASCII source strings in Django’s core and your applications, you must use UTF-8 as the encoding for your PO files (the default when PO files are created). This means that everybody will be using the same encoding, which is important when Django processes the PO files. Fuzzy entries makemessages sometimes generates translation entries marked as fuzzy, e.g. when translations are inferred from previously translated strings. By default, fuzzy entries are not processed by compilemessages. To reexamine all source code and templates for new translation strings and update all message files for all languages, run this: django-admin makemessages -a
Compiling message files After you create your message file – and each time you make changes to it – you’ll need to compile it into a more efficient form, for use by gettext. Do this with the django-admin compilemessages utility. This tool runs over all available .po files and creates .mo files, which are binary files optimized for use by gettext. In the same directory from which you ran django-admin makemessages, run django-admin compilemessages like this: django-admin compilemessages
That’s it. Your translations are ready for use. Working on Windows? If you’re using Windows and need to install the GNU gettext utilities so django-admin compilemessages works see gettext on Windows for more information. .po files: Encoding and BOM usage. Django only supports .po files encoded in UTF-8 and without any BOM (Byte Order Mark) so if your text editor adds such marks to the beginning of files by default then you will need to reconfigure it. Troubleshooting: gettext() incorrectly detects python-format in strings with percent signs In some cases, such as strings with a percent sign followed by a space and a string conversion type (e.g. _("10% interest")), gettext() incorrectly flags strings with python-format. If you try to compile message files with incorrectly flagged strings, you’ll get an error message like number of format specifications in 'msgid' and
'msgstr' does not match or 'msgstr' is not a valid Python format string,
unlike 'msgid'. To workaround this, you can escape percent signs by adding a second percent sign: from django.utils.translation import gettext as _
output = _("10%% interest")
Or you can use no-python-format so that all percent signs are treated as literals: # xgettext:no-python-format
output = _("10% interest")
Creating message files from JavaScript source code You create and update the message files the same way as the other Django message files – with the django-admin makemessages tool. The only difference is you need to explicitly specify what in gettext parlance is known as a domain in this case the djangojs domain, by providing a -d
djangojs parameter, like this: django-admin makemessages -d djangojs -l de
This would create or update the message file for JavaScript for German. After updating message files, run django-admin compilemessages the same way as you do with normal Django message files.
gettext on Windows This is only needed for people who either want to extract message IDs or compile message files (.po). Translation work itself involves editing existing files of this type, but if you want to create your own message files, or want to test or compile a changed message file, download a precompiled binary installer. You may also use gettext binaries you have obtained elsewhere, so long as the xgettext --version command works properly. Do not attempt to use Django translation utilities with a gettext package if the command xgettext
--version entered at a Windows command prompt causes a popup window saying “xgettext.exe has generated errors and will be closed by Windows”. Customizing the makemessages command If you want to pass additional parameters to xgettext, you need to create a custom makemessages command and override its xgettext_options attribute: from django.core.management.commands import makemessages
class Command(makemessages.Command):
xgettext_options = makemessages.Command.xgettext_options + ['--keyword=mytrans']
If you need more flexibility, you could also add a new argument to your custom makemessages command: from django.core.management.commands import makemessages
class Command(makemessages.Command):
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
'--extra-keyword',
dest='xgettext_keywords',
action='append',
)
def handle(self, *args, **options):
xgettext_keywords = options.pop('xgettext_keywords')
if xgettext_keywords:
self.xgettext_options = (
makemessages.Command.xgettext_options[:] +
['--keyword=%s' % kwd for kwd in xgettext_keywords]
)
super().handle(*args, **options)
Miscellaneous The set_language redirect view
set_language(request)
As a convenience, Django comes with a view, django.views.i18n.set_language(), that sets a user’s language preference and redirects to a given URL or, by default, back to the previous page. Activate this view by adding the following line to your URLconf: path('i18n/', include('django.conf.urls.i18n')),
(Note that this example makes the view available at /i18n/setlang/.) Warning Make sure that you don’t include the above URL within i18n_patterns() - it needs to be language-independent itself to work correctly. The view expects to be called via the POST method, with a language parameter set in request. If session support is enabled, the view saves the language choice in the user’s session. It also saves the language choice in a cookie that is named django_language by default. (The name can be changed through the LANGUAGE_COOKIE_NAME setting.) After setting the language choice, Django looks for a next parameter in the POST or GET data. If that is found and Django considers it to be a safe URL (i.e. it doesn’t point to a different host and uses a safe scheme), a redirect to that URL will be performed. Otherwise, Django may fall back to redirecting the user to the URL from the Referer header or, if it is not set, to /, depending on the nature of the request: If the request accepts HTML content (based on its Accept HTTP header), the fallback will always be performed. If the request doesn’t accept HTML, the fallback will be performed only if the next parameter was set. Otherwise a 204 status code (No Content) will be returned. Here’s example HTML template code: {% load i18n %}
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}">
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go">
</form>
In this example, Django looks up the URL of the page to which the user will be redirected in the redirect_to context variable. Explicitly setting the active language You may want to set the active language for the current session explicitly. Perhaps a user’s language preference is retrieved from another system, for example. You’ve already been introduced to django.utils.translation.activate(). That applies to the current thread only. To persist the language for the entire session in a cookie, set the LANGUAGE_COOKIE_NAME cookie on the response: from django.conf import settings
from django.http import HttpResponse
from django.utils import translation
user_language = 'fr'
translation.activate(user_language)
response = HttpResponse(...)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)
You would typically want to use both: django.utils.translation.activate() changes the language for this thread, and setting the cookie makes this preference persist in future requests. Using translations outside views and templates While Django provides a rich set of i18n tools for use in views and templates, it does not restrict the usage to Django-specific code. The Django translation mechanisms can be used to translate arbitrary texts to any language that is supported by Django (as long as an appropriate translation catalog exists, of course). You can load a translation catalog, activate it and translate text to language of your choice, but remember to switch back to original language, as activating a translation catalog is done on per-thread basis and such change will affect code running in the same thread. For example: from django.utils import translation
def welcome_translated(language):
cur_language = translation.get_language()
try:
translation.activate(language)
text = translation.gettext('welcome')
finally:
translation.activate(cur_language)
return text
Calling this function with the value 'de' will give you "Willkommen", regardless of LANGUAGE_CODE and language set by middleware. Functions of particular interest are django.utils.translation.get_language() which returns the language used in the current thread, django.utils.translation.activate() which activates a translation catalog for the current thread, and django.utils.translation.check_for_language() which checks if the given language is supported by Django. To help write more concise code, there is also a context manager django.utils.translation.override() that stores the current language on enter and restores it on exit. With it, the above example becomes: from django.utils import translation
def welcome_translated(language):
with translation.override(language):
return translation.gettext('welcome')
Language cookie A number of settings can be used to adjust language cookie options: LANGUAGE_COOKIE_NAME LANGUAGE_COOKIE_AGE LANGUAGE_COOKIE_DOMAIN LANGUAGE_COOKIE_HTTPONLY LANGUAGE_COOKIE_PATH LANGUAGE_COOKIE_SAMESITE LANGUAGE_COOKIE_SECURE Implementation notes Specialties of Django translation Django’s translation machinery uses the standard gettext module that comes with Python. If you know gettext, you might note these specialties in the way Django does translation: The string domain is django or djangojs. This string domain is used to differentiate between different programs that store their data in a common message-file library (usually /usr/share/locale/). The django domain is used for Python and template translation strings and is loaded into the global translation catalogs. The djangojs domain is only used for JavaScript translation catalogs to make sure that those are as small as possible. Django doesn’t use xgettext alone. It uses Python wrappers around xgettext and msgfmt. This is mostly for convenience. How Django discovers language preference Once you’ve prepared your translations – or, if you want to use the translations that come with Django – you’ll need to activate translation for your app. Behind the scenes, Django has a very flexible model of deciding which language should be used – installation-wide, for a particular user, or both. To set an installation-wide language preference, set LANGUAGE_CODE. Django uses this language as the default translation – the final attempt if no better matching translation is found through one of the methods employed by the locale middleware (see below). If all you want is to run Django with your native language all you need to do is set LANGUAGE_CODE and make sure the corresponding message files and their compiled versions (.mo) exist. If you want to let each individual user specify which language they prefer, then you also need to use the LocaleMiddleware. LocaleMiddleware enables language selection based on data from the request. It customizes content for each user. To use LocaleMiddleware, add 'django.middleware.locale.LocaleMiddleware' to your MIDDLEWARE setting. Because middleware order matters, follow these guidelines: Make sure it’s one of the first middleware installed. It should come after SessionMiddleware, because LocaleMiddleware makes use of session data. And it should come before CommonMiddleware because CommonMiddleware needs an activated language in order to resolve the requested URL. If you use CacheMiddleware, put LocaleMiddleware after it. For example, your MIDDLEWARE might look like this: MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
]
(For more on middleware, see the middleware documentation.) LocaleMiddleware tries to determine the user’s language preference by following this algorithm: First, it looks for the language prefix in the requested URL. This is only performed when you are using the i18n_patterns function in your root URLconf. See Internationalization: in URL patterns for more information about the language prefix and how to internationalize URL patterns.
Failing that, it looks for a cookie. The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.) Failing that, it looks at the Accept-Language HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations. Failing that, it uses the global LANGUAGE_CODE setting. Notes: In each of these places, the language preference is expected to be in the standard language format, as a string. For example, Brazilian Portuguese is pt-br. If a base language is available but the sublanguage specified is not, Django uses the base language. For example, if a user specifies de-at (Austrian German) but Django only has de available, Django uses de.
Only languages listed in the LANGUAGES setting can be selected. If you want to restrict the language selection to a subset of provided languages (because your application doesn’t provide all those languages), set LANGUAGES to a list of languages. For example: LANGUAGES = [
('de', _('German')),
('en', _('English')),
]
This example restricts languages that are available for automatic selection to German and English (and any sublanguage, like de-ch or en-us).
If you define a custom LANGUAGES setting, as explained in the previous bullet, you can mark the language names as translation strings – but use gettext_lazy() instead of gettext() to avoid a circular import. Here’s a sample settings file: from django.utils.translation import gettext_lazy as _
LANGUAGES = [
('de', _('German')),
('en', _('English')),
]
Once LocaleMiddleware determines the user’s preference, it makes this preference available as request.LANGUAGE_CODE for each HttpRequest. Feel free to read this value in your view code. Here’s an example: from django.http import HttpResponse
def hello_world(request, count):
if request.LANGUAGE_CODE == 'de-at':
return HttpResponse("You prefer to read Austrian German.")
else:
return HttpResponse("You prefer to read another language.")
Note that, with static (middleware-less) translation, the language is in settings.LANGUAGE_CODE, while with dynamic (middleware) translation, it’s in request.LANGUAGE_CODE. How Django discovers translations At runtime, Django builds an in-memory unified catalog of literals-translations. To achieve this it looks for translations by following this algorithm regarding the order in which it examines the different file paths to load the compiled message files (.mo) and the precedence of multiple translations for the same literal: The directories listed in LOCALE_PATHS have the highest precedence, with the ones appearing first having higher precedence than the ones appearing later. Then, it looks for and uses if it exists a locale directory in each of the installed apps listed in INSTALLED_APPS. The ones appearing first have higher precedence than the ones appearing later. Finally, the Django-provided base translation in django/conf/locale is used as a fallback. See also The translations for literals included in JavaScript assets are looked up following a similar but not identical algorithm. See JavaScriptCatalog for more details. You can also put custom format files in the LOCALE_PATHS directories if you also set FORMAT_MODULE_PATH. In all cases the name of the directory containing the translation is expected to be named using locale name notation. E.g. de, pt_BR, es_AR, etc. Untranslated strings for territorial language variants use the translations of the generic language. For example, untranslated pt_BR strings use pt translations. This way, you can write applications that include their own translations, and you can override base translations in your project. Or, you can build a big project out of several apps and put all translations into one big common message file specific to the project you are composing. The choice is yours. All message file repositories are structured the same way. They are: All paths listed in LOCALE_PATHS in your settings file are searched for <language>/LC_MESSAGES/django.(po|mo)
$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo) $PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo) To create message files, you use the django-admin makemessages tool. And you use django-admin compilemessages to produce the binary .mo files that are used by gettext. You can also run django-admin compilemessages
--settings=path.to.settings to make the compiler process all the directories in your LOCALE_PATHS setting. Using a non-English base language Django makes the general assumption that the original strings in a translatable project are written in English. You can choose another language, but you must be aware of certain limitations:
gettext only provides two plural forms for the original messages, so you will also need to provide a translation for the base language to include all plural forms if the plural rules for the base language are different from English. When an English variant is activated and English strings are missing, the fallback language will not be the LANGUAGE_CODE of the project, but the original strings. For example, an English user visiting a site with LANGUAGE_CODE set to Spanish and original strings written in Russian will see Russian text rather than Spanish. | |
doc_239 | See Migration guide for more details. tf.compat.v1.raw_ops.QuantizedReluX
tf.raw_ops.QuantizedReluX(
features, max_value, min_features, max_features, out_type=tf.dtypes.quint8,
name=None
)
Args
features A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16.
max_value A Tensor of type float32.
min_features A Tensor of type float32. The float value that the lowest quantized value represents.
max_features A Tensor of type float32. The float value that the highest quantized value represents.
out_type An optional tf.DType from: tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16. Defaults to tf.quint8.
name A name for the operation (optional).
Returns A tuple of Tensor objects (activations, min_activations, max_activations). activations A Tensor of type out_type.
min_activations A Tensor of type float32.
max_activations A Tensor of type float32. | |
doc_240 |
Set the locator of the major ticker. Parameters
locatorLocator
Examples using matplotlib.axis.Axis.set_major_locator
Hatch-filled histograms
Creating a timeline with lines, dates, and text
Date tick labels
Anatomy of a figure
3D surface (colormap)
3D surface (checkerboard)
Scales
MRI With EEG
SkewT-logP diagram: using transforms and custom projections
Centering labels between ticks
Formatting date ticks using ConciseDateFormatter
Date Demo Convert
Placing date ticks using recurrence rules
Major and minor ticks
Setting tick labels from a list of values
Choosing Colormaps in Matplotlib
Text in Matplotlib Plots | |
doc_241 | See Migration guide for more details. tf.compat.v1.train.Features.FeatureEntry
Attributes
key string key
value Feature value | |
doc_242 | tf.nn.embedding_lookup_sparse(
params, sp_ids, sp_weights, combiner=None, max_norm=None, name=None
)
This op assumes that there is at least one id for each row in the dense tensor represented by sp_ids (i.e. there are no rows with empty features), and that all the indices of sp_ids are in canonical row-major order. sp_ids and sp_weights (if not None) are SparseTensors with rank of 2. Embeddings are always aggregated along the last dimension. It also assumes that all id values lie in the range [0, p0), where p0 is the sum of the size of params along dimension 0. If len(params) > 1, each element of sp_ids is partitioned between the elements of params according to the "div" partition strategy, which means we assign ids to partitions in a contiguous manner. For instance, 13 ids are split across 5 partitions as: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]. If the id space does not evenly divide the number of partitions, each of the first (max_id + 1) % len(params) partitions will be assigned one more id.
Args
params A single tensor representing the complete embedding tensor, or a list of tensors all of same shape except for the first dimension, representing sharded embedding tensors following "div" partition strategy.
sp_ids N x M SparseTensor of int64 ids where N is typically batch size and M is arbitrary.
sp_weights either a SparseTensor of float / double weights, or None to indicate all weights should be taken to be 1. If specified, sp_weights must have exactly the same shape and indices as sp_ids.
combiner A string specifying the reduction op. Currently "mean", "sqrtn" and "sum" are supported. "sum" computes the weighted sum of the embedding results for each row. "mean" is the weighted sum divided by the total weight. "sqrtn" is the weighted sum divided by the square root of the sum of the squares of the weights. Defaults to mean.
max_norm If not None, each embedding is clipped if its l2-norm is larger than this value, before combining.
name Optional name for the op.
Returns A dense tensor representing the combined embeddings for the sparse ids. For each row in the dense tensor represented by sp_ids, the op looks up the embeddings for all ids in that row, multiplies them by the corresponding weight, and combines these embeddings as specified. In other words, if shape(combined params) = [p0, p1, ..., pm] and shape(sp_ids) = shape(sp_weights) = [d0, d1] then shape(output) = [d0, p1, ..., pm]. For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are [0, 0]: id 1, weight 2.0
[0, 1]: id 3, weight 0.5
[1, 0]: id 0, weight 1.0
[2, 3]: id 1, weight 3.0
with combiner="mean", then the output will be a 3x20 matrix where output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
output[1, :] = (params[0, :] * 1.0) / 1.0
output[2, :] = (params[1, :] * 3.0) / 3.0
Raises
TypeError If sp_ids is not a SparseTensor, or if sp_weights is neither None nor SparseTensor.
ValueError If combiner is not one of {"mean", "sqrtn", "sum"}. | |
doc_243 |
Resume the animation. | |
doc_244 | A string containing the format (in struct module style) for each element in the view. A memoryview can be created from exporters with arbitrary format strings, but some methods (e.g. tolist()) are restricted to native single element formats. Changed in version 3.3: format 'B' is now handled according to the struct module syntax. This means that memoryview(b'abc')[0] == b'abc'[0] == 97. | |
doc_245 |
Return the SubplotParams for the GridSpec. In order of precedence the values are taken from non-None attributes of the GridSpec the provided figure
rcParams["figure.subplot.*"] | |
doc_246 | See Migration guide for more details. tf.compat.v1.raw_ops.ReaderNumWorkUnitsCompleted
tf.raw_ops.ReaderNumWorkUnitsCompleted(
reader_handle, name=None
)
Args
reader_handle A Tensor of type mutable string. Handle to a Reader.
name A name for the operation (optional).
Returns A Tensor of type int64. | |
doc_247 | sklearn.metrics.label_ranking_loss(y_true, y_score, *, sample_weight=None) [source]
Compute Ranking loss measure. Compute the average number of label pairs that are incorrectly ordered given y_score weighted by the size of the label set and the number of labels not in the label set. This is similar to the error set size, but weighted by the number of relevant and irrelevant labels. The best performance is achieved with a ranking loss of zero. Read more in the User Guide. New in version 0.17: A function label_ranking_loss Parameters
y_true{ndarray, sparse matrix} of shape (n_samples, n_labels)
True binary labels in binary indicator format.
y_scorendarray of shape (n_samples, n_labels)
Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by “decision_function” on some classifiers).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
lossfloat
References
1
Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and knowledge discovery handbook (pp. 667-685). Springer US. | |
doc_248 | A subclass of HTTPException. | |
doc_249 |
Parameters:
regex – If not None, overrides regex. Can be a regular expression string or a pre-compiled regular expression.
message – If not None, overrides message.
code – If not None, overrides code.
inverse_match – If not None, overrides inverse_match.
flags – If not None, overrides flags. In that case, regex must be a regular expression string, or TypeError is raised. A RegexValidator searches the provided value for a given regular expression with re.search(). By default, raises a ValidationError with message and code if a match is not found. Its behavior can be inverted by setting inverse_match to True, in which case the ValidationError is raised when a match is found.
regex
The regular expression pattern to search for within the provided value, using re.search(). This may be a string or a pre-compiled regular expression created with re.compile(). Defaults to the empty string, which will be found in every possible value.
message
The error message used by ValidationError if validation fails. Defaults to "Enter a valid value".
code
The error code used by ValidationError if validation fails. Defaults to "invalid".
inverse_match
The match mode for regex. Defaults to False.
flags
The regex flags used when compiling the regular expression string regex. If regex is a pre-compiled regular expression, and flags is overridden, TypeError is raised. Defaults to 0. | |
doc_250 |
Predict class log-probabilities for X. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
parray of shape (n_samples, n_classes)
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. | |
doc_251 |
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation. | |
doc_252 |
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor). | |
doc_253 |
Return whether rotations of the transform affect the text direction. | |
doc_254 |
Transform self.module and return the transformed GraphModule. | |
doc_255 | tf.experimental.numpy.fabs(
x
)
Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.fabs. | |
doc_256 |
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_257 | Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug(). | |
doc_258 | Return a result record of the query, through calling MsiViewFetch(). | |
doc_259 | class sklearn.neural_network.MLPClassifier(hidden_layer_sizes=100, activation='relu', *, solver='adam', alpha=0.0001, batch_size='auto', learning_rate='constant', learning_rate_init=0.001, power_t=0.5, max_iter=200, shuffle=True, random_state=None, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True, early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08, n_iter_no_change=10, max_fun=15000) [source]
Multi-layer Perceptron classifier. This model optimizes the log-loss function using LBFGS or stochastic gradient descent. New in version 0.18. Parameters
hidden_layer_sizestuple, length = n_layers - 2, default=(100,)
The ith element represents the number of neurons in the ith hidden layer.
activation{‘identity’, ‘logistic’, ‘tanh’, ‘relu’}, default=’relu’
Activation function for the hidden layer. ‘identity’, no-op activation, useful to implement linear bottleneck, returns f(x) = x ‘logistic’, the logistic sigmoid function, returns f(x) = 1 / (1 + exp(-x)). ‘tanh’, the hyperbolic tan function, returns f(x) = tanh(x). ‘relu’, the rectified linear unit function, returns f(x) = max(0, x)
solver{‘lbfgs’, ‘sgd’, ‘adam’}, default=’adam’
The solver for weight optimization. ‘lbfgs’ is an optimizer in the family of quasi-Newton methods. ‘sgd’ refers to stochastic gradient descent. ‘adam’ refers to a stochastic gradient-based optimizer proposed by Kingma, Diederik, and Jimmy Ba Note: The default solver ‘adam’ works pretty well on relatively large datasets (with thousands of training samples or more) in terms of both training time and validation score. For small datasets, however, ‘lbfgs’ can converge faster and perform better.
alphafloat, default=0.0001
L2 penalty (regularization term) parameter.
batch_sizeint, default=’auto’
Size of minibatches for stochastic optimizers. If the solver is ‘lbfgs’, the classifier will not use minibatch. When set to “auto”, batch_size=min(200, n_samples)
learning_rate{‘constant’, ‘invscaling’, ‘adaptive’}, default=’constant’
Learning rate schedule for weight updates. ‘constant’ is a constant learning rate given by ‘learning_rate_init’. ‘invscaling’ gradually decreases the learning rate at each time step ‘t’ using an inverse scaling exponent of ‘power_t’. effective_learning_rate = learning_rate_init / pow(t, power_t) ‘adaptive’ keeps the learning rate constant to ‘learning_rate_init’ as long as training loss keeps decreasing. Each time two consecutive epochs fail to decrease training loss by at least tol, or fail to increase validation score by at least tol if ‘early_stopping’ is on, the current learning rate is divided by 5. Only used when solver='sgd'.
learning_rate_initdouble, default=0.001
The initial learning rate used. It controls the step-size in updating the weights. Only used when solver=’sgd’ or ‘adam’.
power_tdouble, default=0.5
The exponent for inverse scaling learning rate. It is used in updating effective learning rate when the learning_rate is set to ‘invscaling’. Only used when solver=’sgd’.
max_iterint, default=200
Maximum number of iterations. The solver iterates until convergence (determined by ‘tol’) or this number of iterations. For stochastic solvers (‘sgd’, ‘adam’), note that this determines the number of epochs (how many times each data point will be used), not the number of gradient steps.
shufflebool, default=True
Whether to shuffle samples in each iteration. Only used when solver=’sgd’ or ‘adam’.
random_stateint, RandomState instance, default=None
Determines random number generation for weights and bias initialization, train-test split if early stopping is used, and batch sampling when solver=’sgd’ or ‘adam’. Pass an int for reproducible results across multiple function calls. See Glossary.
tolfloat, default=1e-4
Tolerance for the optimization. When the loss or score is not improving by at least tol for n_iter_no_change consecutive iterations, unless learning_rate is set to ‘adaptive’, convergence is considered to be reached and training stops.
verbosebool, default=False
Whether to print progress messages to stdout.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See the Glossary.
momentumfloat, default=0.9
Momentum for gradient descent update. Should be between 0 and 1. Only used when solver=’sgd’.
nesterovs_momentumbool, default=True
Whether to use Nesterov’s momentum. Only used when solver=’sgd’ and momentum > 0.
early_stoppingbool, default=False
Whether to use early stopping to terminate training when validation score is not improving. If set to true, it will automatically set aside 10% of training data as validation and terminate training when validation score is not improving by at least tol for n_iter_no_change consecutive epochs. The split is stratified, except in a multilabel setting. Only effective when solver=’sgd’ or ‘adam’
validation_fractionfloat, default=0.1
The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if early_stopping is True
beta_1float, default=0.9
Exponential decay rate for estimates of first moment vector in adam, should be in [0, 1). Only used when solver=’adam’
beta_2float, default=0.999
Exponential decay rate for estimates of second moment vector in adam, should be in [0, 1). Only used when solver=’adam’
epsilonfloat, default=1e-8
Value for numerical stability in adam. Only used when solver=’adam’
n_iter_no_changeint, default=10
Maximum number of epochs to not meet tol improvement. Only effective when solver=’sgd’ or ‘adam’ New in version 0.20.
max_funint, default=15000
Only used when solver=’lbfgs’. Maximum number of loss function calls. The solver iterates until convergence (determined by ‘tol’), number of iterations reaches max_iter, or this number of loss function calls. Note that number of loss function calls will be greater than or equal to the number of iterations for the MLPClassifier. New in version 0.22. Attributes
classes_ndarray or list of ndarray of shape (n_classes,)
Class labels for each output.
loss_float
The current loss computed with the loss function.
best_loss_float
The minimum loss reached by the solver throughout fitting.
loss_curve_list of shape (n_iter_,)
The ith element in the list represents the loss at the ith iteration.
t_int
The number of training samples seen by the solver during fitting.
coefs_list of shape (n_layers - 1,)
The ith element in the list represents the weight matrix corresponding to layer i.
intercepts_list of shape (n_layers - 1,)
The ith element in the list represents the bias vector corresponding to layer i + 1.
n_iter_int
The number of iterations the solver has ran.
n_layers_int
Number of layers.
n_outputs_int
Number of outputs.
out_activation_str
Name of the output activation function. Notes MLPClassifier trains iteratively since at each time step the partial derivatives of the loss function with respect to the model parameters are computed to update the parameters. It can also have a regularization term added to the loss function that shrinks model parameters to prevent overfitting. This implementation works with data represented as dense numpy arrays or sparse scipy arrays of floating point values. References Hinton, Geoffrey E.
“Connectionist learning procedures.” Artificial intelligence 40.1 (1989): 185-234. Glorot, Xavier, and Yoshua Bengio. “Understanding the difficulty of
training deep feedforward neural networks.” International Conference on Artificial Intelligence and Statistics. 2010. He, Kaiming, et al. “Delving deep into rectifiers: Surpassing human-level
performance on imagenet classification.” arXiv preprint arXiv:1502.01852 (2015). Kingma, Diederik, and Jimmy Ba. “Adam: A method for stochastic
optimization.” arXiv preprint arXiv:1412.6980 (2014). Examples >>> from sklearn.neural_network import MLPClassifier
>>> from sklearn.datasets import make_classification
>>> from sklearn.model_selection import train_test_split
>>> X, y = make_classification(n_samples=100, random_state=1)
>>> X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y,
... random_state=1)
>>> clf = MLPClassifier(random_state=1, max_iter=300).fit(X_train, y_train)
>>> clf.predict_proba(X_test[:1])
array([[0.038..., 0.961...]])
>>> clf.predict(X_test[:5, :])
array([1, 0, 1, 0, 1])
>>> clf.score(X_test, y_test)
0.8...
Methods
fit(X, y) Fit the model to data matrix X and target(s) y.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using the multi-layer perceptron classifier
predict_log_proba(X) Return the log of probability estimates.
predict_proba(X) Probability estimates.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]
Fit the model to data matrix X and target(s) y. Parameters
Xndarray or sparse matrix of shape (n_samples, n_features)
The input data.
yndarray of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels in classification, real numbers in regression). Returns
selfreturns a trained MLP model.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
property partial_fit
Update the model with a single iteration over the given data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input data.
yarray-like of shape (n_samples,)
The target values.
classesarray of shape (n_classes,), default=None
Classes across all calls to partial_fit. Can be obtained via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is required for the first call to partial_fit and can be omitted in the subsequent calls. Note that y doesn’t need to contain all labels in classes. Returns
selfreturns a trained MLP model.
predict(X) [source]
Predict using the multi-layer perceptron classifier Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input data. Returns
yndarray, shape (n_samples,) or (n_samples, n_classes)
The predicted classes.
predict_log_proba(X) [source]
Return the log of probability estimates. Parameters
Xndarray of shape (n_samples, n_features)
The input data. Returns
log_y_probndarray of shape (n_samples, n_classes)
The predicted log-probability of the sample for each class in the model, where classes are ordered as they are in self.classes_. Equivalent to log(predict_proba(X))
predict_proba(X) [source]
Probability estimates. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input data. Returns
y_probndarray of shape (n_samples, n_classes)
The predicted probability of the sample for each class in the model, where classes are ordered as they are in self.classes_.
score(X, y, sample_weight=None) [source]
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
Examples using sklearn.neural_network.MLPClassifier
Classifier comparison
Visualization of MLP weights on MNIST
Compare Stochastic learning strategies for MLPClassifier
Varying regularization in Multi-layer Perceptron | |
doc_260 | tf.experimental.numpy.kron(
a, b
)
See the NumPy documentation for numpy.kron. | |
doc_261 |
Fills the input Tensor with values drawn from the normal distribution N(mean,std2)\mathcal{N}(\text{mean}, \text{std}^2) . Parameters
tensor – an n-dimensional torch.Tensor
mean – the mean of the normal distribution
std – the standard deviation of the normal distribution Examples >>> w = torch.empty(3, 5)
>>> nn.init.normal_(w) | |
doc_262 | Is raised by TarInfo.frombuf() if the buffer it gets is invalid. | |
doc_263 |
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses. | |
doc_264 | tf.experimental.numpy.cbrt(
x
)
Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.cbrt. | |
doc_265 |
Alias for get_edgecolor. | |
doc_266 | See Migration guide for more details. tf.compat.v1.raw_ops.MaxPool3D
tf.raw_ops.MaxPool3D(
input, ksize, strides, padding, data_format='NDHWC', name=None
)
Args
input A Tensor. Must be one of the following types: half, bfloat16, float32. Shape [batch, depth, rows, cols, channels] tensor to pool over.
ksize A list of ints that has length >= 5. 1-D tensor of length 5. The size of the window for each dimension of the input tensor. Must have ksize[0] = ksize[4] = 1.
strides A list of ints that has length >= 5. 1-D tensor of length 5. The stride of the sliding window for each dimension of input. Must have strides[0] = strides[4] = 1.
padding A string from: "SAME", "VALID". The type of padding algorithm to use.
data_format An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width].
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_267 | End the scope of a prefix-URI mapping. See startPrefixMapping() for details. This event will always occur after the corresponding endElement() event, but the order of endPrefixMapping() events is not otherwise guaranteed. | |
doc_268 |
Remove a callback based on its observer id. See also add_callback | |
doc_269 | Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It’s discouraged to override this function. Instead one should override the jinja_loader() function instead. The global loader dispatches between the loaders of the application and the individual blueprints. Changelog New in version 0.7. Return type
flask.templating.DispatchingJinjaLoader | |
doc_270 | Fork a child process, using a new pseudo-terminal as the child’s controlling terminal. Return a pair of (pid, fd), where pid is 0 in the child, the new child’s process id in the parent, and fd is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the pty module. If an error occurs OSError is raised. Raises an auditing event os.forkpty with no arguments. Changed in version 3.8: Calling forkpty() in a subinterpreter is no longer supported (RuntimeError is raised). Availability: some flavors of Unix. | |
doc_271 | Sets the public identifier of this InputSource. | |
doc_272 |
[Deprecated] Notes Deprecated since version 3.4: | |
doc_273 |
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters
Xndarray of shape (n_samples_X, n_features)
Left argument of the returned kernel k(X, Y) Returns
K_diagndarray of shape (n_samples_X,)
Diagonal of kernel k(X, X) | |
doc_274 |
Bases: mpl_toolkits.axes_grid1.axes_divider.Divider The Divider class whose rectangle area is specified as a subplot geometry. Parameters
figmatplotlib.figure.Figure
*argstuple (nrows, ncols, index) or int
The array of subplots in the figure has dimensions (nrows,
ncols), and index is the index of the subplot being created. index starts at 1 in the upper left corner and increases to the right. If nrows, ncols, and index are all single digit numbers, then args can be passed as a single 3-digit number (e.g. 234 for (2, 3, 4)). change_geometry(numrows, numcols, num)[source]
[Deprecated] Change subplot geometry, e.g., from (1, 1, 1) to (2, 2, 3). Notes Deprecated since version 3.4.
propertyfigbox[source]
get_geometry()[source]
[Deprecated] Get the subplot geometry, e.g., (2, 2, 3). Notes Deprecated since version 3.4.
get_position()[source]
Return the bounds of the subplot box.
get_subplotspec()[source]
Get the SubplotSpec instance.
set_subplotspec(subplotspec)[source]
Set the SubplotSpec instance.
update_params()[source]
[Deprecated] Notes Deprecated since version 3.4: | |
doc_275 | Return True if the stream supports writing. If False, write() and truncate() will raise OSError. | |
doc_276 |
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event. | |
doc_277 | turtle.rt(angle)
Parameters
angle – a number (integer or float) Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode(). >>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0 | |
doc_278 | Returns the current position of the file pointer. | |
doc_279 | See torch.allclose() | |
doc_280 |
Return whether the colormap is grayscale. | |
doc_281 |
Calculate the expanding rank. New in version 1.4.0. Parameters
method:{‘average’, ‘min’, ‘max’}, default ‘average’
How to rank the group of records that have the same value (i.e. ties): average: average rank of the group min: lowest rank in the group max: highest rank in the group
ascending:bool, default True
Whether or not the elements should be ranked in ascending order.
pct:bool, default False
Whether or not to display the returned rankings in percentile form. **kwargs
For NumPy compatibility and will not have an effect on the result. Returns
Series or DataFrame
Return type is the same as the original object with np.float64 dtype. See also pandas.Series.expanding
Calling expanding with Series data. pandas.DataFrame.expanding
Calling expanding with DataFrames. pandas.Series.rank
Aggregating rank for Series. pandas.DataFrame.rank
Aggregating rank for DataFrame. Examples
>>> s = pd.Series([1, 4, 2, 3, 5, 3])
>>> s.expanding().rank()
0 1.0
1 2.0
2 2.0
3 3.0
4 5.0
5 3.5
dtype: float64
>>> s.expanding().rank(method="max")
0 1.0
1 2.0
2 2.0
3 3.0
4 5.0
5 4.0
dtype: float64
>>> s.expanding().rank(method="min")
0 1.0
1 2.0
2 2.0
3 3.0
4 5.0
5 3.0
dtype: float64 | |
doc_282 |
Empty the stack. | |
doc_283 | Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This function should only be called from an exception handler. | |
doc_284 |
Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. Parameters
tupsequence of ndarrays
The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Returns
stackedndarray
The array formed by stacking the given arrays, will be at least 2-D. See also concatenate
Join a sequence of arrays along an existing axis. stack
Join a sequence of arrays along a new axis. block
Assemble an nd-array from nested lists of blocks. hstack
Stack arrays in sequence horizontally (column wise). dstack
Stack arrays in sequence depth wise (along third axis). column_stack
Stack 1-D arrays as columns into a 2-D array. vsplit
Split an array into multiple sub-arrays vertically (row-wise). Examples >>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[4],
[5],
[6]]) | |
doc_285 | These decorators can be used to generate ETag and Last-Modified headers; see conditional view processing. | |
doc_286 |
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels. | |
doc_287 | Get the position of an entry or raise ValueError. Parameters
key – The key to be looked up. Changelog Changed in version 0.5: This used to raise IndexError, which was inconsistent with the list API. | |
doc_288 | See Migration guide for more details. tf.compat.v1.app.flags.EnumClassFlag
tf.compat.v1.flags.EnumClassFlag(
name, default, help, enum_class, short_name=None, case_sensitive=False, **args
)
Attributes
value
Methods flag_type
flag_type()
Returns a str that describes the type of the flag.
Note: we use strings, and not the types.*Type constants because our flags can have more exotic types, e.g., 'comma separated list of strings', 'whitespace separated list of strings', etc.
parse
parse(
argument
)
Parses string and sets flag value.
Args
argument str or the correct flag value type, argument to be parsed. serialize
serialize()
Serializes the flag. unparse
unparse()
__eq__
__eq__(
other
)
Return self==value. __ge__
__ge__(
other, NotImplemented=NotImplemented
)
Return a >= b. Computed by @total_ordering from (not a < b). __gt__
__gt__(
other, NotImplemented=NotImplemented
)
Return a > b. Computed by @total_ordering from (not a < b) and (a != b). __le__
__le__(
other, NotImplemented=NotImplemented
)
Return a <= b. Computed by @total_ordering from (a < b) or (a == b). __lt__
__lt__(
other
)
Return self<value. | |
doc_289 |
relation_name
The name of the field on which you’d like to filter the relation.
condition
A Q object to control the filtering. | |
doc_290 | See Migration guide for more details. tf.compat.v1.raw_ops.UnicodeScript
tf.raw_ops.UnicodeScript(
input, name=None
)
This operation converts Unicode code points to script codes corresponding to each code point. Script codes correspond to International Components for Unicode (ICU) UScriptCode values. See ICU project docs for more details on script codes. For an example, see the unicode strings guide on unicode scripts. Returns -1 (USCRIPT_INVALID_CODE) for invalid codepoints. Output shape will match input shape. Examples:
tf.strings.unicode_script([1, 31, 38])
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([0, 0, 0], dtype=int32)>
Args
input A Tensor of type int32. A Tensor of int32 Unicode code points.
name A name for the operation (optional).
Returns A Tensor of type int32. | |
doc_291 |
Set the locators and formatters of axis to instances suitable for this scale. | |
doc_292 |
Aggregate using one or more operations over the specified axis. Parameters
func:function, str, list or dict
Function to use for aggregating the data. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply. Accepted combinations are: function string function name list of functions and/or function names, e.g. [np.sum, 'mean'] dict of axis labels -> functions, function names or list of such. *args
Positional arguments to pass to func. **kwargs
Keyword arguments to pass to func. Returns
scalar, Series or DataFrame
The return can be: scalar : when Series.agg is called with single function Series : when DataFrame.agg is called with a single function DataFrame : when DataFrame.agg is called with several functions Return scalar, Series or DataFrame. See also DataFrame.groupby.aggregate
Aggregate using callable, string, dict, or list of string/callables. DataFrame.resample.transform
Transforms the Series on each group based on the given function. DataFrame.aggregate
Aggregate using one or more operations over the specified axis. Notes agg is an alias for aggregate. Use the alias. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See Mutating with User Defined Function (UDF) methods for more details. A passed user-defined-function will be passed a Series for evaluation. Examples
>>> s = pd.Series([1, 2, 3, 4, 5],
... index=pd.date_range('20130101', periods=5, freq='s'))
>>> s
2013-01-01 00:00:00 1
2013-01-01 00:00:01 2
2013-01-01 00:00:02 3
2013-01-01 00:00:03 4
2013-01-01 00:00:04 5
Freq: S, dtype: int64
>>> r = s.resample('2s')
>>> r.agg(np.sum)
2013-01-01 00:00:00 3
2013-01-01 00:00:02 7
2013-01-01 00:00:04 5
Freq: 2S, dtype: int64
>>> r.agg(['sum', 'mean', 'max'])
sum mean max
2013-01-01 00:00:00 3 1.5 2
2013-01-01 00:00:02 7 3.5 4
2013-01-01 00:00:04 5 5.0 5
>>> r.agg({'result': lambda x: x.mean() / x.std(),
... 'total': np.sum})
result total
2013-01-01 00:00:00 2.121320 3
2013-01-01 00:00:02 4.949747 7
2013-01-01 00:00:04 NaN 5
>>> r.agg(average="mean", total="sum")
average total
2013-01-01 00:00:00 1.5 3
2013-01-01 00:00:02 3.5 7
2013-01-01 00:00:04 5.0 5 | |
doc_293 |
Generates an octagon shaped structuring element. For a given size of (m) horizontal and vertical sides and a given (n) height or width of slanted sides octagon is generated. The slanted sides are 45 or 135 degrees to the horizontal axis and hence the widths and heights are equal. Parameters
mint
The size of the horizontal and vertical sides.
nint
The height or width of the slanted sides. Returns
selemndarray
The structuring element where elements of the neighborhood are 1 and 0 otherwise. Other Parameters
dtypedata-type
The data type of the structuring element. | |
doc_294 |
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array. | |
doc_295 | tf.compat.v1.test.compute_gradient(
x, x_shape, y, y_shape, x_init_value=None, delta=0.001, init_targets=None,
extra_feed_dict=None
)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.test.compute_gradient in 2.0, which has better support for functions. Note that the two versions have different usage, so code change is needed. If x or y is complex, the Jacobian will still be real but the corresponding Jacobian dimension(s) will be twice as large. This is required even if both input and output is complex since TensorFlow graphs are not necessarily holomorphic, and may have gradients not expressible as complex numbers. For example, if x is complex with shape [m] and y is complex with shape [n], each Jacobian J will have shape [m * 2, n * 2] with J[:m, :n] = d(Re y)/d(Re x)
J[:m, n:] = d(Im y)/d(Re x)
J[m:, :n] = d(Re y)/d(Im x)
J[m:, n:] = d(Im y)/d(Im x)
Args
x a tensor or list of tensors
x_shape the dimensions of x as a tuple or an array of ints. If x is a list, then this is the list of shapes.
y a tensor
y_shape the dimensions of y as a tuple or an array of ints.
x_init_value (optional) a numpy array of the same shape as "x" representing the initial value of x. If x is a list, this should be a list of numpy arrays. If this is none, the function will pick a random tensor as the initial value.
delta (optional) the amount of perturbation.
init_targets list of targets to run to initialize model params.
extra_feed_dict dict that allows fixing specified tensor values during the Jacobian calculation.
Returns Two 2-d numpy arrays representing the theoretical and numerical Jacobian for dy/dx. Each has "x_size" rows and "y_size" columns where "x_size" is the number of elements in x and "y_size" is the number of elements in y. If x is a list, returns a list of two numpy arrays. | |
doc_296 |
Draw samples from a negative binomial distribution. Samples are drawn from a negative binomial distribution with specified parameters, n successes and p probability of success where n is > 0 and p is in the interval [0, 1]. Note New code should use the negative_binomial method of a default_rng() instance instead; please see the Quick Start. Parameters
nfloat or array_like of floats
Parameter of the distribution, > 0.
pfloat or array_like of floats
Parameter of the distribution, >= 0 and <=1.
sizeint or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if n and p are both scalars. Otherwise, np.broadcast(n, p).size samples are drawn. Returns
outndarray or scalar
Drawn samples from the parameterized negative binomial distribution, where each sample is equal to N, the number of failures that occurred before a total of n successes was reached. See also Generator.negative_binomial
which should be used for new code. Notes The probability mass function of the negative binomial distribution is \[P(N;n,p) = \frac{\Gamma(N+n)}{N!\Gamma(n)}p^{n}(1-p)^{N},\] where \(n\) is the number of successes, \(p\) is the probability of success, \(N+n\) is the number of trials, and \(\Gamma\) is the gamma function. When \(n\) is an integer, \(\frac{\Gamma(N+n)}{N!\Gamma(n)} = \binom{N+n-1}{N}\), which is the more common form of this term in the the pmf. The negative binomial distribution gives the probability of N failures given n successes, with a success on the last trial. If one throws a die repeatedly until the third time a “1” appears, then the probability distribution of the number of non-“1”s that appear before the third “1” is a negative binomial distribution. References 1
Weisstein, Eric W. “Negative Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/NegativeBinomialDistribution.html 2
Wikipedia, “Negative binomial distribution”, https://en.wikipedia.org/wiki/Negative_binomial_distribution Examples Draw samples from the distribution: A real world example. A company drills wild-cat oil exploration wells, each with an estimated probability of success of 0.1. What is the probability of having one success for each successive well, that is what is the probability of a single success after drilling 5 wells, after 6 wells, etc.? >>> s = np.random.negative_binomial(1, 0.1, 100000)
>>> for i in range(1, 11):
... probability = sum(s<i) / 100000.
... print(i, "wells drilled, probability of one success =", probability) | |
doc_297 | The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server. | |
doc_298 | See torch.log10() | |
doc_299 | See Migration guide for more details. tf.compat.v1.raw_ops.FusedBatchNorm
tf.raw_ops.FusedBatchNorm(
x, scale, offset, mean, variance, epsilon=0.0001, exponential_avg_factor=1,
data_format='NHWC', is_training=True, name=None
)
Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". The size of 1D Tensors matches the dimension C of the 4D Tensors.
Args
x A Tensor. Must be one of the following types: float32. A 4D Tensor for input data.
scale A Tensor. Must have the same type as x. A 1D Tensor for scaling factor, to scale the normalized x.
offset A Tensor. Must have the same type as x. A 1D Tensor for offset, to shift to the normalized x.
mean A Tensor. Must have the same type as x. A 1D Tensor for population mean. Used for inference only; must be empty for training.
variance A Tensor. Must have the same type as x. A 1D Tensor for population variance. Used for inference only; must be empty for training.
epsilon An optional float. Defaults to 0.0001. A small float number added to the variance of x.
exponential_avg_factor An optional float. Defaults to 1.
data_format An optional string from: "NHWC", "NCHW". Defaults to "NHWC". The data format for x and y. Either "NHWC" (default) or "NCHW".
is_training An optional bool. Defaults to True. A bool value to indicate the operation is for training (default) or inference.
name A name for the operation (optional).
Returns A tuple of Tensor objects (y, batch_mean, batch_variance, reserve_space_1, reserve_space_2). y A Tensor. Has the same type as x.
batch_mean A Tensor. Has the same type as x.
batch_variance A Tensor. Has the same type as x.
reserve_space_1 A Tensor. Has the same type as x.
reserve_space_2 A Tensor. Has the same type as x. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.