ChatGPT解决这个技术问题 Extra ChatGPT

NotImplementedError:无法将符号张量 (2nd_target:0) 转换为 numpy 数组

我尝试将 2 个损失函数作为 Keras allows that. 传递给模型

loss:字符串(目标函数的名称)或目标函数或损失实例。见损失。如果模型有多个输出,您可以通过传递字典或损失列表对每个输出使用不同的损失。模型将最小化的损失值将是所有单个损失的总和。

两个损失函数:

def l_2nd(beta):
    def loss_2nd(y_true, y_pred):
        ...
        return K.mean(t)

    return loss_2nd

def l_1st(alpha):
    def loss_1st(y_true, y_pred):
        ...
        return alpha * 2 * tf.linalg.trace(tf.matmul(tf.matmul(Y, L, transpose_a=True), Y)) / batch_size

    return loss_1st

然后我建立模型:

l2 = K.eval(l_2nd(self.beta))
l1 = K.eval(l_1st(self.alpha))
self.model.compile(opt, [l2, l1])

当我训练时,它会产生错误:

1.15.0-rc3 WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630:
calling BaseResourceVariable.__init__ (from
tensorflow.python.ops.resource_variable_ops) with constraint is
deprecated and will be removed in a future version. Instructions for
updating: If using Keras pass *_constraint arguments to layers.
--------------------------------------------------------------------------- 
NotImplementedError                       Traceback (most recent call
last) <ipython-input-20-298384dd95ab> in <module>()
     47                          create_using=nx.DiGraph(), nodetype=None, data=[('weight', int)])
     48 
---> 49     model = SDNE(G, hidden_size=[256, 128],)
     50     model.train(batch_size=100, epochs=40, verbose=2)
     51     embeddings = model.get_embeddings()

10 frames <ipython-input-19-df29e9865105> in __init__(self, graph,
hidden_size, alpha, beta, nu1, nu2)
     72         self.A, self.L = self._create_A_L(
     73             self.graph, self.node2idx)  # Adj Matrix,L Matrix
---> 74         self.reset_model()
     75         self.inputs = [self.A, self.L]
     76         self._embeddings = {}

<ipython-input-19-df29e9865105> in reset_model(self, opt)

---> 84         self.model.compile(opt, loss=[l2, l1])
     85         self.get_embeddings()
     86 

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/tracking/base.py
in _method_wrapper(self, *args, **kwargs)
    455     self._self_setattr_tracking = False  # pylint: disable=protected-access
    456     try:
--> 457       result = method(self, *args, **kwargs)
    458     finally:
    459       self._self_setattr_tracking = previous_value  # pylint: disable=protected-access

NotImplementedError: Cannot convert a symbolic Tensor (2nd_target:0)
to a numpy array.

请帮忙,谢谢!

即使我面临同样的问题,当我禁用急切执行时它也能完美运行。
@Siddhant 您是否找到了替代方案而无需禁用急切执行?禁用它似乎可以解决问题,但我不再受益于急切执行的其他功能。

C
CGFoX

对我来说,从 numpy 1.19 升级到 1.20 并使用 ray 的 RLlib(它在内部使用 tensorflow 2.2)时出现了问题。只需降级

pip install numpy==1.19.5

解决了问题;该错误不再发生。

更新(@codeananda 评论):您现在也可以更新到更新的 TensorFlow (2.6+) 版本来解决问题 (pip install -U tensorflow)。


这也是我的问题,解决方案有效,谢谢
为什么较低的版本是公认的版本?它只是说:不要使用 numpy。但是,当您依赖它时,就不可能实施该解决方案。这是唯一正确的答案。
我想知道是否有解决方法。我不想回滚我的 numpy。
这是一条红鲱鱼..正确的答案应该解决以下解决方案完美的根本原因..我们都从中学到了一些东西
tensorflow 和 numpy 1.20 似乎存在一些兼容性问题。无论如何,tensorflow 并未正式支持 Numpy 1.20,因此目前正确的解决方案是降级到 numpy 1.19,直到某些未来的 tensorflow 版本实现与 numpy 1.20 的兼容性。
T
T D Nguyen

我找到了解决这个问题的方法:

