如何从张量中获取值

时间:2018-03-12 00:29:41

标签: python tensorflow

这是我的设置:

indices = tf.placeholder(tf.int32, shape=[2])
weights = tf.Variable(tf.random_normal([100000, 3], stddev=0.35))

def objective(indices, weights):
    idx1 = indices[0]; idx2 = indices[1] #extract two indices
    mask = np.zeros(weights.shape.as_list()[0]) #builds a mask for some tensor "weights"
    mask[idx1] = 1 # don't ask why I want to do this. I just do.
    mask[idx2] = 1
    obj = tf.reduce_sum(tf.multiply(weights[idx1], weights[idx2]))
    return obj

optimizer = tf.train.GradientDescentOptimizer(0.01)

obj = objective(indices, weights)
trainer = optimizer.minimize(obj)


with tf.Session() as sess:
   sess.run(tf.global_variables_initializer())
   sess.run([trainer, obj], feed_dict={indices=[100, 1000]})

所以关键是我有一些张量,我拿出一片与我mask中的索引相对应的片段。该索引是tf.strided_slice。我希望使用idx1idx2为我的模板编制索引,因为它们都评估为整数。

idx1idx2不是整数,而是张量,因此obj = objective(indices, weights)调用会导致错误。

如何让代码生效?

1 个答案:

答案 0 :(得分:1)

您可以使用tf.SparseTensortf.sparse_tensor_to_dense的组合来实现您的目标:

import numpy as np
import tensorflow as tf

indices = tf.placeholder(tf.int64, shape=[2])
weights = tf.Variable(tf.random_normal([5, 3], stddev=0.35))

def objective(indices, weights):
     idx1 = indices[0]; idx2 = indices[1] #extract two indices
     mask = np.zeros(weights.shape.as_list()[0]) #builds a mask for some tensor "weights"
     mask_ones = tf.SparseTensor(tf.reshape(indices, [-1,1]), [1, 1], mask.shape) # Stores the 1s used in the mask
     mask = mask + tf.sparse_tensor_to_dense(mask_ones) # Set the mask
     obj = tf.reduce_sum(tf.multiply(weights[idx1], weights[idx2]))
     return obj, mask

obj, mask = objective(indices, weights)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run([weights, obj, mask], feed_dict={indices:[0, 4]}))

[array([[...]], dtype=float32), 0.0068909675, array([1., 0., 0., 0., 1.], dtype=int32)]