python - 如何将 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.
我相信转换张量不会出错。
解决方案
看起来问题与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)
推荐阅读
- delphi - Mediaplayer更改歌曲更改不起作用delphi 2010
- java - 是否有将格式化文本插入任意文件的 Java 函数或库?
- google-sheets - 处理重复的索引最小公式
- javascript - 从 mongoDB 检索指定数据的最佳实践
- nuxt.js - Vite:如何指定需要监视的文件夹
- java - 使用 ND4J 进行布尔索引
- java - 错误:选项 -Xbootclasspath/p:目标 14 不允许 - Netbeans 12
- hyperledger-fabric - Hyperledger,使用 configtxgen CLI 工具创建通道
- powerbi - Power BI - 如何将 Web URL 分配给图像
- python - Pandas - 根据 str 包含从另一列创建具有值的新列