_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_3500 | A generic version of collections.abc.ItemsView. Deprecated since version 3.9: collections.abc.ItemsView now supports []. See PEP 585 and Generic Alias Type. | |
doc_3501 | Return a str containing the entire contents of the buffer. Newlines are decoded as if by read(), although the stream position is not changed. | |
doc_3502 |
Given the location and size of the box, return the path of the box around it. Parameters
x0, y0, width, heightfloat
Location and size of the box.
mutation_sizefloat
A reference scale for the mutation. Returns
Path | |
doc_3503 |
Evaluate a 2-D Hermite series on the Cartesian product of x and y. This function returns the values: \[p(a,b) = \sum_{i,j} c_{i,j} * H_i(a) * H_j(b)\] where the points (a, b) consist of all pairs formed by taking a from x and b from y. The resulting points form a grid with x in the first dimension and y in the second. The parameters x and y are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either x and y or their elements must support multiplication and addition both with themselves and with the elements of c. If c has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters
x, yarray_like, compatible objects
The two dimensional series is evaluated at the points in the Cartesian product of x and y. If x or y is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn’t an ndarray, it is treated as a scalar.
carray_like
Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in c[i,j]. If c has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns
valuesndarray, compatible object
The values of the two dimensional polynomial at points in the Cartesian product of x and y. See also
hermval, hermval2d, hermval3d, hermgrid3d
Notes New in version 1.7.0. | |
doc_3504 | Raised when a future is cancelled. | |
doc_3505 | tf.nn.space_to_batch
tf.space_to_batch(
input, block_shape, paddings, name=None
)
This operation divides "spatial" dimensions [1, ..., M] of the input into a grid of blocks of shape block_shape, and interleaves these blocks with the "batch" dimension (0) such that in the output, the spatial dimensions [1, ..., M] correspond to the position within the grid, and the batch dimension combines both the position within a spatial block and the original batch position. Prior to division into blocks, the spatial dimensions of the input are optionally zero padded according to paddings. See below for a precise description.
Args
input A Tensor. N-D with shape input_shape = [batch] + spatial_shape + remaining_shape, where spatial_shape has M dimensions.
block_shape A Tensor. Must be one of the following types: int32, int64. 1-D with shape [M], all values must be >= 1.
paddings A Tensor. Must be one of the following types: int32, int64. 2-D with shape [M, 2], all values must be >= 0. paddings[i] = [pad_start, pad_end] specifies the padding for input dimension i + 1, which corresponds to spatial dimension i. It is required that block_shape[i] divides input_shape[i + 1] + pad_start + pad_end. This operation is equivalent to the following steps: Zero-pad the start and end of dimensions [1, ..., M] of the input according to paddings to produce padded of shape padded_shape. Reshape padded to reshaped_padded of shape: [batch] + [padded_shape[1] / block_shape[0], block_shape[0], ..., padded_shape[M] / block_shape[M-1], block_shape[M-1]] + remaining_shape Permute dimensions of reshaped_padded to produce permuted_reshaped_padded of shape: block_shape + [batch] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape Reshape permuted_reshaped_padded to flatten block_shape into the batch dimension, producing an output tensor of shape: [batch * prod(block_shape)] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape Some examples: (1) For the following input of shape [1, 2, 2, 1], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]: x = [[[[1], [2]], [[3], [4]]]]
The output tensor has shape [4, 1, 1, 1] and value: [[[[1]]], [[[2]]], [[[3]]], [[[4]]]]
(2) For the following input of shape [1, 2, 2, 3], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]: x = [[[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]]]
The output tensor has shape [4, 1, 1, 3] and value: [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]
(3) For the following input of shape [1, 4, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [0, 0]]: x = [[[[1], [2], [3], [4]],
[[5], [6], [7], [8]],
[[9], [10], [11], [12]],
[[13], [14], [15], [16]]]]
The output tensor has shape [4, 2, 2, 1] and value: x = [[[[1], [3]], [[9], [11]]],
[[[2], [4]], [[10], [12]]],
[[[5], [7]], [[13], [15]]],
[[[6], [8]], [[14], [16]]]]
(4) For the following input of shape [2, 2, 4, 1], block_shape = [2, 2], and paddings = [[0, 0], [2, 0]]: x = [[[[1], [2], [3], [4]],
[[5], [6], [7], [8]]],
[[[9], [10], [11], [12]],
[[13], [14], [15], [16]]]]
The output tensor has shape [8, 1, 3, 1] and value: x = [[[[0], [1], [3]]], [[[0], [9], [11]]],
[[[0], [2], [4]]], [[[0], [10], [12]]],
[[[0], [5], [7]]], [[[0], [13], [15]]],
[[[0], [6], [8]]], [[[0], [14], [16]]]]
Among others, this operation is useful for reducing atrous convolution into regular convolution.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_3506 |
Configure the ScalarFormatter used by default for linear axes. If a parameter is not set, the corresponding property of the formatter is left unchanged. Parameters
axis{'x', 'y', 'both'}, default: 'both'
The axis to configure. Only major ticks are affected.
style{'sci', 'scientific', 'plain'}
Whether to use scientific notation. The formatter default is to use scientific notation.
scilimitspair of ints (m, n)
Scientific notation is used only for numbers outside the range 10m to 10n (and only if the formatter is configured to use scientific notation at all). Use (0, 0) to include all numbers. Use (m, m) where m != 0 to fix the order of magnitude to 10m. The formatter default is rcParams["axes.formatter.limits"] (default: [-5, 6]).
useOffsetbool or float
If True, the offset is calculated as needed. If False, no offset is used. If a numeric value, it sets the offset. The formatter default is rcParams["axes.formatter.useoffset"] (default: True).
useLocalebool
Whether to format the number using the current locale or using the C (English) locale. This affects e.g. the decimal separator. The formatter default is rcParams["axes.formatter.use_locale"] (default: False).
useMathTextbool
Render the offset and scientific notation in mathtext. The formatter default is rcParams["axes.formatter.use_mathtext"] (default: False). Raises
AttributeError
If the current formatter is not a ScalarFormatter.
Examples using matplotlib.axes.Axes.ticklabel_format
The default tick formatter | |
doc_3507 | SimpleTestCase.assertWarnsMessage(expected_warning, expected_message)
Analogous to SimpleTestCase.assertRaisesMessage() but for assertWarnsRegex() instead of assertRaisesRegex(). | |
doc_3508 | Should be called after a request is sent to get the response from the server. Returns an HTTPResponse instance. Note Note that you must have read the whole response before you can send a new request to the server. Changed in version 3.5: If a ConnectionError or subclass is raised, the HTTPConnection object will be ready to reconnect when a new request is sent. | |
doc_3509 | This is the main callback interface in SAX, and the one most important to applications. The order of events in this interface mirrors the order of the information in the document. | |
doc_3510 | Returns the best match from a list of possible matches based on the specificity and quality of the client. If two items have the same quality and specificity, the one is returned that comes first. Parameters
matches – a list of matches to check for
default – the value that is returned if none match | |
doc_3511 |
alias of numpy.bool_ | |
doc_3512 |
Return the artist's zorder. | |
doc_3513 | Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped: >>> ' spacious '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
See str.removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example: >>> 'Monty Python'.rstrip(' Python')
'M'
>>> 'Monty Python'.removesuffix(' Python')
'Monty' | |
doc_3514 |
Black and white silhouette of a horse. This image was downloaded from openclipart No copyright restrictions. CC0 given by owner (Andreas Preuss (marauder)). Returns
horse(328, 400) bool ndarray
Horse image. | |
doc_3515 |
Return self<value. | |
doc_3516 | 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_3517 | bytearray.zfill(width)
Return a copy of the sequence left filled with ASCII b'0' digits to make a sequence of length width. A leading sign prefix (b'+'/ b'-') is handled by inserting the padding after the sign character rather than before. For bytes objects, the original sequence is returned if width is less than or equal to len(seq). For example: >>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | |
doc_3518 |
Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). This is mostly equivalent to calling: pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) but uses much less memory, and is faster for large arrays. This function works with dense 2D arrays only. Parameters
Xarray-like of shape (n_samples_X, n_features)
Array containing points.
Yarray-like of shape (n_samples_Y, n_features)
Arrays containing points.
axisint, default=1
Axis along which the argmin and distances are to be computed.
metricstr or callable, default=”euclidean”
Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics.
metric_kwargsdict, default=None
Keyword arguments to pass to specified metric function. Returns
argminnumpy.ndarray
Y[argmin[i], :] is the row in Y that is closest to X[i, :]. See also
sklearn.metrics.pairwise_distances
sklearn.metrics.pairwise_distances_argmin_min | |
doc_3519 |
Hermite series whose graph is a straight line. Parameters
off, sclscalars
The specified line is given by off + scl*x. Returns
yndarray
This module’s representation of the Hermite series for off + scl*x. See also numpy.polynomial.polynomial.polyline
numpy.polynomial.chebyshev.chebline
numpy.polynomial.legendre.legline
numpy.polynomial.laguerre.lagline
numpy.polynomial.hermite.hermline
Examples >>> from numpy.polynomial.hermite_e import hermeline
>>> from numpy.polynomial.hermite_e import hermeline, hermeval
>>> hermeval(0,hermeline(3, 2))
3.0
>>> hermeval(1,hermeline(3, 2))
5.0 | |
doc_3520 |
Set the missing data representation on a Styler. New in version 1.0.0. Deprecated since version 1.3.0. Parameters
na_rep:str
Returns
self:Styler
Notes This method is deprecated. See Styler.format() | |
doc_3521 |
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_3522 |
Return the product of the values over the requested axis. Parameters
axis:{index (0), columns (1)}
Axis for the function to be applied on.
skipna:bool, default True
Exclude NA/null values when computing the result.
level:int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series.
numeric_only:bool, default None
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
min_count:int, default 0
The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. **kwargs
Additional keyword arguments to be passed to the function. Returns
Series or DataFrame (if level specified)
See also Series.sum
Return the sum. Series.min
Return the minimum. Series.max
Return the maximum. Series.idxmin
Return the index of the minimum. Series.idxmax
Return the index of the maximum. DataFrame.sum
Return the sum over the requested axis. DataFrame.min
Return the minimum over the requested axis. DataFrame.max
Return the maximum over the requested axis. DataFrame.idxmin
Return the index of the minimum over the requested axis. DataFrame.idxmax
Return the index of the maximum over the requested axis. Examples By default, the product of an empty or all-NA Series is 1
>>> pd.Series([], dtype="float64").prod()
1.0
This can be controlled with the min_count parameter
>>> pd.Series([], dtype="float64").prod(min_count=1)
nan
Thanks to the skipna parameter, min_count handles all-NA and empty series identically.
>>> pd.Series([np.nan]).prod()
1.0
>>> pd.Series([np.nan]).prod(min_count=1)
nan | |
doc_3523 |
Returns the lowest common multiple of |x1| and |x2| Parameters
x1, x2array_like, int
Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). Returns
yndarray or scalar
The lowest common multiple of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars. See also gcd
The greatest common divisor Examples >>> np.lcm(12, 20)
60
>>> np.lcm.reduce([3, 12, 20])
60
>>> np.lcm.reduce([40, 12, 20])
120
>>> np.lcm(np.arange(6), 20)
array([ 0, 20, 20, 60, 20, 20]) | |
doc_3524 | Returns total time spent on CPU obtained as a sum of all self times across all the events. | |
doc_3525 |
Returns the random number generator state of the specified GPU as a ByteTensor. Parameters
device (torch.device or int, optional) – The device to return the RNG state of. Default: 'cuda' (i.e., torch.device('cuda'), the current CUDA device). Warning This function eagerly initializes CUDA. | |
doc_3526 |
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
Cheat sheet In a hurry? Here’s how to do common aggregate queries, assuming the models above: # Total number of books.
>>> Book.objects.count()
2452
# Total number of books with publisher=BaloneyPress
>>> Book.objects.filter(publisher__name='BaloneyPress').count()
73
# Average price across all books.
>>> from django.db.models import Avg
>>> Book.objects.all().aggregate(Avg('price'))
{'price__avg': 34.35}
# Max price across all books.
>>> from django.db.models import Max
>>> Book.objects.all().aggregate(Max('price'))
{'price__max': Decimal('81.20')}
# Difference between the highest priced book and the average price of all books.
>>> from django.db.models import FloatField
>>> Book.objects.aggregate(
... price_diff=Max('price', output_field=FloatField()) - Avg('price'))
{'price_diff': 46.85}
# All the following queries involve traversing the Book<->Publisher
# foreign key relationship backwards.
# Each publisher, each with a count of books as a "num_books" attribute.
>>> from django.db.models import Count
>>> pubs = Publisher.objects.annotate(num_books=Count('book'))
>>> pubs
<QuerySet [<Publisher: BaloneyPress>, <Publisher: SalamiPress>, ...]>
>>> pubs[0].num_books
73
# Each publisher, with a separate count of books with a rating above and below 5
>>> from django.db.models import Q
>>> above_5 = Count('book', filter=Q(book__rating__gt=5))
>>> below_5 = Count('book', filter=Q(book__rating__lte=5))
>>> pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5)
>>> pubs[0].above_5
23
>>> pubs[0].below_5
12
# The top 5 publishers, in order by number of books.
>>> pubs = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]
>>> pubs[0].num_books
1323
Generating aggregates over a QuerySet
Django provides two ways to generate aggregates. The first way is to generate summary values over an entire QuerySet. For example, say you wanted to calculate the average price of all books available for sale. Django’s query syntax provides a means for describing the set of all books: >>> Book.objects.all()
What we need is a way to calculate summary values over the objects that belong to this QuerySet. This is done by appending an aggregate() clause onto the QuerySet: >>> from django.db.models import Avg
>>> Book.objects.all().aggregate(Avg('price'))
{'price__avg': 34.35}
The all() is redundant in this example, so this could be simplified to: >>> Book.objects.aggregate(Avg('price'))
{'price__avg': 34.35}
The argument to the aggregate() clause describes the aggregate value that we want to compute - in this case, the average of the price field on the Book model. A list of the aggregate functions that are available can be found in the QuerySet reference. aggregate() is a terminal clause for a QuerySet that, when invoked, returns a dictionary of name-value pairs. The name is an identifier for the aggregate value; the value is the computed aggregate. The name is automatically generated from the name of the field and the aggregate function. If you want to manually specify a name for the aggregate value, you can do so by providing that name when you specify the aggregate clause: >>> Book.objects.aggregate(average_price=Avg('price'))
{'average_price': 34.35}
If you want to generate more than one aggregate, you add another argument to the aggregate() clause. So, if we also wanted to know the maximum and minimum price of all books, we would issue the query: >>> from django.db.models import Avg, Max, Min
>>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
{'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}
Generating aggregates for each item in a QuerySet
The second way to generate summary values is to generate an independent summary for each object in a QuerySet. For example, if you are retrieving a list of books, you may want to know how many authors contributed to each book. Each Book has a many-to-many relationship with the Author; we want to summarize this relationship for each book in the QuerySet. Per-object summaries can be generated using the annotate() clause. When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values. The syntax for these annotations is identical to that used for the aggregate() clause. Each argument to annotate() describes an aggregate that is to be calculated. For example, to annotate books with the number of authors: # Build an annotated queryset
>>> from django.db.models import Count
>>> q = Book.objects.annotate(Count('authors'))
# Interrogate the first object in the queryset
>>> q[0]
<Book: The Definitive Guide to Django>
>>> q[0].authors__count
2
# Interrogate the second object in the queryset
>>> q[1]
<Book: Practical Django Projects>
>>> q[1].authors__count
1
As with aggregate(), the name for the annotation is automatically derived from the name of the aggregate function and the name of the field being aggregated. You can override this default name by providing an alias when you specify the annotation: >>> q = Book.objects.annotate(num_authors=Count('authors'))
>>> q[0].num_authors
2
>>> q[1].num_authors
1
Unlike aggregate(), annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet; this QuerySet can be modified using any other QuerySet operation, including filter(), order_by(), or even additional calls to annotate(). Combining multiple aggregations Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries: >>> book = Book.objects.first()
>>> book.authors.count()
2
>>> book.store_set.count()
3
>>> q = Book.objects.annotate(Count('authors'), Count('store'))
>>> q[0].authors__count
6
>>> q[0].store__count
6
For most aggregates, there is no way to avoid this problem, however, the Count aggregate has a distinct parameter that may help: >>> q = Book.objects.annotate(Count('authors', distinct=True), Count('store', distinct=True))
>>> q[0].authors__count
2
>>> q[0].store__count
3
If in doubt, inspect the SQL query! In order to understand what happens in your query, consider inspecting the query property of your QuerySet. Joins and aggregates So far, we have dealt with aggregates over fields that belong to the model being queried. However, sometimes the value you want to aggregate will belong to a model that is related to the model you are querying. When specifying the field to be aggregated in an aggregate function, Django will allow you to use the same double underscore notation that is used when referring to related fields in filters. Django will then handle any table joins that are required to retrieve and aggregate the related value. For example, to find the price range of books offered in each store, you could use the annotation: >>> from django.db.models import Max, Min
>>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price'))
This tells Django to retrieve the Store model, join (through the many-to-many relationship) with the Book model, and aggregate on the price field of the book model to produce a minimum and maximum value. The same rules apply to the aggregate() clause. If you wanted to know the lowest and highest price of any book that is available for sale in any of the stores, you could use the aggregate: >>> Store.objects.aggregate(min_price=Min('books__price'), max_price=Max('books__price'))
Join chains can be as deep as you require. For example, to extract the age of the youngest author of any book available for sale, you could issue the query: >>> Store.objects.aggregate(youngest_age=Min('books__authors__age'))
Following relationships backwards In a way similar to Lookups that span relationships, aggregations and annotations on fields of models or models that are related to the one you are querying can include traversing “reverse” relationships. The lowercase name of related models and double-underscores are used here too. For example, we can ask for all publishers, annotated with their respective total book stock counters (note how we use 'book' to specify the Publisher -> Book reverse foreign key hop): >>> from django.db.models import Avg, Count, Min, Sum
>>> Publisher.objects.annotate(Count('book'))
(Every Publisher in the resulting QuerySet will have an extra attribute called book__count.) We can also ask for the oldest book of any of those managed by every publisher: >>> Publisher.objects.aggregate(oldest_pubdate=Min('book__pubdate'))
(The resulting dictionary will have a key called 'oldest_pubdate'. If no such alias were specified, it would be the rather long 'book__pubdate__min'.) This doesn’t apply just to foreign keys. It also works with many-to-many relations. For example, we can ask for every author, annotated with the total number of pages considering all the books the author has (co-)authored (note how we use 'book' to specify the Author -> Book reverse many-to-many hop): >>> Author.objects.annotate(total_pages=Sum('book__pages'))
(Every Author in the resulting QuerySet will have an extra attribute called total_pages. If no such alias were specified, it would be the rather long book__pages__sum.) Or ask for the average rating of all the books written by author(s) we have on file: >>> Author.objects.aggregate(average_rating=Avg('book__rating'))
(The resulting dictionary will have a key called 'average_rating'. If no such alias were specified, it would be the rather long 'book__rating__avg'.) Aggregations and other QuerySet clauses
filter() and exclude()
Aggregates can also participate in filters. Any filter() (or exclude()) applied to normal model fields will have the effect of constraining the objects that are considered for aggregation. When used with an annotate() clause, a filter has the effect of constraining the objects for which an annotation is calculated. For example, you can generate an annotated list of all books that have a title starting with “Django” using the query: >>> from django.db.models import Avg, Count
>>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))
When used with an aggregate() clause, a filter has the effect of constraining the objects over which the aggregate is calculated. For example, you can generate the average price of all books with a title that starts with “Django” using the query: >>> Book.objects.filter(name__startswith="Django").aggregate(Avg('price'))
Filtering on annotations Annotated values can also be filtered. The alias for the annotation can be used in filter() and exclude() clauses in the same way as any other model field. For example, to generate a list of books that have more than one author, you can issue the query: >>> Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1)
This query generates an annotated result set, and then generates a filter based upon that annotation. If you need two annotations with two separate filters you can use the filter argument with any aggregate. For example, to generate a list of authors with a count of highly rated books: >>> highly_rated = Count('book', filter=Q(book__rating__gte=7))
>>> Author.objects.annotate(num_books=Count('book'), highly_rated_books=highly_rated)
Each Author in the result set will have the num_books and highly_rated_books attributes. See also Conditional aggregation. Choosing between filter and QuerySet.filter() Avoid using the filter argument with a single annotation or aggregation. It’s more efficient to use QuerySet.filter() to exclude rows. The aggregation filter argument is only useful when using two or more aggregations over the same relations with different conditionals. Order of annotate() and filter() clauses When developing a complex query that involves both annotate() and filter() clauses, pay particular attention to the order in which the clauses are applied to the QuerySet. When an annotate() clause is applied to a query, the annotation is computed over the state of the query up to the point where the annotation is requested. The practical implication of this is that filter() and annotate() are not commutative operations. Given: Publisher A has two books with ratings 4 and 5. Publisher B has two books with ratings 1 and 4. Publisher C has one book with rating 1. Here’s an example with the Count aggregate: >>> a, b = Publisher.objects.annotate(num_books=Count('book', distinct=True)).filter(book__rating__gt=3.0)
>>> a, a.num_books
(<Publisher: A>, 2)
>>> b, b.num_books
(<Publisher: B>, 2)
>>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))
>>> a, a.num_books
(<Publisher: A>, 2)
>>> b, b.num_books
(<Publisher: B>, 1)
Both queries return a list of publishers that have at least one book with a rating exceeding 3.0, hence publisher C is excluded. In the first query, the annotation precedes the filter, so the filter has no effect on the annotation. distinct=True is required to avoid a query bug. The second query counts the number of books that have a rating exceeding 3.0 for each publisher. The filter precedes the annotation, so the filter constrains the objects considered when calculating the annotation. Here’s another example with the Avg aggregate: >>> a, b = Publisher.objects.annotate(avg_rating=Avg('book__rating')).filter(book__rating__gt=3.0)
>>> a, a.avg_rating
(<Publisher: A>, 4.5) # (5+4)/2
>>> b, b.avg_rating
(<Publisher: B>, 2.5) # (1+4)/2
>>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(avg_rating=Avg('book__rating'))
>>> a, a.avg_rating
(<Publisher: A>, 4.5) # (5+4)/2
>>> b, b.avg_rating
(<Publisher: B>, 4.0) # 4/1 (book with rating 1 excluded)
The first query asks for the average rating of all a publisher’s books for publisher’s that have at least one book with a rating exceeding 3.0. The second query asks for the average of a publisher’s book’s ratings for only those ratings exceeding 3.0. It’s difficult to intuit how the ORM will translate complex querysets into SQL queries so when in doubt, inspect the SQL with str(queryset.query) and write plenty of tests. order_by() Annotations can be used as a basis for ordering. When you define an order_by() clause, the aggregates you provide can reference any alias defined as part of an annotate() clause in the query. For example, to order a QuerySet of books by the number of authors that have contributed to the book, you could use the following query: >>> Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')
values() Ordinarily, annotations are generated on a per-object basis - an annotated QuerySet will return one result for each object in the original QuerySet. However, when a values() clause is used to constrain the columns that are returned in the result set, the method for evaluating annotations is slightly different. Instead of returning an annotated result for each result in the original QuerySet, the original results are grouped according to the unique combinations of the fields specified in the values() clause. An annotation is then provided for each unique group; the annotation is computed over all members of the group. For example, consider an author query that attempts to find out the average rating of books written by each author: >>> Author.objects.annotate(average_rating=Avg('book__rating'))
This will return one result for each author in the database, annotated with their average book rating. However, the result will be slightly different if you use a values() clause: >>> Author.objects.values('name').annotate(average_rating=Avg('book__rating'))
In this example, the authors will be grouped by name, so you will only get an annotated result for each unique author name. This means if you have two authors with the same name, their results will be merged into a single result in the output of the query; the average will be computed as the average over the books written by both authors. Order of annotate() and values() clauses As with the filter() clause, the order in which annotate() and values() clauses are applied to a query is significant. If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause. However, if the annotate() clause precedes the values() clause, the annotations will be generated over the entire query set. In this case, the values() clause only constrains the fields that are generated on output. For example, if we reverse the order of the values() and annotate() clause from our previous example: >>> Author.objects.annotate(average_rating=Avg('book__rating')).values('name', 'average_rating')
This will now yield one unique result for each author; however, only the author’s name and the average_rating annotation will be returned in the output data. You should also note that average_rating has been explicitly included in the list of values to be returned. This is required because of the ordering of the values() and annotate() clause. If the values() clause precedes the annotate() clause, any annotations will be automatically added to the result set. However, if the values() clause is applied after the annotate() clause, you need to explicitly include the aggregate column. Interaction with order_by()
Fields that are mentioned in the order_by() part of a queryset are used when selecting the output data, even if they are not otherwise specified in the values() call. These extra fields are used to group “like” results together and they can make otherwise identical result rows appear to be separate. This shows up, particularly, when counting things. By way of example, suppose you have a model like this: from django.db import models
class Item(models.Model):
name = models.CharField(max_length=10)
data = models.IntegerField()
If you want to count how many times each distinct data value appears in an ordered queryset, you might try this: items = Item.objects.order_by('name')
# Warning: not quite correct!
items.values('data').annotate(Count('id'))
…which will group the Item objects by their common data values and then count the number of id values in each group. Except that it won’t quite work. The ordering by name will also play a part in the grouping, so this query will group by distinct (data, name) pairs, which isn’t what you want. Instead, you should construct this queryset: items.values('data').annotate(Count('id')).order_by()
…clearing any ordering in the query. You could also order by, say, data without any harmful effects, since that is already playing a role in the query. This behavior is the same as that noted in the queryset documentation for distinct() and the general rule is the same: normally you won’t want extra columns playing a part in the result, so clear out the ordering, or at least make sure it’s restricted only to those fields you also select in a values() call. Note You might reasonably ask why Django doesn’t remove the extraneous columns for you. The main reason is consistency with distinct() and other places: Django never removes ordering constraints that you have specified (and we can’t change those other methods’ behavior, as that would violate our API stability policy). Aggregating annotations You can also generate an aggregate on the result of an annotation. When you define an aggregate() clause, the aggregates you provide can reference any alias defined as part of an annotate() clause in the query. For example, if you wanted to calculate the average number of authors per book you first annotate the set of books with the author count, then aggregate that author count, referencing the annotation field: >>> from django.db.models import Avg, Count
>>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))
{'num_authors__avg': 1.66} | |
doc_3527 |
Roll provided date forward to next offset only if not on offset. Returns
TimeStamp
Rolled timestamp if not on offset, otherwise unchanged timestamp. | |
doc_3528 | Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. | |
doc_3529 |
Construct an array from an index array and a list of arrays to choose from. First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = numpy.lib.index_tricks): np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)]). But this omits some subtleties. Here is a fully general summary: Given an “index” array (a) of integers and a sequence of n arrays (choices), a and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these Ba and Bchoices[i], i = 0,…,n-1 we have that, necessarily, Ba.shape == Bchoices[i].shape for each i. Then, a new array with shape Ba.shape is created as follows: if mode='raise' (the default), then, first of all, each element of a (and thus Ba) must be in the range [0, n-1]; now, suppose that i (in that range) is the value at the (j0, j1, ..., jm) position in Ba - then the value at the same position in the new array is the value in Bchoices[i] at that same position; if mode='wrap', values in a (and thus Ba) may be any (signed) integer; modular arithmetic is used to map integers outside the range [0, n-1] back into that range; and then the new array is constructed as above; if mode='clip', values in a (and thus Ba) may be any (signed) integer; negative integers are mapped to 0; values greater than n-1 are mapped to n-1; and then the new array is constructed as above. Parameters
aint array
This array must contain integers in [0, n-1], where n is the number of choices, unless mode=wrap or mode=clip, in which cases any integers are permissible.
choicessequence of arrays
Choice arrays. a and all of the choices must be broadcastable to the same shape. If choices is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to choices.shape[0]) is taken as defining the “sequence”.
outarray, optional
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Note that out is always buffered if mode='raise'; use other modes for better performance.
mode{‘raise’ (default), ‘wrap’, ‘clip’}, optional
Specifies how indices outside [0, n-1] will be treated: ‘raise’ : an exception is raised ‘wrap’ : value becomes value mod n
‘clip’ : values < 0 are mapped to 0, values > n-1 are mapped to n-1 Returns
merged_arrayarray
The merged result. Raises
ValueError: shape mismatch
If a and each choice array are not all broadcastable to the same shape. See also ndarray.choose
equivalent method numpy.take_along_axis
Preferable if choices is an array Notes To reduce the chance of misinterpretation, even though the following “abuse” is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple. Examples >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
... [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices
... # the first element of the result will be the first element of the
... # third (2+1) "array" in choices, namely, 20; the second element
... # will be the second element of the fourth (3+1) choice array, i.e.,
... # 31, etc.
... )
array([20, 31, 12, 3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
array([20, 31, 12, 3])
>>> # because there are 4 choice arrays
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
array([20, 1, 12, 3])
>>> # i.e., 0
A couple examples illustrating how choose broadcasts: >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> np.choose(a, choices)
array([[ 10, -10, 10],
[-10, 10, -10],
[ 10, -10, 10]])
>>> # With thanks to Anne Archibald
>>> a = np.array([0, 1]).reshape((2,1,1))
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
array([[[ 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3]],
[[-1, -2, -3, -4, -5],
[-1, -2, -3, -4, -5],
[-1, -2, -3, -4, -5]]]) | |
doc_3530 | Frame of a traceback. The Traceback class is a sequence of Frame instances.
filename
Filename (str).
lineno
Line number (int). | |
doc_3531 | class BaseFormSet
A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let’s say you have the following form: >>> from django import forms
>>> class ArticleForm(forms.Form):
... title = forms.CharField()
... pub_date = forms.DateField()
You might want to allow the user to create several articles at once. To create a formset out of an ArticleForm you would do: >>> from django.forms import formset_factory
>>> ArticleFormSet = formset_factory(ArticleForm)
You now have created a formset class named ArticleFormSet. Instantiating the formset gives you the ability to iterate over the forms in the formset and display them as you would with a regular form: >>> formset = ArticleFormSet()
>>> for form in formset:
... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr>
As you can see it only displayed one empty form. The number of empty forms that is displayed is controlled by the extra parameter. By default, formset_factory() defines one extra form; the following example will create a formset class to display two blank forms: >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
Iterating over a formset will render the forms in the order they were created. You can change this order by providing an alternate implementation for the __iter__() method. Formsets can also be indexed into, which returns the corresponding form. If you override __iter__, you will need to also override __getitem__ to have matching behavior. Using initial data with a formset Initial data is what drives the main usability of a formset. As shown above you can define the number of extra forms. What this means is that you are telling the formset how many additional forms to show in addition to the number of forms it generates from the initial data. Let’s take a look at an example: >>> import datetime
>>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
>>> formset = ArticleFormSet(initial=[
... {'title': 'Django is now open source',
... 'pub_date': datetime.date.today(),}
... ])
>>> for form in formset:
... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title"></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-12" id="id_form-0-pub_date"></td></tr>
<tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" id="id_form-1-title"></td></tr>
<tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" id="id_form-1-pub_date"></td></tr>
<tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr>
<tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr>
There are now a total of three forms showing above. One for the initial data that was passed in and two extra forms. Also note that we are passing in a list of dictionaries as the initial data. If you use an initial for displaying a formset, you should pass the same initial when processing that formset’s submission so that the formset can detect which forms were changed by the user. For example, you might have something like: ArticleFormSet(request.POST, initial=[...]). See also Creating formsets from models with model formsets. Limiting the maximum number of forms The max_num parameter to formset_factory() gives you the ability to limit the number of forms the formset will display: >>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
>>> formset = ArticleFormSet()
>>> for form in formset:
... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr>
If the value of max_num is greater than the number of existing items in the initial data, up to extra additional blank forms will be added to the formset, so long as the total number of forms does not exceed max_num. For example, if extra=2 and max_num=2 and the formset is initialized with one initial item, a form for the initial item and one blank form will be displayed. If the number of items in the initial data exceeds max_num, all initial data forms will be displayed regardless of the value of max_num and no extra forms will be displayed. For example, if extra=3 and max_num=1 and the formset is initialized with two initial items, two forms with the initial data will be displayed. A max_num value of None (the default) puts a high limit on the number of forms displayed (1000). In practice this is equivalent to no limit. By default, max_num only affects how many forms are displayed and does not affect validation. If validate_max=True is passed to the formset_factory(), then max_num will affect validation. See validate_max. Limiting the maximum number of instantiated forms New in Django 3.2. The absolute_max parameter to formset_factory() allows limiting the number of forms that can be instantiated when supplying POST data. This protects against memory exhaustion attacks using forged POST requests: >>> from django.forms.formsets import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, absolute_max=1500)
>>> data = {
... 'form-TOTAL_FORMS': '1501',
... 'form-INITIAL_FORMS': '0',
... }
>>> formset = ArticleFormSet(data)
>>> len(formset.forms)
1500
>>> formset.is_valid()
False
>>> formset.non_form_errors()
['Please submit at most 1000 forms.']
When absolute_max is None, it defaults to max_num + 1000. (If max_num is None, it defaults to 2000). If absolute_max is less than max_num, a ValueError will be raised. Formset validation Validation with a formset is almost identical to a regular Form. There is an is_valid method on the formset to provide a convenient way to validate all forms in the formset: >>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm)
>>> data = {
... 'form-TOTAL_FORMS': '1',
... 'form-INITIAL_FORMS': '0',
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
True
We passed in no data to the formset which is resulting in a valid form. The formset is smart enough to ignore extra forms that were not changed. If we provide an invalid article: >>> data = {
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': 'Test',
... 'form-0-pub_date': '1904-06-16',
... 'form-1-title': 'Test',
... 'form-1-pub_date': '', # <-- this date is missing but required
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
[{}, {'pub_date': ['This field is required.']}]
As we can see, formset.errors is a list whose entries correspond to the forms in the formset. Validation was performed for each of the two forms, and the expected error message appears for the second item. Just like when using a normal Form, each field in a formset’s forms may include HTML attributes such as maxlength for browser validation. However, form fields of formsets won’t include the required attribute as that validation may be incorrect when adding and deleting forms.
BaseFormSet.total_error_count()
To check how many errors there are in the formset, we can use the total_error_count method: >>> # Using the previous example
>>> formset.errors
[{}, {'pub_date': ['This field is required.']}]
>>> len(formset.errors)
2
>>> formset.total_error_count()
1
We can also check if form data differs from the initial data (i.e. the form was sent without any data): >>> data = {
... 'form-TOTAL_FORMS': '1',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': '',
... 'form-0-pub_date': '',
... }
>>> formset = ArticleFormSet(data)
>>> formset.has_changed()
False
Understanding the ManagementForm
You may have noticed the additional data (form-TOTAL_FORMS, form-INITIAL_FORMS) that was required in the formset’s data above. This data is required for the ManagementForm. This form is used by the formset to manage the collection of forms contained in the formset. If you don’t provide this management data, the formset will be invalid: >>> data = {
... 'form-0-title': 'Test',
... 'form-0-pub_date': '',
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
False
It is used to keep track of how many form instances are being displayed. If you are adding new forms via JavaScript, you should increment the count fields in this form as well. On the other hand, if you are using JavaScript to allow deletion of existing objects, then you need to ensure the ones being removed are properly marked for deletion by including form-#-DELETE in the POST data. It is expected that all forms are present in the POST data regardless. The management form is available as an attribute of the formset itself. When rendering a formset in a template, you can include all the management data by rendering {{ my_formset.management_form }} (substituting the name of your formset as appropriate). Note As well as the form-TOTAL_FORMS and form-INITIAL_FORMS fields shown in the examples here, the management form also includes form-MIN_NUM_FORMS and form-MAX_NUM_FORMS fields. They are output with the rest of the management form, but only for the convenience of client-side code. These fields are not required and so are not shown in the example POST data. Changed in Django 3.2: formset.is_valid() now returns False rather than raising an exception when the management form is missing or has been tampered with.
total_form_count and initial_form_count
BaseFormSet has a couple of methods that are closely related to the ManagementForm, total_form_count and initial_form_count. total_form_count returns the total number of forms in this formset. initial_form_count returns the number of forms in the formset that were pre-filled, and is also used to determine how many forms are required. You will probably never need to override either of these methods, so please be sure you understand what they do before doing so. empty_form BaseFormSet provides an additional attribute empty_form which returns a form instance with a prefix of __prefix__ for easier use in dynamic forms with JavaScript. error_messages New in Django 3.2. The error_messages argument lets you override the default messages that the formset will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message when the management form is missing: >>> formset = ArticleFormSet({})
>>> formset.is_valid()
False
>>> formset.non_form_errors()
['ManagementForm data is missing or has been tampered with. Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. You may need to file a bug report if the issue persists.']
And here is a custom error message: >>> formset = ArticleFormSet({}, error_messages={'missing_management_form': 'Sorry, something went wrong.'})
>>> formset.is_valid()
False
>>> formset.non_form_errors()
['Sorry, something went wrong.']
Custom formset validation A formset has a clean method similar to the one on a Form class. This is where you define your own validation that works at the formset level: >>> from django.core.exceptions import ValidationError
>>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... def clean(self):
... """Checks that no two articles have the same title."""
... if any(self.errors):
... # Don't bother validating the formset unless each form is valid on its own
... return
... titles = []
... for form in self.forms:
... if self.can_delete and self._should_delete_form(form):
... continue
... title = form.cleaned_data.get('title')
... if title in titles:
... raise ValidationError("Articles in a set must have distinct titles.")
... titles.append(title)
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
>>> data = {
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': 'Test',
... 'form-0-pub_date': '1904-06-16',
... 'form-1-title': 'Test',
... 'form-1-pub_date': '1912-06-23',
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
[{}, {}]
>>> formset.non_form_errors()
['Articles in a set must have distinct titles.']
The formset clean method is called after all the Form.clean methods have been called. The errors will be found using the non_form_errors() method on the formset. Non-form errors will be rendered with an additional class of nonform to help distinguish them from form-specific errors. For example, {{ formset.non_form_errors }} would look like: <ul class="errorlist nonform">
<li>Articles in a set must have distinct titles.</li>
</ul>
Changed in Django 4.0: The additional nonform class was added. Validating the number of forms in a formset Django provides a couple ways to validate the minimum or maximum number of submitted forms. Applications which need more customizable validation of the number of forms should use custom formset validation. validate_max If validate_max=True is passed to formset_factory(), validation will also check that the number of forms in the data set, minus those marked for deletion, is less than or equal to max_num. >>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)
>>> data = {
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': 'Test',
... 'form-0-pub_date': '1904-06-16',
... 'form-1-title': 'Test 2',
... 'form-1-pub_date': '1912-06-23',
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
[{}, {}]
>>> formset.non_form_errors()
['Please submit at most 1 form.']
validate_max=True validates against max_num strictly even if max_num was exceeded because the amount of initial data supplied was excessive. Note Regardless of validate_max, if the number of forms in a data set exceeds absolute_max, then the form will fail to validate as if validate_max were set, and additionally only the first absolute_max forms will be validated. The remainder will be truncated entirely. This is to protect against memory exhaustion attacks using forged POST requests. See Limiting the maximum number of instantiated forms. validate_min If validate_min=True is passed to formset_factory(), validation will also check that the number of forms in the data set, minus those marked for deletion, is greater than or equal to min_num. >>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, min_num=3, validate_min=True)
>>> data = {
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': 'Test',
... 'form-0-pub_date': '1904-06-16',
... 'form-1-title': 'Test 2',
... 'form-1-pub_date': '1912-06-23',
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
[{}, {}]
>>> formset.non_form_errors()
['Please submit at least 3 forms.']
Note Regardless of validate_min, if a formset contains no data, then extra + min_num empty forms will be displayed. Dealing with ordering and deletion of forms The formset_factory() provides two optional parameters can_order and can_delete to help with ordering of forms in formsets and deletion of forms from a formset. can_order
BaseFormSet.can_order
Default: False Lets you create a formset with the ability to order: >>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
>>> formset = ArticleFormSet(initial=[
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
... ])
>>> for form in formset:
... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title"></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date"></td></tr>
<tr><th><label for="id_form-0-ORDER">Order:</label></th><td><input type="number" name="form-0-ORDER" value="1" id="id_form-0-ORDER"></td></tr>
<tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title"></td></tr>
<tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date"></td></tr>
<tr><th><label for="id_form-1-ORDER">Order:</label></th><td><input type="number" name="form-1-ORDER" value="2" id="id_form-1-ORDER"></td></tr>
<tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr>
<tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr>
<tr><th><label for="id_form-2-ORDER">Order:</label></th><td><input type="number" name="form-2-ORDER" id="id_form-2-ORDER"></td></tr>
This adds an additional field to each form. This new field is named ORDER and is an forms.IntegerField. For the forms that came from the initial data it automatically assigned them a numeric value. Let’s look at what will happen when the user changes these values: >>> data = {
... 'form-TOTAL_FORMS': '3',
... 'form-INITIAL_FORMS': '2',
... 'form-0-title': 'Article #1',
... 'form-0-pub_date': '2008-05-10',
... 'form-0-ORDER': '2',
... 'form-1-title': 'Article #2',
... 'form-1-pub_date': '2008-05-11',
... 'form-1-ORDER': '1',
... 'form-2-title': 'Article #3',
... 'form-2-pub_date': '2008-05-01',
... 'form-2-ORDER': '0',
... }
>>> formset = ArticleFormSet(data, initial=[
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
... ])
>>> formset.is_valid()
True
>>> for form in formset.ordered_forms:
... print(form.cleaned_data)
{'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': 'Article #3'}
{'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': 'Article #2'}
{'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': 'Article #1'}
BaseFormSet also provides an ordering_widget attribute and get_ordering_widget() method that control the widget used with can_order. ordering_widget
BaseFormSet.ordering_widget
Default: NumberInput Set ordering_widget to specify the widget class to be used with can_order: >>> from django.forms import BaseFormSet, formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... ordering_widget = HiddenInput
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)
get_ordering_widget
BaseFormSet.get_ordering_widget()
Override get_ordering_widget() if you need to provide a widget instance for use with can_order: >>> from django.forms import BaseFormSet, formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... def get_ordering_widget(self):
... return HiddenInput(attrs={'class': 'ordering'})
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)
can_delete
BaseFormSet.can_delete
Default: False Lets you create a formset with the ability to select forms for deletion: >>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
>>> formset = ArticleFormSet(initial=[
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
... ])
>>> for form in formset:
... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title"></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date"></td></tr>
<tr><th><label for="id_form-0-DELETE">Delete:</label></th><td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE"></td></tr>
<tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title"></td></tr>
<tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date"></td></tr>
<tr><th><label for="id_form-1-DELETE">Delete:</label></th><td><input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE"></td></tr>
<tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr>
<tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr>
<tr><th><label for="id_form-2-DELETE">Delete:</label></th><td><input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE"></td></tr>
Similar to can_order this adds a new field to each form named DELETE and is a forms.BooleanField. When data comes through marking any of the delete fields you can access them with deleted_forms: >>> data = {
... 'form-TOTAL_FORMS': '3',
... 'form-INITIAL_FORMS': '2',
... 'form-0-title': 'Article #1',
... 'form-0-pub_date': '2008-05-10',
... 'form-0-DELETE': 'on',
... 'form-1-title': 'Article #2',
... 'form-1-pub_date': '2008-05-11',
... 'form-1-DELETE': '',
... 'form-2-title': '',
... 'form-2-pub_date': '',
... 'form-2-DELETE': '',
... }
>>> formset = ArticleFormSet(data, initial=[
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
... ])
>>> [form.cleaned_data for form in formset.deleted_forms]
[{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': 'Article #1'}]
If you are using a ModelFormSet, model instances for deleted forms will be deleted when you call formset.save(). If you call formset.save(commit=False), objects will not be deleted automatically. You’ll need to call delete() on each of the formset.deleted_objects to actually delete them: >>> instances = formset.save(commit=False)
>>> for obj in formset.deleted_objects:
... obj.delete()
On the other hand, if you are using a plain FormSet, it’s up to you to handle formset.deleted_forms, perhaps in your formset’s save() method, as there’s no general notion of what it means to delete a form. BaseFormSet also provides a deletion_widget attribute and get_deletion_widget() method that control the widget used with can_delete. deletion_widget New in Django 4.0.
BaseFormSet.deletion_widget
Default: CheckboxInput Set deletion_widget to specify the widget class to be used with can_delete: >>> from django.forms import BaseFormSet, formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... deletion_widget = HiddenInput
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True)
get_deletion_widget New in Django 4.0.
BaseFormSet.get_deletion_widget()
Override get_deletion_widget() if you need to provide a widget instance for use with can_delete: >>> from django.forms import BaseFormSet, formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... def get_deletion_widget(self):
... return HiddenInput(attrs={'class': 'deletion'})
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True)
can_delete_extra New in Django 3.2.
BaseFormSet.can_delete_extra
Default: True While setting can_delete=True, specifying can_delete_extra=False will remove the option to delete extra forms. Adding additional fields to a formset If you need to add additional fields to the formset this can be easily accomplished. The formset base class provides an add_fields method. You can override this method to add your own fields or even redefine the default fields/attributes of the order and deletion fields: >>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... def add_fields(self, form, index):
... super().add_fields(form, index)
... form.fields["my_field"] = forms.CharField()
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
>>> formset = ArticleFormSet()
>>> for form in formset:
... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr>
<tr><th><label for="id_form-0-my_field">My field:</label></th><td><input type="text" name="form-0-my_field" id="id_form-0-my_field"></td></tr>
Passing custom parameters to formset forms Sometimes your form class takes custom parameters, like MyArticleForm. You can pass this parameter when instantiating the formset: >>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> class MyArticleForm(ArticleForm):
... def __init__(self, *args, user, **kwargs):
... self.user = user
... super().__init__(*args, **kwargs)
>>> ArticleFormSet = formset_factory(MyArticleForm)
>>> formset = ArticleFormSet(form_kwargs={'user': request.user})
The form_kwargs may also depend on the specific form instance. The formset base class provides a get_form_kwargs method. The method takes a single argument - the index of the form in the formset. The index is None for the empty_form: >>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory
>>> class BaseArticleFormSet(BaseFormSet):
... def get_form_kwargs(self, index):
... kwargs = super().get_form_kwargs(index)
... kwargs['custom_kwarg'] = index
... return kwargs
Customizing a formset’s prefix In the rendered HTML, formsets include a prefix on each field’s name. By default, the prefix is 'form', but it can be customized using the formset’s prefix argument. For example, in the default case, you might see: <label for="id_form-0-title">Title:</label>
<input type="text" name="form-0-title" id="id_form-0-title">
But with ArticleFormset(prefix='article') that becomes: <label for="id_article-0-title">Title:</label>
<input type="text" name="article-0-title" id="id_article-0-title">
This is useful if you want to use more than one formset in a view. Using a formset in views and templates Formsets have five attributes and five methods associated with rendering.
BaseFormSet.renderer
New in Django 4.0. Specifies the renderer to use for the formset. Defaults to the renderer specified by the FORM_RENDERER setting.
BaseFormSet.template_name
New in Django 4.0. The name of the template used when calling __str__ or render(). This template renders the formset’s management form and then each form in the formset as per the template defined by the form’s template_name. This is a proxy of as_table by default.
BaseFormSet.template_name_p
New in Django 4.0. The name of the template used when calling as_p(). By default this is 'django/forms/formsets/p.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_p() method.
BaseFormSet.template_name_table
New in Django 4.0. The name of the template used when calling as_table(). By default this is 'django/forms/formsets/table.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_table() method.
BaseFormSet.template_name_ul
New in Django 4.0. The name of the template used when calling as_ul(). By default this is 'django/forms/formsets/ul.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_ul() method.
BaseFormSet.get_context()
New in Django 4.0. Returns the context for rendering a formset in a template. The available context is:
formset : The instance of the formset.
BaseFormSet.render(template_name=None, context=None, renderer=None)
New in Django 4.0. The render method is called by __str__ as well as the as_p(), as_ul(), and as_table() methods. All arguments are optional and will default to:
template_name: template_name
context: Value returned by get_context()
renderer: Value returned by renderer
BaseFormSet.as_p()
Renders the formset with the template_name_p template.
BaseFormSet.as_table()
Renders the formset with the template_name_table template.
BaseFormSet.as_ul()
Renders the formset with the template_name_ul template.
Using a formset inside a view is not very different from using a regular Form class. The only thing you will want to be aware of is making sure to use the management form inside the template. Let’s look at a sample view: from django.forms import formset_factory
from django.shortcuts import render
from myapp.forms import ArticleForm
def manage_articles(request):
ArticleFormSet = formset_factory(ArticleForm)
if request.method == 'POST':
formset = ArticleFormSet(request.POST, request.FILES)
if formset.is_valid():
# do something with the formset.cleaned_data
pass
else:
formset = ArticleFormSet()
return render(request, 'manage_articles.html', {'formset': formset})
The manage_articles.html template might look like this: <form method="post">
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
</form>
However there’s a slight shortcut for the above by letting the formset itself deal with the management form: <form method="post">
<table>
{{ formset }}
</table>
</form>
The above ends up calling the BaseFormSet.render() method on the formset class. This renders the formset using the template specified by the template_name attribute. Similar to forms, by default the formset will be rendered as_table, with other helper methods of as_p and as_ul being available. The rendering of the formset can be customized by specifying the template_name attribute, or more generally by overriding the default template. Changed in Django 4.0: Rendering of formsets was moved to the template engine. Manually rendered can_delete and can_order
If you manually render fields in the template, you can render can_delete parameter with {{ form.DELETE }}: <form method="post">
{{ formset.management_form }}
{% for form in formset %}
<ul>
<li>{{ form.title }}</li>
<li>{{ form.pub_date }}</li>
{% if formset.can_delete %}
<li>{{ form.DELETE }}</li>
{% endif %}
</ul>
{% endfor %}
</form>
Similarly, if the formset has the ability to order (can_order=True), it is possible to render it with {{ form.ORDER }}. Using more than one formset in a view You are able to use more than one formset in a view if you like. Formsets borrow much of its behavior from forms. With that said you are able to use prefix to prefix formset form field names with a given value to allow more than one formset to be sent to a view without name clashing. Let’s take a look at how this might be accomplished: from django.forms import formset_factory
from django.shortcuts import render
from myapp.forms import ArticleForm, BookForm
def manage_articles(request):
ArticleFormSet = formset_factory(ArticleForm)
BookFormSet = formset_factory(BookForm)
if request.method == 'POST':
article_formset = ArticleFormSet(request.POST, request.FILES, prefix='articles')
book_formset = BookFormSet(request.POST, request.FILES, prefix='books')
if article_formset.is_valid() and book_formset.is_valid():
# do something with the cleaned_data on the formsets.
pass
else:
article_formset = ArticleFormSet(prefix='articles')
book_formset = BookFormSet(prefix='books')
return render(request, 'manage_articles.html', {
'article_formset': article_formset,
'book_formset': book_formset,
})
You would then render the formsets as normal. It is important to point out that you need to pass prefix on both the POST and non-POST cases so that it is rendered and processed correctly. Each formset’s prefix replaces the default form prefix that’s added to each field’s name and id HTML attributes. | |
doc_3532 |
Bases: matplotlib.dates.DateConverter axisinfo(unit, axis)[source]
Return the AxisInfo for unit. unit is a tzinfo instance or None. The axis argument is required but not used. | |
doc_3533 | Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads. | |
doc_3534 |
Return the minimum along a given axis. Parameters
axis{None, int}, optional
Axis along which to operate. By default, axis is None and the flattened input is used.
outarray_like, optional
Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output.
fill_valuescalar or None, optional
Value used to fill in the masked values. If None, use the output of minimum_fill_value.
keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns
aminarray_like
New array holding the result. If out was specified, out is returned. See also ma.minimum_fill_value
Returns the minimum filling value for a given datatype. | |
doc_3535 | Size in bytes of a plain file; amount of data waiting on some special files. | |
doc_3536 | decode
The stateless encoding and decoding functions. These must be functions or methods which have the same interface as the encode() and decode() methods of Codec instances (see Codec Interface). The functions or methods are expected to work in a stateless mode. | |
doc_3537 |
Set the artist's clip Bbox. Parameters
clipboxBbox | |
doc_3538 | Holds the path to the instance folder. Changelog New in version 0.8. | |
doc_3539 | Similar to border(), but both ls and rs are vertch and both ts and bs are horch. The default corner characters are always used by this function. | |
doc_3540 | mmap.MADV_RANDOM
mmap.MADV_SEQUENTIAL
mmap.MADV_WILLNEED
mmap.MADV_DONTNEED
mmap.MADV_REMOVE
mmap.MADV_DONTFORK
mmap.MADV_DOFORK
mmap.MADV_HWPOISON
mmap.MADV_MERGEABLE
mmap.MADV_UNMERGEABLE
mmap.MADV_SOFT_OFFLINE
mmap.MADV_HUGEPAGE
mmap.MADV_NOHUGEPAGE
mmap.MADV_DONTDUMP
mmap.MADV_DODUMP
mmap.MADV_FREE
mmap.MADV_NOSYNC
mmap.MADV_AUTOSYNC
mmap.MADV_NOCORE
mmap.MADV_CORE
mmap.MADV_PROTECT
These options can be passed to mmap.madvise(). Not every option will be present on every system. Availability: Systems with the madvise() system call. New in version 3.8. | |
doc_3541 | class sklearn.model_selection.RepeatedStratifiedKFold(*, n_splits=5, n_repeats=10, random_state=None) [source]
Repeated Stratified K-Fold cross validator. Repeats Stratified K-Fold n times with different randomization in each repetition. Read more in the User Guide. Parameters
n_splitsint, default=5
Number of folds. Must be at least 2.
n_repeatsint, default=10
Number of times cross-validator needs to be repeated.
random_stateint, RandomState instance or None, default=None
Controls the generation of the random states for each repetition. Pass an int for reproducible output across multiple function calls. See Glossary. See also
RepeatedKFold
Repeats K-Fold n times. Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer. Examples >>> import numpy as np
>>> from sklearn.model_selection import RepeatedStratifiedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> rskf = RepeatedStratifiedKFold(n_splits=2, n_repeats=2,
... random_state=36851234)
>>> for train_index, test_index in rskf.split(X, y):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
...
TRAIN: [1 2] TEST: [0 3]
TRAIN: [0 3] TEST: [1 2]
TRAIN: [1 3] TEST: [0 2]
TRAIN: [0 2] TEST: [1 3]
Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generates indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]
Returns the number of splitting iterations in the cross-validator Parameters
Xobject
Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
yobject
Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
groupsarray-like of shape (n_samples,), default=None
Group labels for the samples used while splitting the dataset into train/test set. Returns
n_splitsint
Returns the number of splitting iterations in the cross-validator.
split(X, y=None, groups=None) [source]
Generates indices to split data into training and test set. Parameters
Xarray-like of shape (n_samples, n_features)
Training data, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None
Group labels for the samples used while splitting the dataset into train/test set. Yields
trainndarray
The training set indices for that split.
testndarray
The testing set indices for that split.
Examples using sklearn.model_selection.RepeatedStratifiedKFold
Statistical comparison of models using grid search | |
doc_3542 | Unpack from buffer starting at position offset, according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes, starting at position offset, must be at least the size required by the format, as reflected by calcsize(). | |
doc_3543 | The scheduling priority for a scheduling policy. | |
doc_3544 |
Dictionary of named fields defined for this data type, or None. The dictionary is indexed by keys that are the names of the fields. Each entry in the dictionary is a tuple fully describing the field: (dtype, offset[, title])
Offset is limited to C int, which is signed and usually 32 bits. If present, the optional title can be any object (if it is a string or unicode then it will also be a key in the fields dictionary, otherwise it’s meta-data). Notice also that the first two elements of the tuple can be passed directly as arguments to the ndarray.getfield and ndarray.setfield methods. See also
ndarray.getfield, ndarray.setfield
Examples >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
>>> print(dt.fields)
{'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)} | |
doc_3545 | bytearray.split(sep=None, maxsplit=-1)
Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or is -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, b'1,,2'.split(b',') returns [b'1', b'', b'2']). The sep argument may consist of a multibyte sequence (for example, b'1<>2<>3'.split(b'<>') returns [b'1', b'2', b'3']). Splitting an empty sequence with a specified separator returns [b''] or [bytearray(b'')] depending on the type of object being split. The sep argument may be any bytes-like object. For example: >>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns []. For example: >>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b' 1 2 3 '.split()
[b'1', b'2', b'3'] | |
doc_3546 | os.CLD_KILLED
os.CLD_DUMPED
os.CLD_TRAPPED
os.CLD_STOPPED
os.CLD_CONTINUED
These are the possible values for si_code in the result returned by waitid(). Availability: Unix. New in version 3.3. Changed in version 3.9: Added CLD_KILLED and CLD_STOPPED values. | |
doc_3547 | Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words. | |
doc_3548 | tf.experimental.numpy.atleast_1d(
*arys
)
See the NumPy documentation for numpy.atleast_1d. | |
doc_3549 | Packs a variable length opaque data string, similarly to pack_string(). | |
doc_3550 |
Find the horizontal edges of an image using the Sobel transform. Parameters
image2-D array
Image to process.
mask2-D array, optional
An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns
output2-D array
The Sobel edge map. Notes We use the following kernel: 1 2 1
0 0 0
-1 -2 -1 | |
doc_3551 | sklearn.metrics.normalized_mutual_info_score(labels_true, labels_pred, *, average_method='arithmetic') [source]
Normalized Mutual Information between two clusterings. Normalized Mutual Information (NMI) is a normalization of the Mutual Information (MI) score to scale the results between 0 (no mutual information) and 1 (perfect correlation). In this function, mutual information is normalized by some generalized mean of H(labels_true) and H(labels_pred)), defined by the average_method. This measure is not adjusted for chance. Therefore adjusted_mutual_info_score might be preferred. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won’t change the score value in any way. This metric is furthermore symmetric: switching label_true with label_pred will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Read more in the User Guide. Parameters
labels_trueint array, shape = [n_samples]
A clustering of the data into disjoint subsets.
labels_predint array-like of shape (n_samples,)
A clustering of the data into disjoint subsets.
average_methodstr, default=’arithmetic’
How to compute the normalizer in the denominator. Possible options are ‘min’, ‘geometric’, ‘arithmetic’, and ‘max’. New in version 0.20. Changed in version 0.22: The default value of average_method changed from ‘geometric’ to ‘arithmetic’. Returns
nmifloat
score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling See also
v_measure_score
V-Measure (NMI with arithmetic mean option).
adjusted_rand_score
Adjusted Rand Index.
adjusted_mutual_info_score
Adjusted Mutual Information (adjusted against chance). Examples Perfect labelings are both homogeneous and complete, hence have score 1.0: >>> from sklearn.metrics.cluster import normalized_mutual_info_score
>>> normalized_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1])
...
1.0
>>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0])
...
1.0
If classes members are completely split across different clusters, the assignment is totally in-complete, hence the NMI is null: >>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3])
...
0.0 | |
doc_3552 |
Return the C++ compiler. Parameters
None
Returns
cxxclass instance
The C++ compiler, as a CCompiler instance. | |
doc_3553 |
Return the list of Line2Ds in the legend. | |
doc_3554 |
Return whether the artist is animated. | |
doc_3555 | See Migration guide for more details. tf.compat.v1.app.flags.tf_decorator.tf_stack.StackTraceTransform Methods reset View source
reset()
__enter__ View source
__enter__()
__exit__ View source
__exit__(
unused_type, unused_value, unused_traceback
) | |
doc_3556 | Floating-point positive infinity. Equivalent to float('inf'). New in version 3.6. | |
doc_3557 | tf.floor Compat aliases for migration See Migration guide for more details. tf.compat.v1.floor, tf.compat.v1.math.floor
tf.math.floor(
x, name=None
)
Both input range is (-inf, inf) and the ouput range consists of all integer values. For example:
x = tf.constant([1.3324, -1.5, 5.555, -2.532, 0.99, float("inf")])
tf.floor(x).numpy()
array([ 1., -2., 5., -3., 0., inf], dtype=float32)
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x. | |
doc_3558 |
Generate a hexagonal binning plot. Generate a hexagonal binning plot of x versus y. If C is None (the default), this is a histogram of the number of occurrences of the observations at (x[i], y[i]). If C is specified, specifies values at given coordinates (x[i], y[i]). These values are accumulated for each hexagonal bin and then reduced according to reduce_C_function, having as default the NumPy’s mean function (numpy.mean()). (If C is specified, it must also be a 1-D sequence of the same length as x and y, or a column label.) Parameters
x:int or str
The column label or position for x points.
y:int or str
The column label or position for y points.
C:int or str, optional
The column label or position for the value of (x, y) point.
reduce_C_function:callable, default np.mean
Function of one argument that reduces all the values in a bin to a single number (e.g. np.mean, np.max, np.sum, np.std).
gridsize:int or tuple of (int, int), default 100
The number of hexagons in the x-direction. The corresponding number of hexagons in the y-direction is chosen in a way that the hexagons are approximately regular. Alternatively, gridsize can be a tuple with two elements specifying the number of hexagons in the x-direction and the y-direction. **kwargs
Additional keyword arguments are documented in DataFrame.plot(). Returns
matplotlib.AxesSubplot
The matplotlib Axes on which the hexbin is plotted. See also DataFrame.plot
Make plots of a DataFrame. matplotlib.pyplot.hexbin
Hexagonal binning plot using matplotlib, the matplotlib function that is used under the hood. Examples The following examples are generated with random data from a normal distribution.
>>> n = 10000
>>> df = pd.DataFrame({'x': np.random.randn(n),
... 'y': np.random.randn(n)})
>>> ax = df.plot.hexbin(x='x', y='y', gridsize=20)
The next example uses C and np.sum as reduce_C_function. Note that ‘observations’ values ranges from 1 to 5 but the result plot shows values up to more than 25. This is because of the reduce_C_function.
>>> n = 500
>>> df = pd.DataFrame({
... 'coord_x': np.random.uniform(-3, 3, size=n),
... 'coord_y': np.random.uniform(30, 50, size=n),
... 'observations': np.random.randint(1,5, size=n)
... })
>>> ax = df.plot.hexbin(x='coord_x',
... y='coord_y',
... C='observations',
... reduce_C_function=np.sum,
... gridsize=10,
... cmap="viridis") | |
doc_3559 | See torch.ldexp() | |
doc_3560 | See Migration guide for more details. tf.compat.v1.keras.applications.xception.preprocess_input
tf.keras.applications.xception.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The inputs pixel values are scaled between -1 and 1, sample-wise.
Raises
ValueError In case of unknown data_format argument. | |
doc_3561 | Clear the auth info and enable digest auth. | |
doc_3562 | tf.experimental.numpy.float_
tf.experimental.numpy.float64(
*args, **kwargs
)
and C double. Character code: 'd'. Canonical name: np.double. Alias: np.float_. Alias on this platform: np.float64: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa. Methods all
all()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. any
any()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. argmax
argmax()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. argmin
argmin()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. argsort
argsort()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. as_integer_ratio
as_integer_ratio()
double.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original floating point number, and with a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs.
np.double(10.0).as_integer_ratio()
(10, 1)
np.double(0.0).as_integer_ratio()
(0, 1)
np.double(-.25).as_integer_ratio()
(-1, 4)
astype
astype()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. byteswap
byteswap()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. choose
choose()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. clip
clip()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. compress
compress()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. conj
conj()
conjugate
conjugate()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. copy
copy()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. cumprod
cumprod()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. cumsum
cumsum()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. diagonal
diagonal()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. dump
dump()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. dumps
dumps()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. fill
fill()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. flatten
flatten()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. fromhex
fromhex(
string, /
)
Create a floating-point number from a hexadecimal string.
float.fromhex('0x1.ffffp10')
2047.984375
float.fromhex('-0x1p-1074')
-5e-324
getfield
getfield()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. hex
hex()
Return a hexadecimal representation of a floating-point number.
(-0.1).hex()
'-0x1.999999999999ap-4'
3.14159.hex()
'0x1.921f9f01b866ep+1'
is_integer
is_integer()
Return True if the float is an integer. item
item()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. itemset
itemset()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. max
max()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. mean
mean()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. min
min()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. newbyteorder
newbyteorder()
newbyteorder(new_order='S') Return a new dtype with a different byte order. Changes are also made in all fields and sub-arrays of the data type. The new_order code can be any from the following: 'S' - swap dtype from current to opposite endian '<', 'L'- little endian '>', 'B'- big endian '=', 'N'- native order '|', 'I'- ignore (no change to byte order) Parameters new_order : str, optional Byte order to force; a value from the byte order specifications above. The default value ('S') results in swapping the current byte order. The code does a case-insensitive check on the first letter of new_order for the alternatives above. For example, any of 'B' or 'b' or 'biggish' are valid to specify big-endian. Returns new_dtype : dtype New dtype object with the given change to the byte order. nonzero
nonzero()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. prod
prod()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. ptp
ptp()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. put
put()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. ravel
ravel()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. repeat
repeat()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. reshape
reshape()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. resize
resize()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. round
round()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. searchsorted
searchsorted()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. setfield
setfield()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. setflags
setflags()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. sort
sort()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. squeeze
squeeze()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. std
std()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. sum
sum()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. swapaxes
swapaxes()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. take
take()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. tobytes
tobytes()
tofile
tofile()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. tolist
tolist()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. tostring
tostring()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. trace
trace()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. transpose
transpose()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. var
var()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. view
view()
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See also the corresponding attribute of the derived class of interest. __abs__
__abs__()
abs(self) __add__
__add__(
value, /
)
Return self+value. __and__
__and__(
value, /
)
Return self&value. __bool__
__bool__()
self != 0 __eq__
__eq__(
value, /
)
Return self==value. __floordiv__
__floordiv__(
value, /
)
Return self//value. __ge__
__ge__(
value, /
)
Return self>=value. __getitem__
__getitem__(
key, /
)
Return self[key]. __gt__
__gt__(
value, /
)
Return self>value. __invert__
__invert__()
~self __le__
__le__(
value, /
)
Return self<=value. __lt__
__lt__(
value, /
)
Return self<value. __mod__
__mod__(
value, /
)
Return self%value. __mul__
__mul__(
value, /
)
Return self*value. __ne__
__ne__(
value, /
)
Return self!=value. __neg__
__neg__()
-self __or__
__or__(
value, /
)
Return self|value. __pos__
__pos__()
+self __pow__
__pow__(
value, mod, /
)
Return pow(self, value, mod). __radd__
__radd__(
value, /
)
Return value+self. __rand__
__rand__(
value, /
)
Return value&self. __rfloordiv__
__rfloordiv__(
value, /
)
Return value//self. __rmod__
__rmod__(
value, /
)
Return value%self. __rmul__
__rmul__(
value, /
)
Return value*self. __ror__
__ror__(
value, /
)
Return value|self. __rpow__
__rpow__(
value, mod, /
)
Return pow(value, self, mod). __rsub__
__rsub__(
value, /
)
Return value-self. __rtruediv__
__rtruediv__(
value, /
)
Return value/self. __rxor__
__rxor__(
value, /
)
Return value^self. __sub__
__sub__(
value, /
)
Return self-value. __truediv__
__truediv__(
value, /
)
Return self/value. __xor__
__xor__(
value, /
)
Return self^value.
Class Variables
T
base
data
dtype
flags
flat
imag
itemsize
nbytes
ndim
real
shape
size
strides | |
doc_3563 | sklearn.utils.sparsefuncs.inplace_swap_column(X, m, n) [source]
Swaps two columns of a CSC/CSR matrix in-place. Parameters
Xsparse matrix of shape (n_samples, n_features)
Matrix whose two columns are to be swapped. It should be of CSR or CSC format.
mint
Index of the column of X to be swapped.
nint
Index of the column of X to be swapped. | |
doc_3564 |
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool | |
doc_3565 | Return True if the queue is empty, False otherwise. If empty() returns False it doesn’t guarantee that a subsequent call to get() will not block. | |
doc_3566 |
Return the mutated path of the rectangle. | |
doc_3567 | This is an optional argument which validates that the array does not exceed the stated length. | |
doc_3568 |
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_3569 | See Migration guide for more details. tf.compat.v1.raw_ops.TensorArrayWriteV3
tf.raw_ops.TensorArrayWriteV3(
handle, index, value, flow_in, name=None
)
Args
handle A Tensor of type resource. The handle to a TensorArray.
index A Tensor of type int32. The position to write to inside the TensorArray.
value A Tensor. The tensor to write to the TensorArray.
flow_in A Tensor of type float32. A float scalar that enforces proper chaining of operations.
name A name for the operation (optional).
Returns A Tensor of type float32. | |
doc_3570 | Change the root directory of the current process to path. Availability: Unix. Changed in version 3.6: Accepts a path-like object. | |
doc_3571 |
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 unknown
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 unknown
facecolor or facecolors or fc unknown
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 list of array-like
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
sort_zpos unknown
transform Transform
url str
urls list of str or None
verts unknown
verts_and_codes unknown
visible bool
zorder float
zsort {'average', 'min', 'max'} | |
doc_3572 | skimage.future.fit_segmenter(labels, …) Segmentation using labeled parts of the image and a classifier.
skimage.future.manual_lasso_segmentation(image) Return a label image based on freeform selections made with the mouse.
skimage.future.manual_polygon_segmentation(image) Return a label image based on polygon selections made with the mouse.
skimage.future.predict_segmenter(features, clf) Segmentation of images using a pretrained classifier.
skimage.future.TrainableSegmenter([clf, …]) Estimator for classifying pixels.
skimage.future.graph fit_segmenter
skimage.future.fit_segmenter(labels, features, clf) [source]
Segmentation using labeled parts of the image and a classifier. Parameters
labelsndarray of ints
Image of labels. Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.
featuresndarray
Array of features, with the first dimension corresponding to the number of features, and the other dimensions correspond to labels.shape.
clfclassifier object
classifier object, exposing a fit and a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier. Returns
clfclassifier object
classifier trained on labels Raises
NotFittedError if self.clf has not been fitted yet (use self.fit).
Examples using skimage.future.fit_segmenter
Trainable segmentation using local features and random forests manual_lasso_segmentation
skimage.future.manual_lasso_segmentation(image, alpha=0.4, return_all=False) [source]
Return a label image based on freeform selections made with the mouse. Parameters
image(M, N[, 3]) array
Grayscale or RGB image.
alphafloat, optional
Transparency value for polygons drawn over the image.
return_allbool, optional
If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons “overwrite” earlier ones where they overlap. Returns
labelsarray of int, shape ([Q, ]M, N)
The segmented regions. If mode is ‘separate’, the leading dimension of the array corresponds to the number of regions that the user drew. Notes Press and hold the left mouse button to draw around each object. Examples >>> from skimage import data, future, io
>>> camera = data.camera()
>>> mask = future.manual_lasso_segmentation(camera)
>>> io.imshow(mask)
>>> io.show()
manual_polygon_segmentation
skimage.future.manual_polygon_segmentation(image, alpha=0.4, return_all=False) [source]
Return a label image based on polygon selections made with the mouse. Parameters
image(M, N[, 3]) array
Grayscale or RGB image.
alphafloat, optional
Transparency value for polygons drawn over the image.
return_allbool, optional
If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons “overwrite” earlier ones where they overlap. Returns
labelsarray of int, shape ([Q, ]M, N)
The segmented regions. If mode is ‘separate’, the leading dimension of the array corresponds to the number of regions that the user drew. Notes Use left click to select the vertices of the polygon and right click to confirm the selection once all vertices are selected. Examples >>> from skimage import data, future, io
>>> camera = data.camera()
>>> mask = future.manual_polygon_segmentation(camera)
>>> io.imshow(mask)
>>> io.show()
predict_segmenter
skimage.future.predict_segmenter(features, clf) [source]
Segmentation of images using a pretrained classifier. Parameters
featuresndarray
Array of features, with the last dimension corresponding to the number of features, and the other dimensions are compatible with the shape of the image to segment, or a flattened image.
clfclassifier object
trained classifier object, exposing a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier. The classifier must be already trained, for example with skimage.segmentation.fit_segmenter(). Returns
outputndarray
Labeled array, built from the prediction of the classifier.
Examples using skimage.future.predict_segmenter
Trainable segmentation using local features and random forests TrainableSegmenter
class skimage.future.TrainableSegmenter(clf=None, features_func=None) [source]
Bases: object Estimator for classifying pixels. Parameters
clfclassifier object, optional
classifier object, exposing a fit and a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier.
features_funcfunction, optional
function computing features on all pixels of the image, to be passed to the classifier. The output should be of shape (m_features, *labels.shape). If None, skimage.segmentation.multiscale_basic_features() is used. Methods
fit(image, labels) Train classifier using partially labeled (annotated) image.
predict(image) Segment new image using trained internal classifier.
compute_features
__init__(clf=None, features_func=None) [source]
Initialize self. See help(type(self)) for accurate signature.
compute_features(image) [source]
fit(image, labels) [source]
Train classifier using partially labeled (annotated) image. Parameters
imagendarray
Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.
labelsndarray of ints
Labeled array of shape compatible with image (same shape for a single-channel image). Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.
predict(image) [source]
Segment new image using trained internal classifier. Parameters
imagendarray
Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func. Raises
NotFittedError if self.clf has not been fitted yet (use self.fit). | |
doc_3573 |
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick | |
doc_3574 |
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data | |
doc_3575 |
Find the duplicates in a structured array along a given key Parameters
aarray-like
Input array
key{string, None}, optional
Name of the fields along which to check the duplicates. If None, the search is performed by records
ignoremask{True, False}, optional
Whether masked data should be discarded or considered as duplicates.
return_index{False, True}, optional
Whether to return the indices of the duplicated values. Examples >>> from numpy.lib import recfunctions as rfn
>>> ndtype = [('a', int)]
>>> a = np.ma.array([1, 1, 1, 2, 2, 3, 3],
... mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype)
>>> rfn.find_duplicates(a, ignoremask=True, return_index=True)
(masked_array(data=[(1,), (1,), (2,), (2,)],
mask=[(False,), (False,), (False,), (False,)],
fill_value=(999999,),
dtype=[('a', '<i8')]), array([0, 1, 3, 4])) | |
doc_3576 | alias of werkzeug.datastructures.ImmutableMultiDict | |
doc_3577 | Sets a test cookie to determine whether the user’s browser supports cookies. Due to the way cookies work, you won’t be able to test this until the user’s next page request. See Setting test cookies below for more information. | |
doc_3578 |
Return an instance of a GraphicsContextBase. | |
doc_3579 | tf.keras.metrics.squared_hinge, tf.losses.squared_hinge, tf.metrics.squared_hinge Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.squared_hinge, tf.compat.v1.keras.metrics.squared_hinge
tf.keras.losses.squared_hinge(
y_true, y_pred
)
loss = mean(square(maximum(1 - y_true * y_pred, 0)), axis=-1) Standalone usage:
y_true = np.random.choice([-1, 1], size=(2, 3))
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.squared_hinge(y_true, y_pred)
assert loss.shape == (2,)
assert np.array_equal(
loss.numpy(),
np.mean(np.square(np.maximum(1. - y_true * y_pred, 0.)), axis=-1))
Args
y_true The ground truth values. y_true values are expected to be -1 or 1. If binary (0 or 1) labels are provided we will convert them to -1 or 1. shape = [batch_size, d0, .. dN].
y_pred The predicted values. shape = [batch_size, d0, .. dN].
Returns Squared hinge loss values. shape = [batch_size, d0, .. dN-1]. | |
doc_3580 | Remove all entity headers from a list or Headers object. This operation works in-place. Expires and Content-Location headers are by default not removed. The reason for this is RFC 2616 section 10.3.5 which specifies some entity headers that should be sent. Changelog Changed in version 0.5: added allowed parameter. Parameters
headers (Union[werkzeug.datastructures.Headers, List[Tuple[str, str]]]) – a list or Headers object.
allowed (Iterable[str]) – a list of headers that should still be allowed even though they are entity headers. Return type
None | |
doc_3581 | Return the time of last modification of path. The return value is a floating point number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible. Changed in version 3.6: Accepts a path-like object. | |
doc_3582 |
Function that computes the dot product between the Jacobian of the given function at the point given by the inputs and a vector v. Parameters
func (function) – a Python function that takes Tensor inputs and returns a tuple of Tensors or a Tensor.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the Jacobian vector product is computed. Must be the same size as the input of func. This argument is optional when the input to func contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the jvp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) jvp (tuple of Tensors or Tensor): result of the dot product with the same shape as the output. Return type
output (tuple) Example >>> def exp_reducer(x):
... return x.exp().sum(dim=1)
>>> inputs = torch.rand(4, 4)
>>> v = torch.ones(4, 4)
>>> jvp(exp_reducer, inputs, v)
(tensor([6.3090, 4.6742, 7.9114, 8.2106]),
tensor([6.3090, 4.6742, 7.9114, 8.2106]))
>>> jvp(exp_reducer, inputs, v, create_graph=True)
(tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SumBackward1>),
tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SqueezeBackward1>))
>>> def adder(x, y):
... return 2 * x + 3 * y
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.ones(2), torch.ones(2))
>>> jvp(adder, inputs, v)
(tensor([2.2399, 2.5005]),
tensor([5., 5.]))
Note The jvp is currently computed by using the backward of the backward (sometimes called the double backwards trick) as we don’t have support for forward mode AD in PyTorch at the moment. | |
doc_3583 |
Alias for get_edgecolor. | |
doc_3584 |
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | |
doc_3585 |
Set the Figure instance the artist belongs to. Parameters
figFigure | |
doc_3586 |
Return the Bbox. | |
doc_3587 |
Attributes
any_info Any any_info
function_aliases repeated FunctionAliasesEntry function_aliases
meta_graph_version string meta_graph_version
stripped_default_attrs bool stripped_default_attrs
stripped_op_list OpList stripped_op_list
tags repeated string tags
tensorflow_git_version string tensorflow_git_version
tensorflow_version string tensorflow_version Child Classes class FunctionAliasesEntry | |
doc_3588 |
Dictionary of global attributes of this dataset. Warning attrs is experimental and may change without warning. See also DataFrame.flags
Global flags applying to this object. | |
doc_3589 | inline and attachment are the only valid values in common use. | |
doc_3590 |
Check if an object is a pandas extension array type. See the Use Guide for more. Parameters
arr_or_dtype:object
For array-like input, the .dtype attribute will be extracted. Returns
bool
Whether the arr_or_dtype is an extension array type. Notes This checks whether an object implements the pandas extension array interface. In pandas, this includes: Categorical Sparse Interval Period DatetimeArray TimedeltaArray Third-party libraries may implement arrays or types satisfying this interface as well. Examples
>>> from pandas.api.types import is_extension_array_dtype
>>> arr = pd.Categorical(['a', 'b'])
>>> is_extension_array_dtype(arr)
True
>>> is_extension_array_dtype(arr.dtype)
True
>>> arr = np.array(['a', 'b'])
>>> is_extension_array_dtype(arr.dtype)
False | |
doc_3591 | See Migration guide for more details. tf.compat.v1.raw_ops.StatelessMultinomial
tf.raw_ops.StatelessMultinomial(
logits, num_samples, seed, output_dtype=tf.dtypes.int64, name=None
)
Args
logits A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. 2-D Tensor with shape [batch_size, num_classes]. Each slice [i, :] represents the unnormalized log probabilities for all classes.
num_samples A Tensor of type int32. 0-D. Number of independent samples to draw for each row slice.
seed A Tensor. Must be one of the following types: int32, int64. 2 seeds (shape [2]).
output_dtype An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int64.
name A name for the operation (optional).
Returns A Tensor of type output_dtype. | |
doc_3592 |
Set parameters within this locator. | |
doc_3593 | “Byteswap” all samples in a fragment and returns the modified fragment. Converts big-endian samples to little-endian and vice versa. New in version 3.4. | |
doc_3594 | See Migration guide for more details. tf.compat.v1.raw_ops.BatchMatrixDiagPart
tf.raw_ops.BatchMatrixDiagPart(
input, name=None
)
Args
input A Tensor.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_3595 | Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. Note that the method resolution order depends on cls’s type. Unless a very peculiar user-defined metatype is in use, cls will be the first element of the tuple. | |
doc_3596 |
An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array. Parameters
(for the __new__ method; see Notes below)
shapetuple of ints
Shape of created array.
dtypedata-type, optional
Any object that can be interpreted as a numpy data type.
bufferobject exposing buffer interface, optional
Used to fill the array with data.
offsetint, optional
Offset of array data in buffer.
stridestuple of ints, optional
Strides of data in memory.
order{‘C’, ‘F’}, optional
Row-major (C-style) or column-major (Fortran-style) order. See also array
Construct an array. zeros
Create an array, each element of which is zero. empty
Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”). dtype
Create a data-type. numpy.typing.NDArray
An ndarray alias generic w.r.t. its dtype.type. Notes There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted. No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
[ nan, 2.5e-323]])
Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]),
... offset=np.int_().itemsize,
... dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])
Attributes
Tndarray
Transpose of the array.
databuffer
The array’s elements, in memory.
dtypedtype object
Describes the format of the elements in the array.
flagsdict
Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
flatnumpy.flatiter object
Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO).
imagndarray
Imaginary part of the array.
realndarray
Real part of the array.
sizeint
Number of elements in the array.
itemsizeint
The memory use of each array element in bytes.
nbytesint
The total number of bytes required to store the array data, i.e., itemsize * size.
ndimint
The array’s number of dimensions.
shapetuple of ints
Shape of the array.
stridestuple of ints
The step-size required to move from one element to the next in memory. For example, a contiguous (3, 4) array of type int16 in C-order has strides (8, 2). This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (2 * 4).
ctypesctypes object
Class containing properties of the array needed for interaction with ctypes.
basendarray
If the array is a view into another array, that array is its base (unless that array is also a view). The base array is where the array data is actually stored. | |
doc_3597 | class secrets.SystemRandom
A class for generating random numbers using the highest-quality sources provided by the operating system. See random.SystemRandom for additional details.
secrets.choice(sequence)
Return a randomly-chosen element from a non-empty sequence.
secrets.randbelow(n)
Return a random int in the range [0, n).
secrets.randbits(k)
Return an int with k random bits.
Generating tokens The secrets module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar.
secrets.token_bytes([nbytes=None])
Return a random byte string containing nbytes number of bytes. If nbytes is None or not supplied, a reasonable default is used. >>> token_bytes(16)
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'
secrets.token_hex([nbytes=None])
Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is None or not supplied, a reasonable default is used. >>> token_hex(16)
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
secrets.token_urlsafe([nbytes=None])
Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used. >>> token_urlsafe(16)
'Drmhze6EPcv0fN_81Bj-nA'
How many bytes should tokens use? To be secure against brute-force attacks, tokens need to have sufficient randomness. Unfortunately, what is considered sufficient will necessarily increase as computers get more powerful and able to make more guesses in a shorter period. As of 2015, it is believed that 32 bytes (256 bits) of randomness is sufficient for the typical use-case expected for the secrets module. For those who want to manage their own token length, you can explicitly specify how much randomness is used for tokens by giving an int argument to the various token_* functions. That argument is taken as the number of bytes of randomness to use. Otherwise, if no argument is provided, or if the argument is None, the token_* functions will use a reasonable default instead. Note That default is subject to change at any time, including during maintenance releases. Other functions
secrets.compare_digest(a, b)
Return True if strings a and b are equal, otherwise False, in such a way as to reduce the risk of timing attacks. See hmac.compare_digest() for additional details.
Recipes and best practices This section shows recipes and best practices for using secrets to manage a basic level of security. Generate an eight-character alphanumeric password: import string
import secrets
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(8))
Note Applications should not store passwords in a recoverable format, whether plain text or encrypted. They should be salted and hashed using a cryptographically-strong one-way (irreversible) hash function. Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits: import string
import secrets
alphabet = string.ascii_letters + string.digits
while True:
password = ''.join(secrets.choice(alphabet) for i in range(10))
if (any(c.islower() for c in password)
and any(c.isupper() for c in password)
and sum(c.isdigit() for c in password) >= 3):
break
Generate an XKCD-style passphrase: import secrets
# On standard Linux systems, use a convenient dictionary file.
# Other platforms may need to provide their own word-list.
with open('/usr/share/dict/words') as f:
words = [word.strip() for word in f]
password = ' '.join(secrets.choice(words) for i in range(4))
Generate a hard-to-guess temporary URL containing a security token suitable for password recovery applications: import secrets
url = 'https://mydomain.com/reset=' + secrets.token_urlsafe() | |
doc_3598 | Prepare the request by connecting to a proxy server. The host and type will replace those of the instance, and the instance’s selector will be the original URL given in the constructor. | |
doc_3599 |
Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes. Recall that what is actually in the ndarray memory representing the Python object is the memory address of that object (a pointer). Special handling may be required, and this attribute is useful for distinguishing data types that may contain arbitrary Python objects and data-types that won’t. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.