'无法将feed_dict key解释为张量:'+e.args[0])

2024-03-28 18:13:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我用这个code重新训练了模型。然后在克隆之后遵循来自这个repo的指令。替换新生成的标签.txt图形.pb文件。当发布一张图片用下面的代码分类时

MAX_K = 10

TF_GRAPH = "{base_path}/inception_model/graph.pb".format(
    base_path=os.path.abspath(os.path.dirname(__file__)))
TF_LABELS = "{base_path}/inception_model/labels.txt".format(
    base_path=os.path.abspath(os.path.dirname(__file__)))


def load_graph():
    sess = tf.Session()
    with tf.gfile.FastGFile(TF_GRAPH, 'rb') as tf_graph:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(tf_graph.read())
        tf.import_graph_def(graph_def, name='')
    label_lines = [line.rstrip() for line in tf.gfile.GFile(TF_LABELS)]
    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
    return sess, softmax_tensor, label_lines


SESS, GRAPH_TENSOR, LABELS = load_graph()


@csrf_exempt
def classify_api(request):
    data = {"success": False}

    if request.method == "POST":
        tmp_f = NamedTemporaryFile()

    if request.FILES.get("image", None) is not None:
        image_request = request.FILES["image"]
        image_bytes = image_request.read()
        image = Image.open(io.BytesIO(image_bytes))
        image.save(tmp_f, image.format)
    elif request.POST.get("image64", None) is not None:
        base64_data = request.POST.get("image64", None).split(',', 1)[1]
        plain_data = b64decode(base64_data)
        tmp_f.write(plain_data)

    classify_result = tf_classify(tmp_f, int(request.POST.get('k', MAX_K)))
    tmp_f.close()

    if classify_result:
        data["success"] = True
        data["confidence"] = {}
        for res in classify_result:
            data["confidence"][res[0]] = float(res[1])

return JsonResponse(data)


def tf_classify(image_file, k=MAX_K):
    result = list()

    image_data = tf.gfile.FastGFile(image_file.name, 'rb').read()

    predictions = SESS.run(GRAPH_TENSOR, {'DecodeJpeg/contents:0': image_data})
    predictions = predictions[0][:len(LABELS)]
    top_k = predictions.argsort()[-k:][::-1]
    for node_id in top_k:
        label_string = LABELS[node_id]
        score = predictions[node_id]
        result.append([label_string, score])

    return result

然后显示以下错误。在

TypeError:无法将feed_dict key解释为张量:名称'DecodeJpeg'/内容:0'是指不存在的张量。图形中不存在“DecodeJpeg/contents”操作。


Tags: pathimagenonedatagetlabelsrequesttf
1条回答
网友
1楼 · 发布于 2024-03-28 18:13:39

你的问题就在这条线上:

predictions = SESS.run(GRAPH_TENSOR, {'DecodeJpeg/contents:0': image_data})

feed_dict字典中的键应该是张量,而不是字符串。您可以先按名称查找张量:

^{pr2}$

相关问题 更多 >