2017-06-26 3 views
0

Ich habe eine Schwelle:Vergleich mit Tensoren - Python/TensorFlow

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

Und ich habe meine y, mein y ein Tensor und das Ergebnis ist:

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

I müssen folgenden Vergleich durchführen:

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

Ich brauche das Format meiner Ausgabe sollte in etwa so aussehen ...

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

ich das tat und bekam die folgende Fehlermeldung:

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. 

Wie soll ich dies tun, richtig mit Tensorflow ?

P. S .: Ich verwende:

import numpy as np 
import tensorflow as tf 

Antwort

1

Sie tf.less verwenden sollten, y mit einem Schwellenwert zu vergleichen. Dies gibt einen Tensor von dtype bool zurück. Wenn Sie Ganzzahlen als Antwort möchten, sollten Sie tf.cast verwenden.

Zum Beispiel

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

Es gibt nur 1, wenn es wie bool_result = tf.less (Schwelle, y) oder 0, wenn es wie diese bool_result = tf.less ist (y, Schwelle), das ist nicht das, was Ich brauche. – QuestionsOverflow

+0

das ist, weil Ihre Schwelle nur Nullen ist, und in Ihrem 'y' sind nur positive Zahlen ... –

+0

Ich habe – QuestionsOverflow