1

我使用 tensorflow 1.12 版

这是我的代码

    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()))

这就是错误

 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'

如何解决这个问题?

4

1 回答 1

0

错误说tf.metrics没有名为的类Mean。您应该tf.metrics.mean改用:

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]))

在急切模式导入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)
于 2019-01-15T07:53:09.707 回答