Как добавить порог в баллах softmax - PullRequest
0 голосов
/ 13 июня 2018

Когда я делаю мультиклассификацию, я обычно получаю оценку 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].Теперь я хочу добавить пороги 0.6 к softmax_socres. Это означает, что ожидаемый прогноз здесь равен [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 голосов
/ 13 июня 2018

Как насчет этого, с использованием 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
...