Tensorflow错误:不允许使用`tf.Tensor`作为Python`bool`

时间:2018-02-01 20:51:12

标签: tensorflow machine-learning deep-learning keras activation-function

我正在努力在Python中的TensorFlow中实现激活功能。

代码如下:

def myfunc(x):
    if (x > 0):
        return 1
    return 0

但我总是收到错误:

  

不允许使用tf.Tensor作为Python bool。使用if t is not None:

3 个答案:

答案 0 :(得分:9)

使用tf.cond

tf.cond(tf.greater(x, 0), lambda: 1, lambda: 0)

另一种解决方案,它还支持多维张量:

tf.sign(tf.maximum(x, 0))

但是请注意,这种激活的梯度到处都是零,所以神经网络不会用它来学习任何东西。

答案 1 :(得分:0)

当我尝试使用以下代码时遇到了类似的问题

if tf.math.equal(a,b):
    break

变量a和b是张量变量

我正在使用1.14版本的tensorflow,它给了我以下错误

Using a tf.Tensor as a Python bool is not allowed. Use if t is not None:

解决方案

if tf.math.equal(a,b) is not None:
   break

这对我有用。希望这对这里的人有帮助。

答案 2 :(得分:0)

在TF2中,您可以使用# === Method using plt.plot() directly ==== # --- generate data ----- data=[] for i in list(range(24)): data += [random()] # --- plot data ---- plt.xticks([0,4,8,12,16,20,23], ["00:00", "01:00", "02:00", "03:00", "04:00","05:00","6:00"]) # note that the final index is 23 not 24 plt.plot(data) # plt.plot() can be called either before or after plt.xticks() in this case plt.show() # === Method using plt.subplots() ==== # --- generate random data again to show its not the same plot ----- data=[] for i in list(range(24)): data += [random()] # --- plot data ---- fig,ax= plt.subplots(nrows=1, ncols=1) plt.xticks([0,4,8,12,16,20,23], ["00:00", "01:00", "02:00", "03:00", "04:00","05:00","6:00"]) #in this case .xticks cannot be called before .subplots() #use the below two lines and remove the line above if you have multiple subplots and want to set each subplot to have a different x-axis #ax.set_xticks([0,4,8,12,16,20,23]) #ax.set_xticklabels(["00:00", "01:00", "02:00", "03:00", "04:00","05:00","6:00"]) ax.plot(data) plt.show() 装饰函数myfunc()

@tf.function