gpt4 book ai didi

python - 如何在 Tensorflow 中将张量读取为 numpy 数组或列表?

转载 作者:太空宇宙 更新时间:2023-11-03 20:31:14 28 4
gpt4 key购买 nike

我有一个张量 x,

x={Tensor} Tensor("Cast:0", shape=(?,3), dtype=int32)

现在,我需要迭代该张量批处理的每个三元组(假设三元组是 (a,b,c))并获取其中的第一个元素(在本例中为 a)。

然后,我需要获取数据集 Y(如下)中也以“a”作为第一个元素的所有其他三元组。

最终,我希望返回以“a”作为第一个元素的所有三元组,不包括相关的三元组(即在本例中,不包括 (a,b,c))。

我之前也使用过同样的方法,假设 x 是一个列表。

因此,就列表操作而言:

t=list({triple for x in x_to_score for triple in self.d[x[0]]} - set(x_to_score.eval()))

其中 d 是一个字典,包含按第一个元素分组的所有三元组的列表。例如:

对于

    Y=np.array([['a', 'y', 'b'],
['b', 'y', 'a'],
['a', 'y', 'c'],
['c', 'y', 'a'],
['a', 'y', 'd'],
['c', 'y', 'd'],
['b', 'y', 'c'],
['f', 'y', 'e']])

d={'f': [('f', 'y', 'e')],
'c': [('c', 'y', 'a'), ('c', 'y', 'd')],
'a': [('a', 'y', 'b'), ('a', 'y', 'c'), ('a', 'y', 'd')],
'b': [('b', 'y', 'a'), ('b', 'y', 'c')]}

但是,我是 tensorflow 新手,找不到将这些操作转换为张量的方法。对于每个评估的三元组,结果也应该是 [?,3] 的顺序。

请注意,必须禁用急切执行。

欢迎任何帮助!

编辑:如果输入张量 x=(a,y,d)(请注意,这可以是批处理,因此 x=[(a,y,d),(b,y,c)] 等),则预期输出将是:

[('a', 'y', 'b'), ('a', 'y', 'c')]

最佳答案

对此的一种可能的解决方案是计算数组结果,其中一个包含所有输入的串联匹配,另一个指示它所引用的输入的索引。它可以像这样工作:

import tensorflow as tf

X = tf.placeholder(tf.string, [None, 3])
Y = tf.constant([
['a', 'y', 'b'],
['b', 'y', 'a'],
['a', 'y', 'c'],
['c', 'y', 'a'],
['a', 'y', 'd'],
['c', 'y', 'd'],
['b', 'y', 'c'],
['f', 'y', 'e']
])
# Compare every input to every data
cmp = tf.equal(tf.expand_dims(X, 1), Y)
# Triples matching the first element
first_match = cmp[:, :, 0]
# Triples matching all elements
all_match = tf.reduce_all(cmp, axis=2)
# Triple matching the first element but not all elements
matches = first_match & (~all_match)
# Find indices
match_idx = tf.where(matches)
# Index of the input triple each result refers to
match_x = match_idx[:, 0]
# Concatenated resulting triples
match_y = tf.gather(Y, match_idx[:, 1])
# Test
with tf.Graph().as_default(), tf.Session() as sess:
x_val = [['a', 'y', 'd'], ['b', 'y', 'c']]
match_x_val, match_y_val = sess.run((match_x, match_y), feed_dict={X: x_val})
print(*zip(match_x_val, match_y_val), sep='\n')

输出:

(0, array([b'a', b'y', b'b'], dtype=object))
(0, array([b'a', b'y', b'c'], dtype=object))
(1, array([b'b', b'y', b'a'], dtype=object))

关于python - 如何在 Tensorflow 中将张量读取为 numpy 数组或列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57494855/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com