当前位置: 首页 > 知识库问答 >
问题:

Tensorflow服务于预先训练的Keras ResNet50模型,返回总是相同的预测

别宏盛
2023-03-14

我使用以下代码将预先训练的ResNet50 keras模型导出到tensorflow中,以便为tensorflow提供服务:

import tensorflow as tf
sess = tf.Session()
from keras import backend as K
K.set_session(sess)
K.set_learning_phase(0)

# Modelo resnet con pesos entrenados en imagenet
from keras.applications.resnet50 import ResNet50
model = ResNet50(weights='imagenet')

# exportar en tensorflow
import os
version_number = max([ int(x) for x in os.listdir('./resnet-classifier') ]) + 1
export_path = './resnet-classifier/{}'.format(version_number)
with tf.keras.backend.get_session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    tf.saved_model.simple_save(sess, export_path,
            inputs=dict(input_image=model.input),
            outputs={t.name:t for t in model.outputs}
    )
docker run -p 8501:8501 \
  -v ./resnet-classifier:/models/resnet-classifier \
  -e MODEL_NAME=resnet-classifier -e MODEL_BASE_PATH=/models \
  -t tensorflow/serving

最后,我使用以下函数对tensorflow服务进行预测:

def imagepath_to_tfserving_payload(img_path):
    import numpy as np
    from keras.preprocessing import image
    from keras.applications.resnet50 import preprocess_input
    img = image.img_to_array(image.load_img(img_path, target_size=(224, 224)))
    X = np.expand_dims(img, axis=0).astype('float32')
    X = preprocess_input(X)
    payload = dict(instances=X.tolist())
    payload = json.dumps(payload)
    return payload

def tfserving_predict(image_payload, url=None):
    import requests
    if url is None:
        url = 'http://localhost:8501/v1/models/resnet-classifier:predict'
    r = requests.post(url, data=image_payload)
    pred_json = json.loads(r.content.decode('utf-8'))
    from keras.applications.resnet50 import decode_predictions
    predictions = decode_predictions(np.asarray(pred_json['predictions']), top=3)[0]
    return predictions

然后,我从一个ipython shell中使用上面的两个函数从ImageNet的val集中选择随机的imagenes,我已经在本地存储了这些ImageNet。问题是tensorflow服务总是为我发送的所有图像返回相同的预测。

每次用上面的第一个脚本导出模型时,我得到的类略有不同,第一个类的可信度为“1”,其他类的可信度为“0”,例如:

# Serialization 1, in ./resnet-classifier/1 always returning:
[
  [
    "n07745940",
    "strawberry",
    1.0
  ],
  [
    "n02104029",
    "kuvasz",
    1.4013e-36
  ],
  [
    "n15075141",
    "toilet_tissue",
    0.0
  ]
]

# Serialization 2, in ./resnet-classifier/2 always returning:
[
  [
    "n01530575",
    "brambling",
    1.0
  ],
  [
    "n15075141",
    "toilet_tissue",
    0.0
  ],
  [
    "n02319095",
    "sea_urchin",
    0.0
  ]
]

共有1个答案

黄锋
2023-03-14

我发现调用sess.run(tf.global_variables_initializer())会覆盖预先训练的权重,可以在http://zachmoshe.com/2017/11/11/use-keras-models-with-tf.html找到线索。

对我来说,解决方案非常简单,只需将原始问题中的第一个代码块修改如下,在模型实例化/权重加载之前调用tf.global_variables_initializer():

import tensorflow as tf
sess = tf.Session()
sess.run(tf.global_variables_initializer())

from keras import backend as K
K.set_session(sess)
K.set_learning_phase(0)

# Modelo resnet con pesos entrenados en imagenet
from keras.applications.resnet50 import ResNet50
model = ResNet50(weights='imagenet')

# exportar en tensorflow
import os
versions = [ int(x) for x in os.listdir('./resnet-classifier') ]
version_number = max(versions) + 1 if versions else 1
export_path = './resnet-classifier/{}'.format(version_number)

tf.saved_model.simple_save(sess, export_path,
        inputs=dict(input_image=model.input),
        outputs={t.name:t for t in model.outputs}
)
 类似资料:
  • 因此,我在TensorFlow 2中使用tf.keras框架重新训练了一个预先训练的ResNet50 V2模型,在顶部添加了两个密集层。现在我想在基本ResNet模型中可视化层中的权重。但是,重新加载保存的模型 导致 如您所见,ResNet模型的层没有单独列出,这意味着调用 只会导致 因此,如何访问基本ResNet50 V2模型中每个层内部的权重?

  • 问题内容: 我一直在尝试使用Google发布的经过预先训练的inception_resnet_v2模型。我正在使用他们的模型定义(https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py)和给定的检查点(http://download.tensorflow.org/models/incepti

  • 我们在转换预应变张量流模型时遇到问题,我们将该模型作为以下文件 snapshot_140.ckpt.index snapshot_140.ckpt.meta snapshot_140.ckpt.data-00000-of-00001 当我们使用转换后的tflie文件进行预测时,所有的预测在加载正常的张量流模型时都给出了正确的回归预测 我们得到了上面的这些文件,从ckpt文件到张量流.pb图的转换是

  • 我已经在AWS SageMaker上使用内置算法语义分割训练了一个模型。这个名为model.tar.gz的训练模型存储在S3上。所以我想从S3下载这个文件,然后使用它在我的本地电脑上进行推断,而不使用AWS SageMaker。 以下是三个文件: > :包括网络架构、数据输入和训练的参数。请参阅语义分割超参数。 我的代码: 错误:

  • TensorFlow-Lite Android演示与它提供的原始模型mobileNet_quant_v1_224.tflite一起工作。参见:https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/lite 他们还在这里提供了其他预训练的lite模型:https://github.com/tensorflow/

  • 本文向大家介绍Keras使用ImageNet上预训练的模型方式,包括了Keras使用ImageNet上预训练的模型方式的使用技巧和注意事项,需要的朋友参考一下 我就废话不多说了,大家还是直接看代码吧! 在以上代码中,我们首先import各种模型对应的module,然后load模型,并用ImageNet的参数初始化模型的参数。 如果不想使用ImageNet上预训练到的权重初始话模型,可以将各语句的中