![](/img/trans.png)
[英]Using a custom step activation function in Keras results in “An operation has `None` for gradient.” error. How to resolve this?
[英]Using a custom step activation function in Keras results in “'tuple' object has no attribute '_keras_shape'” error. How to resolve this?
我正在尝试在 Keras Z20F35E630DAF49DBFACZ368853 的 output 层中实现二进制自定义激活 function。
这是我的试验:
def binary_activation(x):
ones = tf.ones(tf.shape(x), dtype=x.dtype.base_dtype)
zeros = tf.zeros(tf.shape(x), dtype=x.dtype.base_dtype)
def grad(dy):
return dy
return switch(x > 0.5, ones, zeros), grad
与此处类似。 但我得到以下错误:
文件“/usr/local/lib/python3.6/dist-packages/spyder_kernels/customize/spydercustomize.py”,第 786 行,运行文件 execfile(文件名,命名空间)
文件“/usr/local/lib/python3.6/dist-packages/spyder_kernels/customize/spydercustomize.py”,第 110 行,在 execfile exec(compile(f.read(), filename, 'exec'), namespace)
文件“/home/marlon/Área de Trabalho/omj_project/predicting_change.py”,第 85 行,model = baseline_model()
文件“/home/marlon/Área de Trabalho/omj_project/predicting_change.py”,第 80 行,baseline_model model.add(Dense(1, activation=binary_activation))
文件“/usr/local/lib/python3.6/dist-packages/keras/engine/sequential.py”,第 181 行,添加 output_tensor = layer(self.outputs[0])
文件“/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py”,第 497 行,调用参数=user_kwargs)
文件“/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py”,第 565 行,在 _add_inbound_node output_tensors[i]._keras_shape = output_shapes[i]
AttributeError: 'tuple' object 没有属性 '_keras_shape'
谢谢你的帮助。
你需要添加
@tf.custom_gradient
在您的代码之上,就像您提到的其他评论一样。
@tf.custom_gradient
def binary_activation(x):
ones = tf.ones(tf.shape(x), dtype=x.dtype.base_dtype)
zeros = tf.zeros(tf.shape(x), dtype=x.dtype.base_dtype)
res = tf.keras.backend.switch(x > 0.5, ones, zeros)
def grad(dy):
return dy
return res, grad
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.