Python tensorflow 模块,confusion_matrix() 实例源码
我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用tensorflow.confusion_matrix()。
def confusion_matrix_op(logits, labels, num_classes):
"""Creates the operation to build the confusion matrix between the
predictions and the labels. The number of classes are required to build
the matrix correctly.
Args:
logits: a [batch_size, 1,1, num_classes] tensor or
a [batch_size, num_classes] tensor
labels: a [batch_size] tensor
Returns:
confusion_matrix_op: the confusion matrix tf op
"""
with tf.variable_scope('confusion_matrix'):
# handle fully convolutional classifiers
logits_shape = logits.shape
if len(logits_shape) == 4 and logits_shape[1:3] == [1, 1]:
top_k_logits = tf.squeeze(logits, [1, 2])
else:
top_k_logits = logits
# Extract the predicted label (top-1)
_, top_predicted_label = tf.nn.top_k(top_k_logits, k=1, sorted=False)
# (batch_size, k) -> k = 1 -> (batch_size)
top_predicted_label = tf.squeeze(top_predicted_label, axis=1)
return tf.confusion_matrix(
labels, top_predicted_label, num_classes=num_classes)
def single_label(predictions_batch, one_hot_labels_batch, moving_average=True):
with tf.variable_scope('metrics'):
shape = predictions_batch.get_shape().as_list()
batch_size, num_outputs = shape[0], shape[1]
# get the most probable label
predicted_batch = tf.argmax(predictions_batch, axis=1)
real_label_batch = tf.argmax(one_hot_labels_batch, axis=1)
# tp, tn, fp, fn
predicted_bool = tf.cast(tf.one_hot(predicted_batch, depth=num_outputs), dtype=tf.bool)
real_bool = tf.cast(tf.one_hot(real_label_batch, depth=num_outputs), dtype=tf.bool)
d = _metrics(predicted_bool, real_bool, moving_average)
# confusion matrix
confusion_batch = tf.confusion_matrix(labels=real_label_batch, predictions=predicted_batch,
num_classes=num_outputs)
if moving_average:
# calculate moving averages
confusion_batch = tf.cast(confusion_batch, dtype=tf.float32)
ema = tf.train.ExponentialMovingAverage(decay=0.9)
update_op = ema.apply([confusion_batch])
confusion_matrix = ema.average(confusion_batch)
d['update_op'] = [d['update_op'], update_op]
else:
# accumulative
confusion_matrix = tf.Variable(tf.zeros([num_outputs, num_outputs], dtype=tf.int32),
name='confusion_matrix', trainable=False)
confusion_matrix = tf.assign_add(confusion_matrix, confusion_batch)
d['confusion_matrix'] = confusion_matrix
return d
def single_label(predictions_batch, one_hot_labels_batch, moving_average=True):
with tf.variable_scope('metrics'):
shape = predictions_batch.get_shape().as_list()
batch_size, num_outputs = shape[0], shape[1]
# get the most probable label
predicted_batch = tf.argmax(predictions_batch, axis=1)
real_label_batch = tf.argmax(one_hot_labels_batch, axis=1)
# tp, tn, fp, fn
predicted_bool = tf.cast(tf.one_hot(predicted_batch, depth=num_outputs), dtype=tf.bool)
real_bool = tf.cast(tf.one_hot(real_label_batch, depth=num_outputs), dtype=tf.bool)
d = _metrics(predicted_bool, real_bool, moving_average)
# confusion matrix
confusion_batch = tf.confusion_matrix(labels=real_label_batch, predictions=predicted_batch,
num_classes=num_outputs)
if moving_average:
# calculate moving averages
confusion_batch = tf.cast(confusion_batch, dtype=tf.float32)
ema = tf.train.ExponentialMovingAverage(decay=0.9)
update_op = ema.apply([confusion_batch])
confusion_matrix = ema.average(confusion_batch)
d['update_op'] = [d['update_op'], update_op]
else:
# accumulative
confusion_matrix = tf.Variable(tf.zeros([num_outputs, num_outputs], dtype=tf.int32),
name='confusion_matrix', trainable=False)
confusion_matrix = tf.assign_add(confusion_matrix, confusion_batch)
d['confusion_matrix'] = confusion_matrix
return d
def _compute_specific(self, predicted, targets):
targets = tf.cast(targets, tf.int64)
return tf.confusion_matrix(labels=targets,
predictions=predicted,
num_classes=self._num_classes)
def _calculate_miou(self,logits,label_batch):
with tf.variable_scope('MIOU_CAL'):
confusion_matrix = tf.confusion_matrix(labels=tf.reshape(label_batch,[-1]),predictions=tf.reshape(logits,[-1]),num_classes=N_CLASSES,dtype=tf.float32)
def cal_miou(matrix):
sum_col = np.zeros(shape = [N_CLASSES],dtype=np.float32)
sum_row = np.zeros(shape = [N_CLASSES],dtype=np.float32)
miou = np.zeros(shape = [],dtype=np.float32)
for i in range(N_CLASSES):
for j in range(N_CLASSES):
sum_row[i] += matrix[i][j]
sum_col[j] += matrix[i][j]
for i in range(N_CLASSES):
miou += matrix[i][i]/(sum_col[i]+sum_row[i]-matrix[i][i])
miou = (miou/N_CLASSES).astype(np.float32)
return miou
miou = tf.py_func(cal_miou, [confusion_matrix], tf.float32)
# def miou_fun(eval,label):
#
# miou1 = 0.0
# for i in range(BATCH_SIZE):
# img = eval[i]
# gt = label[i]
# miou1 += py_img_seg_eval.mean_IU(img, gt)
# miou1 = float(miou1/BATCH_SIZE)
# print miou1
# return miou1
#
#
# miou1 = tf.py_func(miou_fun,[logits,label_batch],tf.double)
return miou #,miou1