溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用tensorflow怎么自定義激活函數(shù)

發(fā)布時間:2021-05-14 16:25:17 來源:億速云 閱讀:343 作者:Leah 欄目:開發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)使用tensorflow怎么自定義激活函數(shù),文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

首先要確定梯度函數(shù),之后將其處理為tf能接受的類型。

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

2.2 定義該激活函數(shù)的一次梯度函數(shù)

def square_grad(x):
 return 2 * x

2.3 讓numpy數(shù)組每一個元素都能應(yīng)用該函數(shù)(全局)

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

2.4 轉(zhuǎn)為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版的梯度函數(shù)

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 定義函數(shù)

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 定義梯度,該函數(shù)依靠上一個函數(shù)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函數(shù)

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.使用

跟用其他激活函數(shù)一樣,直接用就行了。input_data:輸入數(shù)據(jù)。

h = square_tf(input_data)

上述就是小編為大家分享的使用tensorflow怎么自定義激活函數(shù)了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI