我在tensorflow中编写了以下代码,这是一个函数,我将使用它根据输入的X值进行一些计算
import tensorflow as tf
import math as m
def tf_fn(x):
pi = tf.constant(m.pi)
miu=0.0
o=1.0
f1=1/(tf.sqrt(2*o**2*pi))
f2= tf.exp(-((x - miu)**2)/ 2*o**2)
f3= f1 * f2
return (f3)
x = np.array([0,1,2,3])
tf.print(tf_fn(x))
当我尝试打印这个时,我得到以下错误:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-70-fba9acd28831> in <module>()
1 x = np.array([0,1,2,3])
----> 2 tf.print(tf_fn(x))
7 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)
InvalidArgumentError: cannot compute Mul as input #1(zero-based) was expected to be a float
tensor but is a double tensor [Op:Mul]
我的预期输出是:[0.39894228,0.24197072,0.05399097,0.00443185]我知道问题是numpy数组需要被转换成张量。怎样才能得到预期的输出呢?多谢! !* *
在创建数组时指定要使用float32
而不是int64
。Numpy默认为64位类型,但TensorFlow使用float32
进行大多数计算。
x = np.array([0,1,2,3], np.float32)
应该能解决你的问题。
>>> x = np.array([0,1,2,3], np.float32)
>>> tf_fn(x)
[0.398942292 0.241970733 0.0539909676 0.00443184841]