与Tensors比较--Python / TensorFlow

时间:2017-06-26 12:29:52

标签: python python-2.7 tensorflow

我有一个门槛:

threshold = tf.Variable(tf.zeros([1]))

我的 y ,我的 y 是一个张量,其结果是:

 [[  1.13162342e-02]
  [  6.52027056e-02]
  [  2.14621667e-02]
  [  1.38542265e-01]
  [  1.53827667e-02]
  [  4.87363040e-02]
  [  1.25984079e-04]
  [  1.36357039e-01]
  [  2.74352938e-01]
  [  2.11421549e-02]
  [  9.93497610e-01]
  [  8.08861554e-01]
  [  9.99999881e-01]
  [  9.98271227e-01]
  [  9.72766817e-01]
  [  8.13062727e-01]
  [  9.20997798e-01]
  [  9.00570035e-01]
  [  9.86454725e-01]
  [  8.39891076e-01]]

我需要进行以下比较:

if y > threshold:
    output = 1
else:
    output = 0

我需要输出的格式看起来像这样......

 [[  0]
  [  0]
  [  0]
  [  1]
  [  1]
  [  0]
  [  0]
  [  1]
  [  0]
  [  1]
  [  1]
  [  1]
  [  1]
  [  0]
  [  0]
  [  1]
  [  0]
  [  0]
  [  1]
  [  0]]

我这样做并收到以下错误消息:

Traceback (most recent call last):
    File "SLP_1.py", line 130, in <module>
        if y > threshold:
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 541, in __nonzero__
        raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

如何使用Tensorflow正确执行此操作?

P.S。:我正在使用:

import numpy as np
import tensorflow as tf

1 个答案:

答案 0 :(得分:1)

您应该使用tf.less将y与阈值进行比较。这将返回一个dtype bool的张量。如果你想要整数作为答案,你应该使用tf.cast

例如,

bool_result = tf.less(threshold, y)
int_result = tf.cast(bool_result, tf.int32)