2016-12-21 47 views
-1

有一个int32的1维张量。我想在第一次出现1之前用0代替元素。如何用一定的索引张量来分割一维张量?

#This is a numpy equivalent. 
import numpy as np 
a = np.array([5, 4, 1, 3, 1, 2, 3, 3, 1, 5], np.int32) 
first_ind = np.where(a == 1)[0][0] # => 2 
result = np.concatenate((np.zeros((first_ind,)), a[first_ind:])) 
# =>[ 0. 0. 1. 3. 1. 2. 3. 3. 1. 5.] 

import tensorflow as tf 
_a = tf.convert_to_tensor(a) 
_first_ind = tf.where(tf.equal(_a, 1))[0][0] 
# But I don't know what to do next. 

回答

0

我自己得到了答案。

import numpy as np 
a = np.array([5, 4, 1, 3, 1, 2, 3, 3, 1, 5], np.int32) 
first_ind = np.where(a == 1)[0][0] # => 2 
result = np.concatenate((np.zeros((first_ind,)), a[first_ind:])) 
# =>[ 0. 0. 1. 3. 1. 2. 3. 3. 1. 5.] 

import tensorflow as tf 
_a = tf.convert_to_tensor(a) 
_first_ind = tf.where(tf.equal(_a, 1))[0] 

zero_padding = tf.zeros(tf.to_int32(_first_ind), tf.int32) 
_a_back = tf.slice(_a, _first_ind, [-1]) 
out = tf.concat(0, (zero_padding, _a_back)) 
with tf.Session() as sess: 
    print out.eval() 
    #=> [0 0 1 3 1 2 3 3 1 5] 
相关问题