

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 TensorFlow-Neuron 和 Neuron 编译器 AWS
<a name="tutorial-inferentia-tf-neuron"></a>

 本教程演示如何使用 Ne AWS uron 编译器编译 Keras ResNet -50 模型并将其以格式导出为已保存的模型。 SavedModel 这种格式是典型的 TensorFlow 模型可互换格式。您还可以学习如何使用示例输入，在 Inf1 实例上运行推理过程。  

 有关 Neuron SDK 的更多信息，请参阅 [AWS Neuron SDK 文档](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/tensorflow-neuron/index.html)。

**Topics**
+ [前提条件](#tutorial-inferentia-tf-neuron-prerequisites)
+ [激活 Conda 环境](#tutorial-inferentia-tf-neuron-activate)
+ [Resnet50 编译](#tutorial-inferentia-tf-neuron-compilation)
+ [ResNet50 推论](#tutorial-inferentia-tf-neuron-inference)

## 前提条件
<a name="tutorial-inferentia-tf-neuron-prerequisites"></a>

 使用本教程之前，您应已完成 [启动带有神经元的 DLAMI 实例 AWS](tutorial-inferentia-launching.md) 中的设置步骤。您还应该熟悉深度学习知识以及如何使用 DLAMI。

## 激活 Conda 环境
<a name="tutorial-inferentia-tf-neuron-activate"></a>

 使用以下命令激活 TensorFlow-Neuron conda 环境：

```
source activate aws_neuron_tensorflow_p36
```

 要退出当前 Conda 环境，请运行以下命令：

```
source deactivate
```

## Resnet50 编译
<a name="tutorial-inferentia-tf-neuron-compilation"></a>

创建一个名为 **tensorflow\_compile\_resnet50.py** 的 Python 脚本，其中包含以下内容。此 Python 脚本编译 Keras ResNet 50 模型并将其导出为已保存的模型。

```
import os
import time
import shutil
import tensorflow as tf
import tensorflow.neuron as tfn
import tensorflow.compat.v1.keras as keras
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input

# Create a workspace
WORKSPACE = './ws_resnet50'
os.makedirs(WORKSPACE, exist_ok=True)

# Prepare export directory (old one removed)
model_dir = os.path.join(WORKSPACE, 'resnet50')
compiled_model_dir = os.path.join(WORKSPACE, 'resnet50_neuron')
shutil.rmtree(model_dir, ignore_errors=True)
shutil.rmtree(compiled_model_dir, ignore_errors=True)

# Instantiate Keras ResNet50 model
keras.backend.set_learning_phase(0)
model = ResNet50(weights='imagenet')

# Export SavedModel
tf.saved_model.simple_save(
 session            = keras.backend.get_session(),
 export_dir         = model_dir,
 inputs             = {'input': model.inputs[0]},
 outputs            = {'output': model.outputs[0]})

# Compile using Neuron
tfn.saved_model.compile(model_dir, compiled_model_dir)

# Prepare SavedModel for uploading to Inf1 instance
shutil.make_archive(compiled_model_dir, 'zip', WORKSPACE, 'resnet50_neuron')
```

 使用以下命令编译该模型：

```
python tensorflow_compile_resnet50.py
```

编译过程将需要几分钟时间。完成后，您的输出应与以下内容类似：

```
...
INFO:tensorflow:fusing subgraph neuron_op_d6f098c01c780733 with neuron-cc
INFO:tensorflow:Number of operations in TensorFlow session: 4638
INFO:tensorflow:Number of operations after tf.neuron optimizations: 556
INFO:tensorflow:Number of operations placed on Neuron runtime: 554
INFO:tensorflow:Successfully converted ./ws_resnet50/resnet50 to ./ws_resnet50/resnet50_neuron
...
```

 ​ 

 编译后，保存的模型将进行压缩，放置在 **ws\_resnet50/resnet50\_neuron.zip** 中。使用以下命令对模型解压缩，并下载用于推理的示例图像：

```
unzip ws_resnet50/resnet50_neuron.zip -d .
curl -O https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg
```

## ResNet50 推论
<a name="tutorial-inferentia-tf-neuron-inference"></a>

创建一个名为 **tensorflow\_infer\_resnet50.py** 的 Python 脚本，其中包含以下内容。此脚本使用先前编译的推理模型，对下载的模型运行推理过程。

```
import os
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications import resnet50

# Create input from image
img_sgl = image.load_img('kitten_small.jpg', target_size=(224, 224))
img_arr = image.img_to_array(img_sgl)
img_arr2 = np.expand_dims(img_arr, axis=0)
img_arr3 = resnet50.preprocess_input(img_arr2)
# Load model
COMPILED_MODEL_DIR = './ws_resnet50/resnet50_neuron/'
predictor_inferentia = tf.contrib.predictor.from_saved_model(COMPILED_MODEL_DIR)
# Run inference
model_feed_dict={'input': img_arr3}
infa_rslts = predictor_inferentia(model_feed_dict);
# Display results
print(resnet50.decode_predictions(infa_rslts["output"], top=5)[0])
```

 使用以下命令对模型运行推理过程：

```
python tensorflow_infer_resnet50.py
```

 您的输出应与以下内容类似：

```
...
[('n02123045', 'tabby', 0.6918919), ('n02127052', 'lynx', 0.12770271), ('n02123159', 'tiger_cat', 0.08277027), ('n02124075', 'Egyptian_cat', 0.06418919), ('n02128757', 'snow_leopard', 0.009290541)]
```

**下一个步骤**  
[使用 AWS 神经元服务 TensorFlow](tutorial-inferentia-tf-neuron-serving.md)