[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2020-10-01 UTC."],[],[],null,["# tf.keras.metrics.Metric\n\n\u003cbr /\u003e\n\n|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------|\n| [TensorFlow 1 version](/versions/r1.15/api_docs/python/tf/keras/metrics/Metric) | [View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/keras/metrics.py#L77-L290) |\n\nEncapsulates metric logic and state.\n\nInherits From: [`Layer`](../../../tf/keras/layers/Layer)\n\n#### View aliases\n\n\n**Main aliases**\n\n[`tf.metrics.Metric`](/api_docs/python/tf/keras/metrics/Metric)\n**Compat aliases for migration**\n\nSee\n[Migration guide](https://www.tensorflow.org/guide/migrate) for\nmore details.\n\n[`tf.compat.v1.keras.metrics.Metric`](/api_docs/python/tf/keras/metrics/Metric)\n\n\u003cbr /\u003e\n\n tf.keras.metrics.Metric(\n name=None, dtype=None, **kwargs\n )\n\n#### Usage:\n\n m = SomeMetric(...)\n for input in ...:\n m.update_state(input)\n print('Final result: ', m.result().numpy())\n\nUsage with tf.keras API: \n\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Dense(64, activation='relu'))\n model.add(tf.keras.layers.Dense(64, activation='relu'))\n model.add(tf.keras.layers.Dense(10, activation='softmax'))\n\n model.compile(optimizer=tf.keras.optimizers.RMSprop(0.01),\n loss=tf.keras.losses.CategoricalCrossentropy(),\n metrics=[tf.keras.metrics.CategoricalAccuracy()])\n\n data = np.random.random((1000, 32))\n labels = np.random.random((1000, 10))\n\n dataset = tf.data.Dataset.from_tensor_slices((data, labels))\n dataset = dataset.batch(32)\n\n model.fit(dataset, epochs=10)\n\nTo be implemented by subclasses:\n\n- `__init__()`: All state variables should be created in this method by calling `self.add_weight()` like: `self.var = self.add_weight(...)`\n- `update_state()`: Has all updates to the state variables like: self.var.assign_add(...).\n- `result()`: Computes and returns a value for the metric from the state variables.\n\nExample subclass implementation: \n\n class BinaryTruePositives(tf.keras.metrics.Metric):\n\n def __init__(self, name='binary_true_positives', **kwargs):\n super(BinaryTruePositives, self).__init__(name=name, **kwargs)\n self.true_positives = self.add_weight(name='tp', initializer='zeros')\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n y_true = tf.cast(y_true, tf.bool)\n y_pred = tf.cast(y_pred, tf.bool)\n\n values = tf.logical_and(tf.equal(y_true, True), tf.equal(y_pred, True))\n values = tf.cast(values, self.dtype)\n if sample_weight is not None:\n sample_weight = tf.cast(sample_weight, self.dtype)\n sample_weight = tf.broadcast_weights(sample_weight, values)\n values = tf.multiply(values, sample_weight)\n self.true_positives.assign_add(tf.reduce_sum(values))\n\n def result(self):\n return self.true_positives\n\nMethods\n-------\n\n### `add_weight`\n\n[View source](https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/keras/metrics.py#L256-L284) \n\n add_weight(\n name, shape=(), aggregation=tf.compat.v1.VariableAggregation.SUM,\n synchronization=tf.VariableSynchronization.ON_READ, initializer=None, dtype=None\n )\n\nAdds state variable. Only for use by subclasses.\n\n### `reset_states`\n\n[View source](https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/keras/metrics.py#L218-L224) \n\n reset_states()\n\nResets all of the metric state variables.\n\nThis function is called between epochs/steps,\nwhen a metric is evaluated during training.\n\n### `result`\n\n[View source](https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/keras/metrics.py#L246-L253) \n\n @abc.abstractmethod\n result()\n\nComputes and returns the metric value tensor.\n\nResult computation is an idempotent operation that simply calculates the\nmetric value using the state variables.\n\n### `update_state`\n\n[View source](https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/keras/metrics.py#L226-L244) \n\n @abc.abstractmethod\n update_state(\n *args, **kwargs\n )\n\nAccumulates statistics for the metric.\n| **Note:** This function is executed as a graph function in graph mode. This means: a) Operations on the same resource are executed in textual order. This should make it easier to do things like add the updated value of a variable to another, for example. b) You don't need to worry about collecting the update ops to execute. All update ops added to the graph by this function will be executed. As a result, code should generally work the same way with graph or eager execution.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ||\n|------------|---------------------------------------|\n| `*args` | \u003cbr /\u003e \u003cbr /\u003e |\n| `**kwargs` | A mini-batch of inputs to the Metric. |\n\n\u003cbr /\u003e"]]