简体   繁体   中英

module 'tensorflow._api.v1.metrics' has no attribute 'Mean'

I use tensorflow version 1.12

this is my code

    train_loss_results = []
train_accuracy_results = []
num_epochs = 201

for epoch in range(num_epochs):
    epoch_loss_avg = tf.metrics.Mean()
    epoch_accuracy = tf.metrics.Accuracy()
    for x,y in train_dataset:
        loss_value,grads = grad(model,x,y)
        optimizer.apply_gradients(zip(grads,model.variables),global_step)
        epoch_loss_avg(loss_value)
        epoch_accuracy(tf.argmax(model(x), axis=1, output_type=tf.int32), y)
train_loss_results.append(epoch_loss_avg.result())
train_accuracy_results.append(epoch_accuracy.result())
if epoch % 50 == 0:
    print("Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}".format(epoch,
                                                                epoch_loss_avg.result(),
                                                                epoch_accuracy.result()))

and this is the error

 AttributeError                            Traceback (most recent call last)
<ipython-input-33-6c3fabbf8b76> in <module>
      4 
      5 for epoch in range(num_epochs):
----> 6     epoch_loss_avg = tf.metrics.Mean()
      7     epoch_accuracy = tf.metrics.Accuracy()
      8     for x,y in train_dataset:


AttributeError: module 'tensorflow._api.v1.metrics' has no attribute 'Mean'

How to solve this?

The error says tf.metrics has no class named Mean . You should use tf.metrics.mean instead:

import tensorflow as tf

values = tf.constant([[1, 2],
                      [3, 4]])

weights = tf.constant([[1, 0],
                       [1, 0]])

mean, mean_op = tf.metrics.mean(values, weights)

with tf.Session() as sess:
    sess.run(tf.local_variables_initializer())
    sess.run(tf.global_variables_initializer())
    print(sess.run([mean, mean_op]))
    print(sess.run([mean]))

In eager-mode import tf.contrib.eager.metrics.Mean :

tf.enable_eager_execution()

values = tf.constant([[1, 2],
                      [3, 4]])

weights = tf.constant([[0, 2],
                     [2, 0]])

mean = tf.contrib.eager.metrics.Mean()(values, weights)
print(mean)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM