【发布时间】:2021-08-13 19:49:02
【问题描述】:
我正在尝试编写以下函数:
我已经使用 numpy 在 python 中实现了它,但需要将其重新编码为 tensorflow:
input_array = np.array([0.2, 2.1, 4.5, 6.7, 8.1, 10.0])
def f_funct(input_array):
arr = np.ones(len(input_array))
delta_vec = np.multiply(arr,6.0/29.0)
res = np.where(input_array>np.power(delta_vec,3), np.cbrt(input_array),
input_array/(3*np.power(delta_vec,2)) + 4.0/29.0)
return res
print(f_funct(input_array))
我试过了:
# convert input from np.array to tensor
def np_array_to_tensor(input_array):
input_array = tf.convert_to_tensor(input_array, dtype=tf.float64)
return input_array
input_tensor = np_array_to_tensor(tf.constant(input_array))
arr = tf.ones([tf.size(input_tensor)], tf.float64)
delta_vec = tf.math.multiply(arr,tf.math.divide(6.0,29.0))
res1 = tf.math.divide(4.0,29.0)
res2 = tf.divide(input_tensor,(3*tf.pow(delta_vec,2)))
res = tf.cond(input_tensor>tf.pow(delta_vec,3),
lambda: tf.pow(input_tensor,1.0/3.0),
lambda: tf.add(res2,res1))
with tf.Session() as sess:
print(input_tensor.eval())
print(arr.eval())
print(delta_vec.eval())
print(res1)
print(res2.eval())
print(res.eval())
但这会引发错误,因为条件只能使用标量。
ValueError: Shape must be rank 0 but is rank 1 for 'cond_13/Switch' (op: 'Switch') with input shapes: [6], [6].
由于我的输入数组相当大,我宁愿坚持使用数组/张量。是否可以使用基于条件的张量来做到这一点?
如果有任何建议,我将不胜感激。谢谢。
【问题讨论】:
-
@Lescurel 谢谢。我已经修好了。
标签: arrays numpy tensorflow conditional-statements