使用tensorflow怎么自定义激活函数

发布时间:2021-05-14 16:25:17 作者:Leah
来源:亿速云 阅读:336

这期内容当中小编将会给大家带来有关使用tensorflow怎么自定义激活函数,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

首先要确定梯度函数,之后将其处理为tf能接受的类型。

def square(x):
 return pow(x, 2)

2.2 定义该激活函数的一次梯度函数

def square_grad(x):
 return 2 * x

2.3 让numpy数组每一个元素都能应用该函数(全局)

square_np = np.vectorize(square)
square_grad_np = np.vectorize(square_grad)

2.4 转为tf可用的32位float型,numpy默认是64位(全局)

square_np_32 = lambda x: square_np(x).astype(np.float32)
square_grad_np_32 = lambda x: square_grad_np(x).astype(np.float32)

2.5 定义tf版的梯度函数

def square_grad_tf(x, name=None):
 with ops.name_scope(name, "square_grad_tf", [x]) as name:
 y = tf.py_func(square_grad_np_32, [x], [tf.float32], name=name, stateful=False)
 return y[0]

2.6 定义函数

def my_py_func(func, inp, Tout, stateful=False, name=None, my_grad_func=None):
 # need to generate a unique name to avoid duplicates:
 random_name = "PyFuncGrad" + str(np.random.randint(0, 1E+8))
 tf.RegisterGradient(random_name)(my_grad_func)
 g = tf.get_default_graph()
 with g.gradient_override_map({"PyFunc": random_name, "PyFuncStateless": random_name}):
 return tf.py_func(func, inp, Tout, stateful=stateful, name=name)

2.7 定义梯度,该函数依靠上一个函数my_py_func计算并传播

def _square_grad(op, pred_grad):
 x = op.inputs[0]
 cur_grad = square_grad(x)
 next_grad = pred_grad * cur_grad
 return next_grad

2.8 定义tf版的square函数

def square_tf(x, name=None):
 with ops.name_scope(name, "square_tf", [x]) as name:
 y = my_py_func(square_np_32,
   [x],
   [tf.float32],
   stateful=False,
   name=name,
   my_grad_func=_square_grad)
 return y[0]

3.使用

跟用其他激活函数一样,直接用就行了。input_data:输入数据。

h = square_tf(input_data)

上述就是小编为大家分享的使用tensorflow怎么自定义激活函数了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. TensorFlow怎么使用Graph
  2. 使用tensorflow怎么自定义损失函数

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

tensorflow

上一篇:Python中递归函数的原理是什么

下一篇:如何在Python中使用函数生成器

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》