小编xuh*_*hai的帖子

循环张量并将函数应用于每个元素

我想遍历一个包含 的张量Int,并将一个函数应用于每个元素。在函数中,每个元素都将从 python 的字典中获取值。我已经尝试了简单的方法 with tf.map_fn,它可以处理add函数,例如以下代码:

import tensorflow as tf

def trans_1(x):
    return x+10

a = tf.constant([1, 2, 3])
b = tf.map_fn(trans_1, a)
with tf.Session() as sess:
    res = sess.run(b)
    print(str(res))
# output: [11 12 13]
Run Code Online (Sandbox Code Playgroud)

但以下代码抛出KeyError: tf.Tensor'map_8/while/TensorArrayReadV3:0' shape=() dtype=int32异常:

import tensorflow as tf

kv_dict = {1:11, 2:12, 3:13}

def trans_2(x):
    return kv_dict[x]

a = tf.constant([1, 2, 3])
b = tf.map_fn(trans_2, a)
with tf.Session() as sess:
    res = sess.run(b)
    print(str(res))
Run Code Online (Sandbox Code Playgroud)

我的 tensorflow 版本是 …

python tensorflow tensor

5
推荐指数
1
解决办法
2010
查看次数

标签 统计

python ×1

tensor ×1

tensorflow ×1