如何将KerasTensor转换为张量(Tensorflow)?



我需要将KerasTensor转换为张量,因为当我尝试使用条件(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.

我相信转换张量不会产生错误。

看起来问题是与numpy =1.20版本。把你的numpy版本降级到1.19.5

得到你可以使用下面的样例代码

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)

最新更新