Accuracy

class paddle.metric. Accuracy ( topk=(1,), name=None, *args, **kwargs ) [source]

Encapsulates accuracy metric logic.

Parameters
  • topk (list[int]|tuple[int]) – Number of top elements to look at for computing accuracy. Default is (1,).

  • name (str, optional) – String name of the metric instance. Default is acc.

Examples

>>> import numpy as np
>>> import paddle

>>> x = paddle.to_tensor(np.array([
...     [0.1, 0.2, 0.3, 0.4],
...     [0.1, 0.4, 0.3, 0.2],
...     [0.1, 0.2, 0.4, 0.3],
...     [0.1, 0.2, 0.3, 0.4]]))
>>> y = paddle.to_tensor(np.array([[0], [1], [2], [3]]))

>>> m = paddle.metric.Accuracy()
>>> correct = m.compute(x, y)
>>> m.update(correct)
>>> res = m.accumulate()
>>> print(res)
0.75
>>> import paddle
>>> from paddle.static import InputSpec
>>> import paddle.vision.transforms as T
>>> from paddle.vision.datasets import MNIST

>>> input = InputSpec([None, 1, 28, 28], 'float32', 'image')
>>> label = InputSpec([None, 1], 'int64', 'label')
>>> transform = T.Compose([T.Transpose(), T.Normalize([127.5], [127.5])])
>>> train_dataset = MNIST(mode='train', transform=transform)

>>> model = paddle.Model(paddle.vision.models.LeNet(), input, label)
>>> optim = paddle.optimizer.Adam(
...     learning_rate=0.001, parameters=model.parameters())
>>> model.prepare(
...     optim,
...     loss=paddle.nn.CrossEntropyLoss(),
...     metrics=paddle.metric.Accuracy())
...
>>> model.fit(train_dataset, batch_size=64)
compute ( pred, label, *args )

compute

Compute the top-k (maximum value in topk) indices.

Parameters
  • pred (Tensor) – The predicted value is a Tensor with dtype float32 or float64. Shape is [batch_size, d0, …, dN].

  • label (Tensor) – The ground truth value is Tensor with dtype int64. Shape is [batch_size, d0, …, 1], or [batch_size, d0, …, num_classes] in one hot representation.

Returns

Correct mask, a tensor with shape [batch_size, d0, …, topk].

Return type

Tensor

update ( correct, *args )

update

Update the metrics states (correct count and total count), in order to calculate cumulative accuracy of all instances. This function also returns the accuracy of current step.

Parameters

correct – Correct mask, a tensor with shape [batch_size, d0, …, topk].

Returns

the accuracy of current step.

Return type

Tensor

reset ( )

reset

Resets all of the metric state.

accumulate ( )

accumulate

Computes and returns the accumulated metric.

name ( )

name

Return name of metric instance.