mindspore.train.TopKCategoricalAccuracy

View Source On Gitee
class mindspore.train.TopKCategoricalAccuracy(k)[source]

Calculates the top-k categorical accuracy.

Parameters

k (int) – Specifies the top-k categorical accuracy to compute.

Raises
Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore.train import TopKCategoricalAccuracy
>>>
>>> x = Tensor(np.array([[0.2, 0.5, 0.3, 0.6, 0.2], [0.1, 0.35, 0.5, 0.2, 0.],
...         [0.9, 0.6, 0.2, 0.01, 0.3]]), mindspore.float32)
>>> y = Tensor(np.array([2, 0, 1]), mindspore.float32)
>>> topk = TopKCategoricalAccuracy(3)
>>> topk.clear()
>>> topk.update(x, y)
>>> output = topk.eval()
>>> print(output)
0.6666666666666666
clear()[source]

Clear the internal evaluation result.

eval()[source]

Computes the top-k categorical accuracy.

Returns

numpy.float64, computed result.

update(*inputs)[source]

Updates the internal evaluation result y_pred and y.

Parameters

inputs – Input y_pred and y. y_pred and y are Tensor, list or numpy.ndarray. y_pred is in most cases (not strictly) a list of floating numbers in range \([0, 1]\) and the shape is \((N, C)\), where \(N\) is the number of cases and \(C\) is the number of categories. y contains values of integers. The shape is \((N, C)\) if one-hot encoding is used. Shape can also be \((N,)\) if category index is used.

Note

The method update must receive input of the form \((y\_pred, y)\). If some samples have the same accuracy, the first sample will be chosen.