Python 取一个张量的元素,它在另一个张量的内部
我有两个张量,我必须迭代第一个,只取另一个张量内的元素。Python 取一个张量的元素,它在另一个张量的内部,python,tensorflow,Python,Tensorflow,我有两个张量,我必须迭代第一个,只取另一个张量内的元素。t2中只有一个元素也在t1中。这里有一个例子 t1 = tf.where(values > 0) # I get some indices example [6, 0], [3, 0] t2 = tf.where(values2 > 0) # I get [4, 0], [3, 0] t3 = .... # [3, 0] 我尝试使用.eval()对它们进行求值和迭代,并使用中的运算符检查t2的元素是否在t1中,但不起作用。T
t2
中只有一个元素也在t1
中。这里有一个例子
t1 = tf.where(values > 0) # I get some indices example [6, 0], [3, 0]
t2 = tf.where(values2 > 0) # I get [4, 0], [3, 0]
t3 = .... # [3, 0]
我尝试使用
.eval()
对它们进行求值和迭代,并使用中的运算符检查t2
的元素是否在t1
中,但不起作用。TensorFlow有没有一个函数可以做到这一点
编辑
for index in xrange(max_indices):
indices = tf.where(tf.equal(values, (index + 1))).eval() # indices: [[1 0]\n [4 0]\n [9 0]]
cent_indices = tf.where(centers > 0).eval() # cent_indices: [[6 0]\n [9 0]]
indices_list.append(indices)
for cent in cent_indices:
if cent in indices:
centers_list.append(cent)
break
第一次迭代cent
的值为[6 0]
,但它进入if
条件
回答
for index in xrange(max_indices):
indices = tf.where(tf.equal(values, (index + 1))).eval()
cent_indices = tf.where(centers > 0).eval()
indices_list.append(indices)
for cent in cent_indices:
# batch_item is an iterator from an outer loop
if values[batch_item, cent[0]].eval() == (index + 1):
centers_list.append(tf.constant(cent))
break
该解决方案与我的任务相关,但如果您正在寻找一维张量的解决方案,我建议您查看一下tf.sets.set\u交叉点
这就是您想要的吗?我只使用了这两个测试用例
x = tf.constant([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 1]])
y = tf.constant([[1, 2, 3, 4, 3, 6], [1, 2, 3, 4, 5, 1]])
# x = tf.constant([[1, 2], [4, 5], [7, 7]])
# y = tf.constant([[7, 7], [3, 5]])
def match(xiterations, yiterations, yvalues, xvalues ):
for i in range(xiterations):
for j in range(yiterations):
if (np.array_equal(yvalues[j], xvalues[i])):
print( yvalues[j])
with tf.Session() as sess:
xindex = tf.where( x > 4 )
yindex = tf.where( y > 4 )
xvalues = xindex.eval()
yvalues = yindex.eval()
xiterations = tf.shape(xvalues)[0].eval()
yiterations = tf.shape(yvalues)[0].eval()
print(tf.shape(xvalues)[0].eval())
print(tf.shape(yvalues)[0].eval())
if tf.shape(xvalues)[0].eval() >= tf.shape(yvalues)[0].eval():
match( xiterations, yiterations, yvalues, xvalues)
else:
match( yiterations, xiterations, xvalues, yvalues)
In是一个运算符,而不是内置的“我尝试使用.eval()对它们进行求值和迭代,并使用内置的In检查t2的元素是否在t1中,但不起作用”。发布代码并显示错误。你能澄清一下你的例子吗?我将从一个张量中获取一些值的索引,从另一个张量中获取其他索引,然后我必须从第二个张量中获取所有索引,而不是第一个张量中的索引。我将尝试,谢谢。如果两个张量的长度不同,你认为它也有效吗?在我的示例中,一个长度为3,一个长度为2,使用这些x=tf.constant([[1,2],[4,5],[7,7]])
y=tf.constant([[7,7],[3,5]])
和我的例子一样,我得到了tensorflow.python.framework.errors\u impact.InvalidArgumentError:期望开始、结束和跨步是1D大小相等的张量,但得到了形状[1,0]、[1]和[1]相反
我用另一种方法解决了问题,但是,感谢您的时间,您也可以编辑答案或发布另一个答案,以便对其他人有用。