简体   繁体   English

如何在张量流中定义条件语句?

[英]how to define condition statement in tensorflow?

I have three functions in file fe_extraction.py 我在文件fe_extraction.py中具有三个功能

def rms_value(x):
    return tf.sqrt(tf.reduce_mean(tf.square(x)))
def meanabs(x):
    return tf.reduce_mean(tf.abs(x))

def req_value(x,y,Thersh):
    z = tf.cond(y>Thersh,rms_freq(x),peak_value(x))
return z

I want to simply apply a condition if y > thershold perform rms_freq(x) or else peak_value(x) and return that value. 如果y> thershold执行rms_freq(x)或peak_value(x)并返回该值,我想简单地应用一个条件。 y is the value obtained from another function. y是从另一个函数获得的值。

# given values
# Thershold = 10.69 
# x is defined as tf.Variable , dtype tf.float64
# y = 45.34 obtained from function
....
z = fe_extraction.req_value(x,y,Thershold)

I get error as TypeError:fn1 must be callable. 我收到错误,因为TypeError:fn1必须是可调用的。

With rms_freq(x) and peak_value(x) you're calling the function rms_freq and peak_value respectively, passing x as argument. 使用rms_freq(x)peak_value(x)您分别调用函数rms_freqpeak_value ,并传递x作为参数。

Instead, you have to pass a callable or, in other words, a function, that tf.cond can execute. 相反,您必须传递tf.cond可以执行的可调用函数或换句话说,就是函数。

Since you want x as a parameter for your functions, you can wrap them in a lambda that defines a callable object that captures the outside scope and thus sees the parameter x . 由于希望将x作为函数的参数,因此可以将它们包装在lambda ,该lambda定义可调用对象,该对象可捕获外部作用域并因此看到参数x

z = tf.cond(y>Thersh,lambda: rms_freq(x) ,lambda: peak_value(x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM