TensorFlow目标检测session.run报错:TypeError: unhashable type: 'list'
解决TensorFlow sess.run中TypeError: unhashable type: 'list'的问题
这个错误其实很好定位——你在给sess.run()传feed_dict的时候犯了一个小错误:把列表当成了字典的键。
先看你的代码里的问题点:
_input = [graph.get_tensor_by_name(tensor_name) for tensor_name in input_tensors] # 然后你这么用: sess.run(_output_ops, feed_dict={_input: image_expanded})
这里_input是一个列表(哪怕里面只有一个张量),而Python字典的键必须是可哈希的类型(比如字符串、张量对象这种),列表是不可哈希的,所以直接触发了TypeError。
解决方法
因为你的输入张量只有一个,所以有两种简单的修复方式:
方式1:直接定义单个输入张量(推荐)
既然input_tensors里只有一个元素,没必要用列表来存,直接把_input定义成单个张量对象:
input_tensor = "import/image_tensor:0" output_tensors=['import/detection_boxes:0', 'import/detection_scores:0', 'import/detection_classes:0', 'import/num_detections:0'] _input = graph.get_tensor_by_name(input_tensor) # 这里不再是列表 _output_ops = [graph.get_tensor_by_name(tensor_name) for tensor_name in output_tensors] sess = tf.Session(graph=graph, config=_config_proto) image_expanded = 符合模型尺寸的numpy数组(1, 512, 512, 1) (boxes, scores, classes, num_detections) = sess.run(_output_ops, feed_dict={_input: image_expanded})
方式2:保留列表,取列表中的单个张量作为键
如果后续可能需要扩展多个输入,不想修改_input的列表形式,那就直接取列表的第一个元素作为feed_dict的键:
input_tensors=["import/image_tensor:0"] output_tensors=['import/detection_boxes:0', 'import/detection_scores:0', 'import/detection_classes:0', 'import/num_detections:0'] _input = [graph.get_tensor_by_name(tensor_name) for tensor_name in input_tensors] _output_ops = [graph.get_tensor_by_name(tensor_name) for tensor_name in output_tensors] sess = tf.Session(graph=graph, config=_config_proto) image_expanded = 符合模型尺寸的numpy数组(1, 512, 512, 1) # 用_input[0]作为键,而不是整个列表 (boxes, scores, classes, num_detections) = sess.run(_output_ops, feed_dict={_input[0]: image_expanded})
额外提醒
如果以后你的模型有多个输入张量,feed_dict的格式应该是{张量1: 对应数据1, 张量2: 对应数据2, ...},每个键都必须是单独的张量对象,绝对不能把多个张量的列表作为键哦。
内容的提问来源于stack exchange,提问作者Shaik Ahmad
相关产品推荐
相关产品推荐

