python - tensorflow 中的等效列表理解

标签 python tensorflow list-comprehension tensor

如何使用字典将包含 N int 的 1 阶张量修改为包含 N 大小为 M 的向量的 2 阶张量

在Python中类似:

dict = {1 : [1,2,3] , 2 : [3,2,1]}
array1 = np.array([1,1,2,1,2])
array2 = np.array([dict[x] for x in array1])

但我无法迭代张量(除了 while 循环,但我不认为这是最佳解决方案)

最佳答案

如果你的字典是这样的

dict = {1: tf.constant([1, 2, 3]), 2: tf.constant([1, 2, 3])}
tensor1 = tf.constant([1, 1, 2, 1, 2])

那么像这样的事情应该可以完成工作:

vals = [dict[tensor1[k]] for k in range(tensor1.get_shape().as_list()[0])]
tensor2 = tf.stack(vals, axis=0)

如果尺寸未知,事情会变得更加复杂。例如,如果 tensor1 的形状未知,我看不到不涉及 tf.while_loop 的解决方案。

关于python - tensorflow 中的等效列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44284477/

相关文章:

python - Keras模型只能预测一个类

python - tensorflow 中的单神经元前馈网络

python - 在 TensorFlow 中使用预训练的词嵌入(word2vec 或 Glove)

Python 嵌套列表理解来计算列表中相同字符串的出现次数

python - 创建字节范围(用于请求部分数据)

python - 使用长正则表达式公式进行自由文本解析导致错误 : multiple repeat in python? 包含屏幕截图

python .count 用于多维数组(列表列表)

tensorflow - 如何向 tf.data.Dataset 对象添加新的特征列?

python - 将大写字母移动到字符串前面并将小写字母大写的函数?

python - python 对象列表,每个对象都有自己的数组字典。附加到一个附加到所有