tensorflow中自定义激活函数

一、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}

二、在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中可以自定义单独的激活函数。只要保证输入、输出是形状和元素数据类型一样就可以。

当然如果想定义复杂的激活函数,就需要使用激活层来实现了。

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值