如何用一定的指数张量分割一维张量?

时间:2016-12-21 03:50:50

标签: tensorflow

有一个int32的1-D张量。我想在第一次出现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.

1 个答案:

答案 0 :(得分:1)

我自己得到了答案。

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]