这个错误是因为TensorFlow 2.4.0中删除了Swish激活函数。解决此问题的方法是将您的代码中Swish函数的使用更改为类似于此的内容:
import tensorflow as tf
def swish(x, beta = 1.0):
return x * tf.keras.activations.sigmoid(beta * x)
# 在您的代码中使用新函数
output = swish(input_tensor)
您还可以通过从GitHub TensorFlow仓库中直接复制函数来添加自己的Swish实现。只需将以下代码添加到您的代码中:
import tensorflow as tf
from tensorflow.python.ops import math_ops
@tf.RegisterGradient("Swish")
def _swish_grad(op, grad):
sigmoid = tf.math.sigmoid(op.outputs[0])
activation = op.outputs[0] + tf.multiply(tf.constant(op.get_attr('beta'), dtype=tf.float32), tf.math.sigmoid(tf.multiply(op.outputs[0], op.outputs[0])))
return grad * activation * (sigmoid * (1 + tf.multiply(tf.constant(op.get_attr('beta'), dtype=tf.float32), (1 - sigmoid))))
@tf.keras.utils.register_keras_serializable()
def swish(x, beta=1.0, name=None):
with tf.name_scope(name or "swish"):
beta_tensor = tf.convert_to_tensor(beta, dtype=x.dtype, name="beta")
return x * tf.math.sigmoid(beta_tensor * x)