python - TypeError : You are attempting to use Python control flow in a layer that was not declared to be dynamic. 将 `dynamic=True` 传递给类构造函数

标签 python tensorflow neural-network tensorflow2.0 tf.keras

我正在使用 TensorFlow 2.0.0tf.keras创建一个接受 n 个输入的模型网络,[x1,x2,x3,x4,x5,...xn] , 并计算 f(x1,x2,x3,x4,x5,...xn) .

我将我的模型定义为:

def custom_func(vec):   # Test function specifically for a 2-D input
        [x,y] = vec
        x1 = tf.math.atanh(x)
        y1 = tf.math.atanh(y)
        return tf.math.exp(-x1**2 + -y1**2)*(x1**2 + y1**2)

ndim = 2     #Input is 2-D for a sample case
model2 = Sequential()
model2.add(Dense(1, kernel_initializer='ones',bias_initializer='zeros',
                    activation=custom_func, input_shape=(ndim,)))

print(model2.predict(np.array([[1,2],[3,4]])))

在运行以下代码块时,我收到错误:
TypeError: You are attempting to use Python control flow in a layer that was not declared to be dynamic. Pass `dynamic=True` to the class constructor.
Encountered error:
"""
iterating over `tf.Tensor` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
"""

什么可能导致此错误?我该如何解决这个问题?任何帮助/建议都会非常有帮助。

最佳答案

即使我不清楚你想做什么,我也为你尝试过这种方式。希望它可以帮助你。当我们使用急切执行时,它允许立即评估操作,而无需构建图:操作返回具体值而不是构建计算图以稍后运行。m ore info .我将 keras Activation 用于自定义激活功能,将 dynamic=True 用于 Dense 层。到目前为止它一直有效

import tensorflow as tf

import numpy as np

from keras.layers import Activation
from keras import backend as K
from keras.utils.generic_utils import get_custom_objects

@tf.function
def custom_activation(vec):   # Test function specifically for a 2-D input
  [x,y] = vec
  x1 = tf.math.atanh(x)
  y1 = tf.math.atanh(y)
  return tf.math.exp(-x1**2 + -y1**2)*(x1**2 + y1**2)



ndim = 2     #Input is 2-D for a sample case


mnist_model = tf.keras.Sequential([tf.keras.layers.Dense(1, kernel_initializer='ones',bias_initializer='zeros',activation=Activation('custom_activation'), input_shape=(ndim,),dynamic=True)])

@tf.function
def output():
  print(mnist_model(np.array([[1,2],[3,4]])))


output()

输出结果:
Using TensorFlow backend.
Tensor("sequential/dense/Placeholder:0", shape=(2, 1), dtype=float32)

关于python - TypeError : You are attempting to use Python control flow in a layer that was not declared to be dynamic. 将 `dynamic=True` 传递给类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59628640/

相关文章:

通过 Ajax 'is not defined' 调用的 Python 函数

python - 如何在 Django 中使用 toastr 获取成功或失败消息

tensorflow - 如何使用 python 编写此 pbtxt?

python - 如何将字符串数据保存到 TFRecord?

machine-learning - scikit learn如何实现输出层

machine-learning - keras 模型的准确性没有提高

python - 使用 pytorch 进行多类句子分类(使用 nn.LSTM)

python - Flask Caching 文件系统缓存是否跨进程共享?

python - 使用 Python 更改的墙纸在重启时重置为默认值

android - 如何在 Android 上使用 JNI 训练 tensorflow 网络?