title: Custom f1_score metric in tensorflow
body: <p>I want to implement the f1_score metric for tf.keras.</p>
  <pre><code>from tensorflow.keras.models import Model, Sequential
  from tensorflow.keras.layers import Dense
  from tensorflow.keras.optimizers import Adam
  from tensorflow.keras.losses import binary_crossentropy
  from tensorflow.keras.metrics import Accuracy, BinaryAccuracy
  from sklearn.metrics import accuracy_score
  import numpy as np
  import tensorflow as tf
  
  class F1_Score(tf.keras.metrics.Metric):
  
      def __init__(self, name='f1_score', **kwargs):
          super().__init__(name=name, **kwargs)
          self.f1 = self.add_weight(name='f1', initializer='zeros')
  
      def update_state(self, y_true, y_pred, sample_weight=None):
          p = Precision(thresholds=0.5)(y_true, y_pred)
          r = Recall(thresholds=0.5)(y_true, y_pred)
          self.f1 = 2 * ((p * r) / (p + r + 1e-6))
  
      def result(self):
          return self.f1
  
      def reset_states(self):
          self.f1.assign(0)
          
  model = Sequential([
    Dense(64, activation='relu', input_shape=(784,)),
    Dense(64, activation='relu'),
    Dense(4, activation='sigmoid'),
  ])
  x = np.random.normal(size=(10, 784))
  y = np.random.choice(2, size=(10, 4))
  model.compile(optimizer=Adam(0.001), loss='binary_crossentropy',
                    metrics=['accuracy', , F1_Score()])
  model.fit(x[:1], y[:1], batch_size=1, epochs=1, verbose=1)
  </code></pre>
  <p>I got an error:</p>
  <blockquote>
  <p>ValueError: tf.function-decorated function tried to create variables
  on non-first call.</p>
  </blockquote>