下面可以看到构建网络的代码。使用probs = tf.nn.softmax(logits)
,我得到概率:
def build_network_test(input_images, labels, num_classes):
logits = embedding_model(input_images, train_phase=True)
logits = fully_connected(logits, num_classes, activation_fn=None,
scope='tmp')
with tf.variable_scope('loss') as scope:
with tf.name_scope('soft_loss'):
softmax = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels))
probs = tf.nn.softmax(logits)
scope.reuse_variables()
with tf.name_scope('acc'):
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits, 1), labels), tf.float32))
with tf.name_scope('loss/'):
tf.summary.scalar('TotalLoss', softmax)
return logits, softmax, accuracy,probs # returns total loss
此外,我正在使用以下代码片段计算accuracy
和loss
:
for idx in range(num_of_batches):
batch_images, batch_labels = get_batch(idx, FLAGS.batch_size, mm_labels, mm_data)
_, summary_str, train_batch_acc, train_batch_loss, probabilities_1 = sess.run(
[train_op, summary_op, accuracy, total_loss, probs],
feed_dict={
input_images: batch_images - mean_data_img_train,
labels: batch_labels,
})
train_acc += train_batch_acc
train_loss += train_batch_loss
train_acc /= num_of_batches
train_acc = train_acc * 100
我的问题:
我得到了两个特征值的概率。之后,我用以下代码对这些概率进行平均
mvalue = np.mean(np.array([probabilities_1, probabilities_2]), axis=0)
现在,我想在mvalue
上计算accuracy
。有人能给我指点一下怎么做吗?
到目前为止我做了什么
tmp = tf.argmax(input=mvalue, axis=1)
an_array = tmp.eval(session=tf.compat.v1.Session())
它给了我谓词标签,然而,我希望有一个准确度值。
到目前为止你所做的一切都很好。。。,希望,如果我理解了,那么你可以很容易地找到平均精度。。。,通过tf.compat.v1.keras.metrics.categorical_accuracy()
所以,我在你的情况下放了一个伪代码,希望这能有所帮助。。。
probabilities_1 = tf.constant([[0.5 , 0.1]])
probabilities_2 = tf.constant([[0.1 , 0.3]])
mvalue = np.mean(np.array([probabilities_1, probabilities_2]), axis=0)
tmp = tf.argmax(input=mvalue, axis=1)
#here, this y_true is your label and tmp is your y_pred your logits
y_true = tf.constant([[0]])
tf.compat.v1.keras.metrics.categorical_accuracy(y_true, tmp)
<tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>
在给定的场景中,有两种方法可以计算精度。两者将产生相同的结果:
方法1
如果我是正确的,您将不得不运行代码片段两次x2次,以获得概率1和概率2的值。此外,每个输入将有2个单独的精度值。
现在,让我们结合这些概率:
mvalue = np.mean(np.array([probabilities_1, probabilities_2]), axis=0)
下一篇:
# y_hat
predicted_labels = tf.argmax(mvalue, 1)
# Of course in tf1 you have to run a Session to get values from tensors.
m_preds = predicted_labels.eval(session=tf.compat.v1.Session())
# Now computing accuracy is straight-forward.
from sklearn import metrics
accuracy = metrics.accuracy_score(y_true, m_preds)
方法2您似乎也在从build_network_test
函数返回logits。在您的主代码中,您还可以计算精度为:
mlogits = np.mean(np.array([logits_1, logits_2]), axis=0)
m_probs = tf.nn.softmax(mlogits)
m_preds = tf.argmax(m_probs, 1)
m_preds_value = m_preds.eval(session=tf.compat.v1.Session())
# Compute accuracy
from sklearn import metrics
accuracy = metrics.accuracy_score(y_true, m_preds_value)