首页 > 解决方案 > 如何将 KerasTensor 转换为张量(Tensorflow)?

问题描述

我需要将 KerasTensor 转换为 Tensor,因为当我尝试使用 contional ( tf.cond()) 时,它会报告错误:

def custon_loss(self, input_tensor): # input type = <class 'tensorflow.python.keras.engine.keras_tensor.KerasTensor'>
    def loss(y_actual, y_predicted):
        mse = K.mean(K.sum(K.square(y_actual - y_predicted)))
        mse = tf.reshape(mse, [1, 1])
        y_actual = keras.layers.core.Reshape([1, 1])(y_actual)[0]
        ax_input = tf.reshape(input_tensor[0][-1:][0][:1], [1, 1])

        # convert here ax_input to Tensor

        greater_equal = tf.reshape(tf.math.logical_and(tf.math.greater_equal(ax_input, y_actual), tf.math.greater_equal(ax_input, y_predicted))[0], [1, 1])
        less_equal = tf.reshape(tf.math.logical_and(tf.math.less_equal(ax_input, y_actual), tf.math.less_equal(ax_input, y_predicted))[0], [1, 1])
        logical_or = tf.reshape(tf.math.logical_or(greater_equal, less_equal)[0], [1, 1])
        
        return tf.cond(logical_or, lambda: mse, lambda: tf.math.multiply(mse, 10))
    return loss

错误导致tf.cond

TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.

我相信转换张量不会出错。

标签: pythontensorflowkerastensor

解决方案


看起来问题与numpy =1.20版本有关。将您的 numpy 版本降级为1.19.5.

您可以在下面的示例代码中使用 WRT Keras 张量

import tensorflow as tf
import numpy as np
np_var = np.array([1])
keras_var = tf.keras.backend.variable(np_var)
def f1(): return tf.multiply(np_var, 17)
def f2(): return tf.add(np_var, 23)
r = tf.cond(tf.less(np_var, np_var), f1, f2)

推荐阅读