一、tensorflow中常用的模型定义
import tensorflow as tf
model=tf.keras.Sequential([
tf.keras.layers.Dense(64, kernel_initializer='normal', activation='relu'),
tf.keras.layers.Dense(1, kernel_initializer='normal', activation='relu')
)]
上面这段代码定义了两层,输出为一个元素。
如果想实验自己的激活函数,又不想过多地写代码。可以使用以下方法:
比如定义tanh
![\tanh(x)=\frac{e^x-e^{-x}}{e^x+e^{-x}}=\frac{e^{2x}-1}{e^{2x}+1}=1-\frac{2}{e^{2x}+1}](https://latex.csdn.net/eq?%5Ctanh%28x%29%3D%5Cfrac%7Be%5Ex-e%5E%7B-x%7D%7D%7Be%5Ex+e%5E%7B-x%7D%7D%3D%5Cfrac%7Be%5E%7B2x%7D-1%7D%7Be%5E%7B2x%7D+1%7D%3D1-%5Cfrac%7B2%7D%7Be%5E%7B2x%7D+1%7D)
二、在keras网站上对自定义激活函数有如下说明:
Creating custom activations
You can also use a TensorFlow callable as an activation (in this case it should take a tensor and return a tensor of the same shape and dtype):
简单地翻译:你可以使用一个可调用的tensorflow作为激活函数(这种情况下,它输入一个张量并且返回一个具有同样形状和类型的张量)
三、例子:
import tensorflow as tf
def m_tanh(x):
return 1-2/(tf.math.exp(2*x)+1)
model=tf.keras.Sequential([
tf.keras.layers.Dense(64, kernel_initializer='normal', activation=m_tanh),
tf.keras.layers.Dense(1, kernel_initializer='normal', activation=m_tanh)
)]
四、总结:
tensorflow中可以自定义单独的激活函数。只要保证输入、输出是形状和元素数据类型一样就可以。
当然如果想定义复杂的激活函数,就需要使用激活层来实现了。