如何从 TensorFlow 中的函数返回张量的值



我正在 Keras 中从事一个深度学习项目,并使用 TensorFlow 后端实现了一个灵敏度函数,因为如果我想使用它评估模型,这是必需的。但是,我无法从张量中提取值。我想返回它,以便我可以在其他函数中使用这些值。理想情况下,返回值应为int。每当我评估函数时,我只会得到张量对象本身,而不是它的实际值。

我尝试创建一个会话并进行评估,但无济于事。我能够以这种方式很好地打印值,但我无法将值分配给另一个变量。

def calculate_tp(y, y_pred):
    TP = 0
    FP = 0
    TN = 0
    FN = 0
    for i in range(5):
        true = K.equal(y, i)
        preds = K.equal(y_pred, i)
        TP += K.sum(K.cast(tf.boolean_mask(preds, tf.math.equal(true, True)), 'int32'))
        FP += K.sum(K.cast(tf.boolean_mask(true, tf.math.equal(~preds, True)), 'int32'))
        TN += K.sum(K.cast(tf.boolean_mask(~preds, tf.math.equal(true, True)), 'int32'))
        FN += K.sum(K.cast(tf.boolean_mask(true, tf.math.equal(preds, False)), 'int32'))
    """with tf.Session() as sess:
    TP = TP.eval()
    FP = FP.eval()
    FN = FN.eval()
    FP = FP.eval()
    print(TP, FP, TN, FN)
    #sess.run(FP)"""
    return TP / (TP + FN)

如果我很好地理解你的问题,你可以简单地创建一个带有值的新张量 痴迷。

例如:

tensor = tf.constant([5, 5, 8, 6, 10, 1, 2])
tensor_value = tensor.eval(session=tf.Session())
print(tensor_value) #get [ 5  5  8  6 10  1  2]
new_tensor = tf.constant(tensor_value)
print(new_tensor) #get Tensor("Const_25:0", shape=(7,), dtype=int32)

希望我有帮助!

好的,可能是因为在您的尝试中TP始终为0

如果我尝试:

y = np.array([0, 0, 0, 0, 0, 1, 1, 1 ,1 ,1])
y_pred = np.array([0.01, 0.005, 0.5, 0.09, 0.56, 0.999, 0.89, 0.987 ,0.899 ,1])
def calculate_tp(y, y_pred):
    TP = 0
    FP = 0
    TN = 0
    FN = 0
    for i in range(5):
        true = K.equal(y, i)
        preds = K.equal(y_pred, i)
        TP += K.sum(K.cast(tf.boolean_mask(preds, tf.math.equal(true, True)), 'int32'))
        FP += K.sum(K.cast(tf.boolean_mask(true, tf.math.equal(~preds, True)), 'int32'))
        TN += K.sum(K.cast(tf.boolean_mask(~preds, tf.math.equal(true, True)), 'int32'))
        FN += K.sum(K.cast(tf.boolean_mask(true, tf.math.equal(preds, False)), 'int32'))
        TP = TP.eval(session=tf.Session())
        FP = FP.eval(session=tf.Session())
        TN = TN.eval(session=tf.Session())
        FN = FN.eval(session=tf.Session())
        print(TP, FP, TN, FN)
    results = TP / (TP + FN)
    return results
res = calculate_tp(y, y_pred)
print(res) 
#Outputs : 
#0 5 5 5
#1 9 9 9
#1 9 9 9
#1 9 9 9
#1 9 9 9
#0.1

它给了我一个浮点数,就像你想要的那样。

有帮助吗?

最新更新