[英]How can I implement a layer which can keep several decimal?
I want to achieve, in the output layer to retain two decimal functions. 我想实现,在输出层保留两个十进制函数。 Because I want to use it between two convolution layers, so I want to use it to achieve this.
因为我想在两个卷积层之间使用它,所以我想用它来实现这一目标。
But because the two decimals it keeps often overflow, I don't know how to solve it? 但是由于它经常保留的两位小数,我不知道如何解决?
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])
This is a mistake. 这是个错误。
input: [3.5115156 3.365 3.3811514] output_clipping: [3.51 3.36 3.3799999] 输入:[3.5115156 3.365 3.3811514] output_clipping:[3.51 3.36 3.3799999]
I expect the output of roud_test(3.3811514)
to be 3.38
, but the actual output is 3.3799999
我预计
roud_test(3.3811514)
的输出为3.38
,但实际输出为3.3799999
I just want to keep two decimal places. 我只想保留两位小数。
Try tf.py_func
: 尝试
tf.py_func
:
import numpy as np #add
return tf.py_func(lambda a:np.round(a,2),[x],tf.float32),grad
The results: 结果:
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.