- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试了解 tf.metrics.accuracy
的工作原理。我想比较下面给出的函数的批量准确度结果
with tf.name_scope('Accuracy1'):
correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(y, 1))
accuracy1 = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name="accuracy")
与
with tf.name_scope('Accuracy2'):
accuracy2, accuracy_op = tf.metrics.accuracy(labels=tf.argmax(y, 1), predictions=tf.argmax(predictions, 1))
下面提供了最小的工作示例:
import numpy as np
import pandas as pd
import tensorflow as tf
import math
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
num_steps=28
num_inputs = 28
num_classes = 10
num_neurons = 128
num_layers = 3
batch_size = 500
graph = tf.Graph()
with graph.as_default():
with tf.name_scope("graph_inputs"):
X = tf.placeholder(tf.float32, [None, num_steps, num_inputs], name='input_placeholder')
y = tf.placeholder(tf.float32, [None, num_classes], name='labels_placeholder')
output_keep_prob = tf.placeholder_with_default(1.0, shape=(), name ="output_dropout")
def build_lstm_cell(num_neurons, output_keep_prob):
"""Returns a dropout-wrapped LSTM-cell.
See https://stackoverflow.com/a/44882273/2628369 for why this local function is necessary.
Returns:
tf.contrib.rnn.DropoutWrapper: The dropout-wrapped LSTM cell.
"""
initializer = tf.contrib.layers.xavier_initializer()
lstm_cell = tf.contrib.rnn.LSTMCell(num_units=num_neurons, initializer=initializer, forget_bias=1.0, state_is_tuple=True, name='LSTM_cell')
lstm_cell_drop = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=output_keep_prob)
return lstm_cell_drop
with tf.name_scope("LSTM"):
with tf.name_scope("Cell"):
multi_layer_cell = tf.contrib.rnn.MultiRNNCell([build_lstm_cell(num_neurons, output_keep_prob) for _ in range(num_layers)], state_is_tuple=True)
with tf.name_scope("Model"):
outputs, states = tf.nn.dynamic_rnn(cell=multi_layer_cell, inputs=X, swap_memory=False, time_major = False, dtype=tf.float32)#[Batch_size, time_steps, num_neurons]
with tf.name_scope("Graph_Outputs"):
outputs = tf.transpose(outputs, [1, 0, 2]) # [num_timesteps, batch_size, num_neurons]
outputs = tf.gather(outputs, int(outputs.get_shape()[0]) - 1) # [batch_size, num_neurons]
with tf.variable_scope('Softmax'):
logits = tf.layers.dense(inputs = outputs, units = num_classes, name="logits") #[Batch_size, num_classes]
with tf.name_scope('Predictions'):
predictions = tf.nn.softmax(logits, name="predictions") #[Batch_size, num_classes]
with tf.name_scope('Accuracy1'):
correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(y, 1))
accuracy1 = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name="accuracy")
with tf.name_scope('Accuracy2'):
accuracy2, accuracy_op = tf.metrics.accuracy(labels=tf.argmax(y, 1), predictions=tf.argmax(predictions, 1))
with tf.name_scope('Loss'):
xentropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y)
loss = tf.reduce_mean(xentropy, name="loss")
with tf.name_scope('Train'):
optimizer= tf.train.AdamOptimizer(learning_rate=0.0001)
trainer=optimizer.minimize(loss, name="training_op")
with tf.Session(graph = graph) as sess:
tf.global_variables_initializer().run()
total_batch = mnist.train.num_examples // batch_size
for batch in range(total_batch):
tf.local_variables_initializer().run()
xBatch, yBatch = mnist.train.next_batch(batch_size)
xBatch = xBatch.reshape((batch_size, num_steps, num_inputs))
sess.run(trainer, feed_dict={X: xBatch, y: yBatch, output_keep_prob: 0.5})
miniBatchAccuracy1 = sess.run(accuracy1, feed_dict={X: xBatch, y: yBatch, output_keep_prob: 0.5})
print('[hand-written] Batch {} accuracy: {}'.format(batch, miniBatchAccuracy1))
accuracy_op_val = sess.run(accuracy_op, feed_dict={X: xBatch, y: yBatch, output_keep_prob: 0.5})
miniBatchAccuracy2 = sess.run(accuracy2)
print("[tf.metrics.accuracy] Batch {} accuracy: {}".format(batch, miniBatchAccuracy2))
sess.close()
我使用这两种方法打印每个批处理的准确度值,它们是不同的。结果不应该是一样的吗?
[hand-written] Batch 0 accuracy: 0.09600000083446503
[tf.metrics.accuracy] Batch 0 accuracy: 0.09399999678134918
[hand-written] Batch 1 accuracy: 0.1120000034570694
[tf.metrics.accuracy] Batch 1 accuracy: 0.07800000160932541
[hand-written] Batch 2 accuracy: 0.10199999809265137
[tf.metrics.accuracy] Batch 2 accuracy: 0.09600000083446503
[hand-written] Batch 3 accuracy: 0.12999999523162842
[tf.metrics.accuracy] Batch 3 accuracy: 0.12800000607967377
[hand-written] Batch 4 accuracy: 0.1379999965429306
[tf.metrics.accuracy] Batch 4 accuracy: 0.10199999809265137
[hand-written] Batch 5 accuracy: 0.16200000047683716
[tf.metrics.accuracy] Batch 5 accuracy: 0.1340000033378601
[hand-written] Batch 6 accuracy: 0.1340000033378601
[tf.metrics.accuracy] Batch 6 accuracy: 0.12600000202655792
[hand-written] Batch 7 accuracy: 0.12999999523162842
[tf.metrics.accuracy] Batch 7 accuracy: 0.16200000047683716
...
...
...
...
最佳答案
在测量这两种情况的准确性时,您将辍学率
传递为0.5。这就是它给出两个不同值的原因。将 dropout
值设置为 1.0,您应该会看到这两种情况的类似值。
关于python - tf.metrics.accuracy 和手写准确度函数给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53255873/
在 Tensorflow(从 v1.2.1 开始)中,似乎有(至少)两个并行 API 来构建计算图。 tf.nn 中有函数,如 conv2d、avg_pool、relu、dropout,tf.laye
我正在处理眼睛轨迹数据和卷积神经网络。我被要求使用 tf.reduce_max(lastconv, axis=2)代替 MaxPooling 层和 tf.reduce_sum(lastconv,axi
TensorFlow 提供了 3 种不同的数据存储格式 tf.train.Feature .它们是: tf.train.BytesList tf.train.FloatList tf.train.In
我正在尝试为上下文强盗问题 (https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part
我在使用 Tensorflow 时遇到问题: 以下代码为卷积 block 生成正确的图: def conv_layer(self, inputs, filter_size = 3, num_filte
我正在将我的训练循环迁移到 Tensorflow 2.0 API .在急切执行模式下,tf.GradientTape替换 tf.gradients .问题是,它们是否具有相同的功能?具体来说: 在函数
tensorflow 中 tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)) 的目的是什么? 更多上下文:
我一直在努力学习 TensorFlow,我注意到不同的函数用于相同的目标。例如,为了平方变量,我看到了 tf.square()、tf.math.square() 和 tf.keras.backend.
我正在尝试使用自动编码器开发图像着色器。有 13000 张训练图像。如果我使用 tf.data,每个 epoch 大约需要 45 分钟,如果我使用 tf.utils.keras.Sequence 大约
我尝试按照 tensorflow 教程实现 MNIST CNN 神经网络,并找到这些实现 softmax 交叉熵的方法给出了不同的结果: (1) 不好的结果 softmax = tf.nn.softm
其实,我正在coursera上做deeplearning.ai的作业“Art Generation with Neural Style Transfer”。在函数 compute_layer_styl
训练神经网络学习“异或” 我正在尝试使用“批量归一化”,我创建了一个批量归一化层函数“batch_norm1”。 import tensorflow as tf import nump
我正在尝试协调来自 TF“图形和 session ”指南以及 TF“Keras”指南和 TF Estimators 指南的信息。现在在前者中它说 tf.Session 使计算图能够访问物理硬件以执行图
我正在关注此处的多层感知器示例:https://github.com/aymericdamien/TensorFlow-Examples我对函数 tf.nn.softmax_cross_entropy
回到 TensorFlow = 2.0 中消失了。因此,像这样的解决方案...... with tf.variable_scope("foo"): with tf.variable_scope
我按照官方网站中的步骤安装了tensorflow。但是,在该网站中,作为安装的最后一步,他们给出了一行代码来“验证安装”。但他们没有告诉这段代码会给出什么输出。 该行是: python -c "imp
代码: x = tf.constant([1.,2.,3.], shape = (3,2,4)) y = tf.constant([1.,2.,3.], shape = (3,21,4)) tf.ma
我正在尝试从 Github 训练一个 3D 分割网络.我的模型是用 Keras (Python) 实现的,这是一个典型的 U-Net 模型。模型,总结如下, Model: "functional_3"
我正在使用 TensorFlow 2。我正在尝试优化一个函数,该函数使用经过训练的 tensorflow 模型(毒药)的损失。 @tf.function def totalloss(x): x
试图了解 keras 优化器中的 SGD 优化代码 (source code)。在 get_updates 模块中,我们有: # momentum shapes = [K.int_shape(p) f
我是一名优秀的程序员,十分优秀!