2017-06-26 116 views
0

我有一個門檻:比較與張量 - 的Python/TensorFlow

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

我有我的Ÿ,我ÿ是張量和它的結果是:

[[ 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

您應該使用tf.less爲y與閾值進行比較。這將返回dtype bool的張量。如果你想整數作爲答案,你應該使用tf.cast

例如,

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

它,只有當它像bool_result = tf.less(閾值,Y)或0,如果是這樣的bool_result = tf.less(Y,閾值),這不是什麼返回1我需要。 – QuestionsOverflow

+0

這是因爲你的閾值全是零,而你的'y'只有正數...... –

+0

我不明白 – QuestionsOverflow