[英]tf.py_func , custom tensorflow function getting applied to only the first element in the tensor
I am new to tensorflow and was playing around with a deep learning network. 我是tensorflow的新手,正在玩一个深度学习网络。 I wanted to do a custom rounding off on all the weights after each iteration.
我想在每次迭代后对所有权重进行自定义四舍五入。 As the round function in tensorflow library doesn't give you the option to round the values down to a certain number of decimal points.
由于tensorflow库中的舍入函数无法为您提供将值舍入到小数位数的选项。 So I wrote this
所以我写了这个
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
np_prec = lambda x: np.round(x,3).astype(np.float32)
def tf_prec(x,name=None):
with ops.name_scope( "d_spiky", name,[x]) as name:
y = tf.py_func(np_prec,
[x],
[tf.float32],
name=name,
stateful=False)
return y[0]
with tf.Session() as sess:
x = tf.constant([0.234567,0.712,1.2,1.7])
y = tf_prec(x)
y = tf_prec(x)
tf.global_variables_initializer
print(x.eval(), y.eval())
The output I got was this 我得到的输出是这个
[ 0.234567 0.71200001 1.20000005 1.70000005] [ 0.235 0.71200001 1.20000005 1.70000005]
So the custom rounding off worked only on the first item in the tensor and I am not sure about what I am doing wrong. 因此,自定义舍入仅在张量中的第一项上起作用,并且我不确定自己做错了什么。 Thanks in advance.
提前致谢。
The error here because of the following line, 由于以下行,此处出现错误,
np_prec = lambda x: np.round(x,3).astype(np.float32)
you are casting the output to np.float32 . 您正在将输出转换为np.float32 。 You can verify the error by the following code,
您可以通过以下代码验证错误,
print(np.round([0.234567,0.712,1.2,1.7], 3).astype(np.float32)) #prints [ 0.235 0.71200001 1.20000005 1.70000005]
The default output of np.round is float64 . np.round的默认输出是float64 。 Moreover, you also have to change the Tout argument in tf.py_func to float64 .
此外,还必须将tf.py_func中的Tout参数更改为float64 。
I have given the following code with the above fix and commented where necessary. 我已通过以下修复程序提供了以下代码,并在必要时进行了注释。
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
np_prec = lambda x: np.round(x,3)
def tf_prec(x,name=None):
with ops.name_scope( "d_spiky", name,[x]) as name:
y = tf.py_func(np_prec,
[x],
[tf.float64], #changed this line to tf.float64
name=name,
stateful=False)
return y[0]
with tf.Session() as sess:
x = tf.constant([0.234567,0.712,1.2,1.7],dtype=np.float64) #specify the input data type np.float64
y = tf_prec(x)
y = tf_prec(x)
tf.global_variables_initializer
print(x.eval(), y.eval())
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.