如何在softmax分数中添加阈值

时间:2018-06-13 03:28:49

标签: python tensorflow deep-learning classification multilabel-classification

在进行多分类时,通常我得到softmax分数和下面的预测值,

softmax_scores = tf.nn.softmax(logits=self.scores, dim=-1)
prediction=tf.argmax(self.scores, 1, name="predictions")

如果我得到的softmax_socres是[0.5,0.2,0.3]。预测是[0]。 现在我想向softmax_socres添加阈值0.6。这意味着此处预期的预测是[4],这意味着其他人。 我做了如下

threshold=0.6
self.predictions = tf.argmax(self.scores, 1, name="predictions")
x = tf.constant([num_classes], shape=self.predictions.shape, dtype=tf.int64)
self.predictions1 =tf.where(tf.reduce_max(tf.nn.softmax(logits=self.scores, dim=-1),1)>=threshold,self.predictions,x)

得到了:

File "E:\ai\wide-and-shallow cnn\text_cnn.py", line 102, in __init__
    x = tf.constant([num_classes], shape=self.predictions.shape, dtype=tf.int64)
  File "E:\Python\Python36\lib\site-packages\tensorflow\python\framework\constant_op.py", line 214, in constant
    value, dtype=dtype, shape=shape, verify_shape=verify_shape))
  File "E:\Python\Python36\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 430, in make_tensor_proto
    if shape is not None and np.prod(shape, dtype=np.int64) == 0:
  File "E:\Python\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 2566, in prod
    out=out, **kwargs)
  File "E:\Python\Python36\lib\site-packages\numpy\core\_methods.py", line 35, in _prod
    return umr_prod(a, axis, dtype, out, keepdims)
TypeError: __int__ returned non-int (type NoneType)

它在这个演示中有效。

import tensorflow as tf
import numpy as np
a=tf.constant(np.arange(6),shape=(3,2))
b=tf.reduce_max(a,1)
#c=tf.to_int32(a>3)
c=tf.argmax(a,1)
d=b>=3
f=tf.constant([5],shape=c.shape,dtype=tf.int64)
e=tf.where(d,c,f)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(a.eval(),b.eval(),c.eval(),d.eval(),f.eval(),e.eval())

1 个答案:

答案 0 :(得分:1)

如何使用tf.where

这样做
threshold = 0.6

softmax_scores = tf.nn.softmax(logits=self.scores, dim=-1)

other_class_idx = tf.cast(tf.shape(softmax_scores)[0] + 1, tf.int64)
other_class_idx = tf.tile( \
    tf.expand_dims(other_class_idx, 0), \
    [tf.shape(softmax_scores)[0]] \
)

is_other = tf.reduce_max(tf.cast(softmax_scores > threshold, tf.int8), axis=1)

predictions = tf.where( \
                 is_other>0, \
                 tf.argmax(softmax_scores, 1), \
                 other_class_idx \
              ) # 4