这是因为我将符号张量与非符号类型(例如 numpy.例如。不建议有这样的东西:

def my_mse_loss_b(b):
     def mseb(y_true, y_pred):
         ...
         a = np.ones_like(y_true) #numpy array here is not recommended
         return K.mean(K.square(y_pred - y_true)) + a
     return mseb

相反,您应该将所有转换为符号张量,如下所示:

def my_mse_loss_b(b):
     def mseb(y_true, y_pred):
         ...
         a = K.ones_like(y_true) #use Keras instead so they are all symbolic
         return K.mean(K.square(y_pred - y_true)) + a
     return mseb

希望这有帮助!


但我没有在计算中的任何地方使用 numpy。 github.com/siddhantkushwaha/east_1x/blob/east_tf2.0/losses.py
我的意思是尽量确保所有类型都是符号,如示例中所示,尤其是损失函数的参数。它适用于我的情况。
我也有同样的问题。 tf.zeros 内部使用 numpy,因此无法避免。
f
fidel morris omolo

我遇到了同样的错误。当我尝试将输入层传递给数据增强顺序层时。错误和我的代码如下所示。
错误:
NotImplementedError: Cannot convert a symbolic Tensor (data_augmentation/random_rotation_5/rotation_matrix/strided_slice:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported.

我产生错误的代码:


#Create data augmentation layer using the Sequential model using horizontal flipping, rotations and zoom etc.
data_augmentation = Sequential([
    preprocessing.RandomFlip("horizontal"),
    preprocessing.RandomRotation(0.2),
    preprocessing.RandomZoom(0.2),
    preprocessing.RandomHeight(0.2),
    preprocessing.RandomWidth(0.2)
   # preprocessing.Rescale()
], name="data_augmentation")

# Setting up the input_shape and base model, and freezing the underlying base model layers.
input_shape = (224,224,3)
base_model = tf.keras.applications.EfficientNetB0(include_top=False)
base_model.trainable=False

#Create the input layers
inputs = tf.keras.Input(shape=input_shape, name="input_layer")

#Add in data augmentation Sequential model as a layer
x = data_augmentation(inputs) #This is the line of code that generated the error.

我对生成的错误的解决方案: 解决方案 1:我在较低版本的 Tensorflow 版本 2.4.0 上运行。所以我卸载它并重新安装它以获得更高版本的 2.6.0。较新的张量流版本会自动卸载并重新安装 numpy 版本(1.19.5)(如果您的本地计算机中已经安装了 numpy)。这将自动解决错误。在当前 conda 环境的终端中输入以下命令:

pip uninstall tensorflow
pip install tensorflow

解决方案 2:我猜它是所有建议解决方案中最简单的。在 Google colab 而不是本地计算机中运行您的代码。 Colab 将始终预装最新的软件包。


非常有帮助的是,通过升级到更新版本的 TF (2.6+),它会自动安装正确的 numpy 版本以避免这个问题。
A
Alper

我尝试将 SimpleRNN 层添加到我的模型中,但在 Python 3.9.5 中收到了类似的错误(NotImplementedError:无法将符号张量 (SimpleRNN-1/strided_slice:0) 转换为 numpy 数组)。

当我使用 Python 3.8.10 和我需要的所有其他模块创建另一个环境时,问题就解决了。


T
Tarik

正如其他人所指出的,这是由于特定 tensorflow 版本和特定 numpy 版本之间的不兼容造成的。

以下是我的具体环境和我已经安装的包列表:

康达版本 4.11.0

设置工作环境的命令:

conda activate base
conda create -y --name myenv python=3.9
conda activate myenv
conda install -y tensorflow=2.4
conda install -y numpy=1.19.2
conda install -y keras

系统信息

System:    Kernel: 5.4.0-100-generic x86_64 bits: 64 compiler: gcc v: 9.3.0 
           Desktop: Cinnamon 5.2.7 wm: muffin dm: LightDM Distro: Linux Mint 20.3 Una 
           base: Ubuntu 20.04 focal 
Machine:   Type: Laptop System: LENOVO product: 20308 v: Lenovo Ideapad Flex 14 serial: <filter> 
           Chassis: type: 10 v: Lenovo Ideapad Flex 14 serial: <filter> 
           Mobo: LENOVO model: Strawberry 4A v: 31900059Std serial: <filter> UEFI: LENOVO 
           v: 8ACN30WW date: 12/06/2013 
CPU:       Topology: Dual Core model: Intel Core i5-4200U bits: 64 type: MT MCP arch: Haswell 
           rev: 1 L2 cache: 3072 KiB 
           flags: avx avx2 lm nx pae sse sse2 sse3 sse4_1 sse4_2 ssse3 vmx bogomips: 18357 
           Speed: 798 MHz min/max: 800/2600 MHz Core speeds (MHz): 1: 798 2: 798 3: 798 4: 799 
Graphics:  Device-1: Intel Haswell-ULT Integrated Graphics vendor: Lenovo driver: i915 v: kernel 
           bus ID: 00:02.0 chip ID: 8086:0a16 
           Display: x11 server: X.Org 1.20.13 driver: modesetting unloaded: fbdev,vesa 
           resolution: 1366x768~60Hz 
           OpenGL: renderer: Mesa DRI Intel HD Graphics 4400 (HSW GT2) v: 4.5 Mesa 21.2.6 
           compat-v: 3.0 direct render: Yes 
 

S
Singh

我在将暗网权重转换为 TensorFlow 模型时遇到了这个问题。当我使用 Tensorflow v2.3(之前是 Tensorflow v2.2)创建一个新环境并且预装了 NumPy 时,我摆脱了这个问题。

所以也许更新你的 TF 版本可能会解决这个问题。


g
gojira

我有同样的问题并解决了。

为了找到根本原因,我使用 python 3.8 创建了一个新的 anaconda 环境,并且 conda 安装了 tensorflow(安装 2.4)

当我运行 keras LSTM 代码时,它出现了

rnnmodel.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))

通过安装最新的 tensorflow 2.8 修复它

pip uninstall tensorflow
pip install tensorflow

p
philsavor

以下配置对我有用。

蟒蛇=3.8

张量流=2.8.0


正如目前所写的那样,您的答案尚不清楚。请edit添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以找到有关如何写出好答案的更多信息in the help center
A
Avateer

进入 Anaconda Navigator 找到你安装的包(numpy) 点击包左边的绿色勾“mark for specific version installation” 选择版本,应用


从命令提示符更难做

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