gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:09:25 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com