2016-02-28 16 views
6

ho due incastri tensore A e B, che si presenta comereduce_sum da certa dimensione

[ 
    [1,1,1], 
    [1,1,1] 
] 

e

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

quello che voglio fare è calcolare la distanza L2 d(A,B) elemento-saggio.

Prima ho fatto un tf.square(tf.sub(lhs, rhs)) per ottenere

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

e poi voglio fare un elemento-saggio ridurre che restituisce

[ 
    3, 
    0 
] 

ma tf.reduce_sum non permette di ridurre il mio per riga. Qualsiasi input sarebbe apprezzato. Grazie.

risposta

9

aggiungere l'argomento reduction_indices con un valore di 1, ad es .:

tf.reduce_sum(tf.square(tf.sub(lhs, rhs)), 1) 

che dovrebbe produrre il risultato che stai cercando. Here is the documentation su reduce_sum().

3

Secondo TensorFlow documentation, reduce_sum, funzione che richiede quattro argomenti.

tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None). 

Ma reduction_indices è stato sconsigliato. Meglio usare l'asse al posto di Se l'asse non è impostato, riduce tutte le sue dimensioni.

A titolo di esempio, questo è preso dal documentation,

# 'x' is [[1, 1, 1] 
#   [1, 1, 1]] 
tf.reduce_sum(x) ==> 6 
tf.reduce_sum(x, 0) ==> [2, 2, 2] 
tf.reduce_sum(x, 1) ==> [3, 3] 
tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]] 
tf.reduce_sum(x, [0, 1]) ==> 6 

Sopra requisito può essere scritto in questo modo,

import numpy as np 
import tensorflow as tf 

a = np.array([[1,7,1],[1,1,1]]) 
b = np.array([[0,0,0],[1,1,1]]) 

xtr = tf.placeholder("float", [None, 3]) 
xte = tf.placeholder("float", [None, 3]) 

pred = tf.reduce_sum(tf.square(tf.subtract(xtr, xte)),1) 

# Initializing the variables 
init = tf.global_variables_initializer() 

# Launch the graph 
with tf.Session() as sess: 
    sess.run(init) 
    nn_index = sess.run(pred, feed_dict={xtr: a, xte: b}) 
    print nn_index 
Problemi correlati