Skip to main content
 首页 » 编程设计

python之如何从张量中获取值

2025年01月19日10bjzhanghao

这是我的设置:

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。我想用 idx1 和 idx2 索引我的掩码,因为两者的计算结果都是整数。

但是 idx1 和 idx2 不是整数而是张量,所以 obj = objective(indices, weights) 调用会导致错误。

如何让代码工作?

请您参考如下方法:

您可以结合使用 tf.SparseTensor 和 tf.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]})) 

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