Compilar el modelo de Keras

Este artículo está traducido del documento en inglés Compile Keras Models

El autor es Yuwei Hu

Se puede acceder a más documentos chinos de TVM → Estación china de TVM .

Este artículo describe cómo implementar un modelo de Keras con Relay.

Primero instale Keras y TensorFlow, que se pueden instalar rápidamente a través de pip:

pip install -U keras --user
pip install -U tensorflow --user

O consulte el sitio web oficial: https://keras.io/#installation

import tvm
from tvm import te
import tvm.relay as relay
from tvm.contrib.download import download_testdata
import keras
import tensorflow as tf
import numpy as np

Cargue un modelo de Keras previamente entrenado

Cargue el modelo de clasificación resnet-50 preentrenado proporcionado por Keras:

if tuple(keras.__version__.split(".")) < ("2", "4", "0"):
    weights_url = "".join(
        [
            "https://github.com/fchollet/deep-learning-models/releases/",
            "download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5",
        ]
    )
    weights_file = "resnet50_keras_old.h5"
else:
    weights_url = "".join(
        [
            " https://storage.googleapis.com/tensorflow/keras-applications/",
            "resnet/resnet50_weights_tf_dim_ordering_tf_kernels.h5",
        ]
    )
    weights_file = "resnet50_keras_new.h5"

weights_path = download_testdata(weights_url, weights_file, module="keras")
keras_resnet50 = tf.keras.applications.resnet50.ResNet50(
    include_top=True, weights=None, input_shape=(224, 224, 3), classes=1000
)
keras_resnet50.load_weights(weights_path)

imagen de prueba de carga

Aquí está la imagen del gato de antes:

from PIL import Image
from matplotlib import pyplot as plt
from tensorflow.keras.applications.resnet50 import preprocess_input

img_url = "https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true"
img_path = download_testdata(img_url, "cat.png", module="data")
img = Image.open(img_path).resize((224, 224))
plt.imshow(img)
plt.show()
# 预处理输入
data = np.array(img)[np.newaxis, :].astype("float32")
data = preprocess_input(data).transpose([0, 3, 1, 2])
print("input_1", data.shape)

Por favor agregue una descripción de la imagen

Resultado de salida:

input_1 (1, 3, 224, 224)

Compile el modelo con Relay

Convierta el modelo Keras (diseño NHWC) al formato de relé (diseño NCHW):

shape_dict = {"input_1": data.shape}
mod, params = relay.frontend.from_keras(keras_resnet50, shape_dict)
# 编译模型
target = "cuda"
dev = tvm.cuda(0)

# TODO(mbs):opt_level=3 导致 nn.contrib_conv2d_winograd_weight_transform
# 很可能由于潜在的错误,最终出现在 cuda 上的内存验证失败的模块中。
# 注意:只能在 evaluate() 中传递 context,它不被 create_executor() 捕获。
with tvm.transform.PassContext(opt_level=0):
    model = relay.build_module.create_executor("graph", mod, dev, target, param).evaluate()

Ejecutar en TVM

dtype = "float32"
tvm_out = model(tvm.nd.array(data.astype(dtype)))
top1_tvm = np.argmax(tvm_out.numpy()[0])

Buscar el nombre del conjunto de taxonomía

En un conjunto de clasificación de 1000 clases, encuentre la primera con la puntuación más alta:

synset_url = "".join(
    [
        "https://gist.githubusercontent.com/zhreshold/",
        "4d0b62f3d01426887599d4f7ede23ee5/raw/",
        "596b27d23537e5a1b5751d2b0481ef172f58b539/",
        "imagenet1000_clsid_to_human.txt",
    ]
)
synset_name = "imagenet1000_clsid_to_human.txt"
synset_path = download_testdata(synset_url, synset_name, module="data")
with open(synset_path) as f:
    synset = eval(f.read())
print("Relay top-1 id: {}, class name: {}".format(top1_tvm, synset[top1_tvm]))
# 验证 Keras 输出的正确性
keras_out = keras_resnet50.predict(data.transpose([0, 2, 3, 1]))
top1_keras = np.argmax(keras_out)
print("Keras top-1 id: {}, class name: {}".format(top1_keras, synset[top1_keras]))

Resultado de salida:

Relay top-1 id: 285, class name: Egyptian cat
Keras top-1 id: 285, class name: Egyptian cat

Descarga el código fuente de Python: from_keras.py

Descargar Jupyter Notebook: from_keras.ipynb

Supongo que te gusta

Origin blog.csdn.net/HyperAI/article/details/131165422
Recomendado
Clasificación