使用字典映射Tensor值时报Tensor不可哈希TypeError错误如何解决
错误成因
你遇到的报错本质是TensorFlow计算图的执行逻辑和Python原生字典的使用规则冲突导致的:tf.map_fn默认会在计算图模式下运行传入的函数,函数体中的x在图构建阶段是符号化的张量占位符,并非实际运行时的具体数值。你写的int(x)不会在图构建阶段真的把张量转成Python整数,只会生成一个类型转换的张量节点,直接把这个张量对象传入Python字典做key查询时,因为张量本身不支持哈希操作,就触发了该报错。
解决方案
以下是3种不同场景下的可行解法,优先推荐第一种原生TensorFlow实现的方案,兼容性和性能最好:
- 方案1:使用TensorFlow原生哈希表
tf.lookup.StaticHashTable实现映射,支持图模式、eager模式,且支持批量查询无需循环,性能最高
import tensorflow as tf tensor1 = tf.cast([1,2,3], dtype=tf.int32) # 构造映射对应的键、值张量 keys = tf.constant([1, 2, 3], dtype=tf.int32) values = tf.constant([101, 102, 103], dtype=tf.int32) # 初始化静态哈希表,第二个参数为找不到对应key时的默认返回值 lookup_table = tf.lookup.StaticHashTable( tf.lookup.KeyValueTensorInitializer(keys, values), default_value=-1 ) # 直接批量查询得到结果张量 result = lookup_table.lookup(tensor1) print(result) # 输出:tf.Tensor([101 102 103], shape=(3,), dtype=int32)
- 方案2:如果必须使用
tf.map_fn实现逻辑,可以用tf.py_function包裹Python原生逻辑,强制函数在运行时(而非图构建时)执行,仅适合小规模数据使用,性能较低
import tensorflow as tf tensor1 = tf.cast([1,2,3], dtype=tf.int32) m = {1:101, 2:102, 3:103} def map_func(x): # 运行时x会有实际数值,可通过numpy()转成Python整数查字典 return m[int(x.numpy())] result = tf.map_fn( lambda x: tf.py_function(func=map_func, inp=[x], Tout=tf.int32), elems=tensor1, fn_output_signature=tf.int32 ) print(result)
- 方案3:如果是eager模式下处理小规模张量,直接转成numpy数组遍历处理后再转回张量,写法最简单
import tensorflow as tf tensor1 = tf.cast([1,2,3], dtype=tf.int32) m = {1:101, 2:102, 3:103} result = tf.constant([m[num] for num in tensor1.numpy()], dtype=tf.int32) print(result)
内容的提问来源于stack exchange,提问作者Andrei Pop
相关产品推荐
相关产品推荐

