[英]How can I implement a layer which can keep several decimal?
我想實現,在輸出層保留兩個十進制函數。 因為我想在兩個卷積層之間使用它,所以我想用它來實現這一目標。
但是由於它經常保留的兩位小數,我不知道如何解決?
import tensorflow as tf
input = tf.Variable([3.5115155, 3.365, 3.38115155, 3.81151536, 3.38115159, 3.38115158, 3.398115155], dtype=tf.float32)
@tf.custom_gradient
def round_test(x):
def grad(dy):
return 1.0*dy
return tf.math.round(x * 100)/100, grad
output_clip = round_test(input)
grad_clip = tf.gradients(output_clip, input)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print("input:", sess.run(input))
print("output_clipping:", sess.run(output_clip))
print("with clipping:", sess.run(grad_clip)[0])
這是個錯誤。
輸入:[3.5115156 3.365 3.3811514] output_clipping:[3.51 3.36 3.3799999]
我預計roud_test(3.3811514)
的輸出為3.38
,但實際輸出為3.3799999
我只想保留兩位小數。
嘗試tf.py_func
:
import numpy as np #add
return tf.py_func(lambda a:np.round(a,2),[x],tf.float32),grad
結果:
input: [3.5115156 3.365 3.3811514]
output_clipping: [3.51 3.36 3.38]
with clipping: [1. 1. 1.]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.