ch02.md 23.3 KB
Newer Older
W
wizardforcel 已提交
1 2
# 二、TensorFlow 的高级库

W
wizardforcel 已提交
3
TensorFlow 有几个高级库和接口(API),允许我们使用 TFLearn,TFSlim,Sonnet,PrettyTensor,Keras 和最近发布的 TensorFlow Estimators 轻松构建和训练模型。
W
wizardforcel 已提交
4 5 6

我们将在本章中介绍以下高级库,同时将下一章专门用于 Keras:

W
wizardforcel 已提交
7 8
*   TFEstimator - 以前的 TF 学习
*   TFSlim
W
wizardforcel 已提交
9 10
*   TFLearn
*   PrettyTensor
W
wizardforcel 已提交
11
*   Sonnet
W
wizardforcel 已提交
12 13 14

我们将提供使用所有五个库构建 MNIST 数据集模型的示例。当我们从第 4 章开始介绍模型的细节时,不要担心理解模型的细节。

W
wizardforcel 已提交
15
您可以使用代码包中包含的 Jupyter 笔记本`ch-02_TF_High_Level_Libraries`来遵循本章中的代码示例。 尝试修改笔记本中的示例以进行实验和游戏。
W
wizardforcel 已提交
16 17


W
wizardforcel 已提交
18
# TFEstimator - 以前的 TF 学习
W
wizardforcel 已提交
19

W
wizardforcel 已提交
20
TFEstimator 是一个高级 API,通过封装训练,评估,预测和导出函数,可以轻松创建和训练模型。 TensorFlow 最近重新命名并在 TensorFlow 中以新名称 TFEstimator 发布了 TFLearn 软件包,可能是为了避免与 tflearn.org 的 TFLearn 软件包混淆。 TFEstimator API 对原始 TF 学习包进行了重大改进,这些包在 KDD 17 会议上提供的研究论文中有所描述,[可以在此链接中找到](https://doi.org/10.1145/3097983.3098171)
W
wizardforcel 已提交
21

W
wizardforcel 已提交
22
TFEstimator 接口设计灵感来自流行的机器学习库 SciKit Learn,允许从不同类型的可用模型创建估计器对象,然后在任何类型的估计器上提供四个主要函数:
W
wizardforcel 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

*   `estimator.fit()`
*   `estimator.evaluate()`
*   `estimator.predict()`
*   `estimator.export()`

函数的名称是不言自明的。估计器对象表示模型,但模型本身是从提供给估计器的模型定义函数创建的。

我们可以在下图中描述估计器对象及其接口:

![](img/f96f0dc6-5093-419b-8c1c-1b0eb1cf388a.png)

使用 Estimator API 而不是在核心 TensorFlow 中构建所有内容,可以不用担心图,会话,初始化变量或其他低级细节。在撰写本书时,TensorFlow 提供了以下预构建的估计器:

*   `tf.contrib.learn.KMeansClustering`
*   `tf.contrib.learn.DNNClassifier`
*   `tf.contrib.learn.DNNRegressor`
*   `tf.contrib.learn.DNNLinearCombinedRegressor`
*   `tf.contrib.learn.DNNLinearCombinedClassifier`
*   `tf.contrib.learn.LinearClassifier`
*   `tf.contrib.learn.LinearRegressor`
*   `tf.contrib.learn.LogisticRegressor`

W
wizardforcel 已提交
46
TFEstimator API 中的简单工作流程如下:
W
wizardforcel 已提交
47 48 49 50 51 52 53 54 55 56

1.  找到与您要解决的问题相关的预构建 Estimator。
2.  编写导入数据集的函数。
3.  定义包含特征的数据中的列。
4.  创建在步骤 1 中选择的预构建估计器的实例。
5.  训练估计器。
6.  使用经过训练的估计器进行评估或预测。

下一章讨论的 Keras 库提供了将 Keras 模型转换为 Estimators 的便捷函数:`keras.estimator.model_to_estimator()`

W
wizardforcel 已提交
57
笔记本`ch-02_TF_High_Level_Libraries`中提供了 MNIST 分类示例的完整代码。 TFEstimator MNIST 示例的输出如下:
W
wizardforcel 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

```py
INFO:tensorflow:Using default config.
WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmprvcqgu07
INFO:tensorflow:Using config: {'_save_checkpoints_steps': None, '_task_type': 'worker', '_save_checkpoints_secs': 600, '_service': None, '_task_id': 0, '_master': '', '_session_config': None, '_num_worker_replicas': 1, '_keep_checkpoint_max': 5, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7ff9d15f5fd0>, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_is_chief': True, '_save_summary_steps': 100, '_model_dir': '/tmp/tmprvcqgu07', '_num_ps_replicas': 0, '_tf_random_seed': None}
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Saving checkpoints for 1 into /tmp/tmprvcqgu07/model.ckpt.
INFO:tensorflow:loss = 2.4365, step = 1
INFO:tensorflow:global_step/sec: 597.996
INFO:tensorflow:loss = 1.47152, step = 101 (0.168 sec)
INFO:tensorflow:global_step/sec: 553.29
INFO:tensorflow:loss = 0.728581, step = 201 (0.182 sec)
INFO:tensorflow:global_step/sec: 519.498
INFO:tensorflow:loss = 0.89795, step = 301 (0.193 sec)
INFO:tensorflow:global_step/sec: 503.414
INFO:tensorflow:loss = 0.743328, step = 401 (0.202 sec)
INFO:tensorflow:global_step/sec: 539.251
INFO:tensorflow:loss = 0.413222, step = 501 (0.181 sec)
INFO:tensorflow:global_step/sec: 572.327
INFO:tensorflow:loss = 0.416304, step = 601 (0.174 sec)
INFO:tensorflow:global_step/sec: 543.99
INFO:tensorflow:loss = 0.459793, step = 701 (0.184 sec)
INFO:tensorflow:global_step/sec: 687.748
INFO:tensorflow:loss = 0.501756, step = 801 (0.146 sec)
INFO:tensorflow:global_step/sec: 654.217
INFO:tensorflow:loss = 0.666772, step = 901 (0.153 sec)
INFO:tensorflow:Saving checkpoints for 1000 into /tmp/tmprvcqgu07/model.ckpt.
INFO:tensorflow:Loss for final step: 0.426257.
INFO:tensorflow:Starting evaluation at 2017-12-15-02:27:45
INFO:tensorflow:Restoring parameters from /tmp/tmprvcqgu07/model.ckpt-1000
INFO:tensorflow:Finished evaluation at 2017-12-15-02:27:45
INFO:tensorflow:Saving dict for global step 1000: accuracy = 0.8856, global_step = 1000, loss = 0.40996

{'accuracy': 0.88559997, 'global_step': 1000, 'loss': 0.40995964}
```

您将在第 5 章中看到如何使用核心 TensorFlow 创建此类模型。

W
wizardforcel 已提交
96
# TFSlim
W
wizardforcel 已提交
97

W
wizardforcel 已提交
98
TFSlim 是一个基于 TensorFlow 核心构建的轻量级库,用于定义和训练模型。 TFSlim 可与其他 TensorFlow 低级和高级库(如 TFLearn)结合使用。 TFSlim 是包装中 TensorFlow 安装的一部分:`tf.contrib.slim`。运行以下命令以检查 TFSlim 安装是否正常工作:
W
wizardforcel 已提交
99 100 101 102 103

```py
python3 -c 'import tensorflow.contrib.slim as slim; eval = slim.evaluation.evaluate_once'
```

W
wizardforcel 已提交
104
TFSlim 提供了几个模块,可以独立挑选和应用,并与其他 TensorFlow 软件包混合使用。例如,在撰写本书时,TFSlim 有以下主要模块:
W
wizardforcel 已提交
105

W
wizardforcel 已提交
106
| TFSlim 模块 | 模块说明 |
W
wizardforcel 已提交
107
| --- | --- |
W
wizardforcel 已提交
108 109 110 111 112 113 114 115 116
| `arg_scope` | 提供将元素应用于作用域下定义的所有图节点的机制。 |
| `layer` | 提供几种不同的层,如`fully_connected``conv2d`等等。 |
| `loss` | 提供用于训练优化器的损失函数 |
| `learn` | 提供训练模型的函数 |
| `evaluate` | 提供评估函数 |
| `metics` | 提供用于评估模型的度量函数 |
| `regularizers` | 提供用于创建正则化方法的函数 |
| `variable` | 提供变量创建的函数 |
| `net` | 提供各种预制和预训练模型,如 VGG16,InceptionV3,ResNet |
W
wizardforcel 已提交
117

W
wizardforcel 已提交
118
TFSlim 的简单工作流程如下:
W
wizardforcel 已提交
119 120 121

1.  使用细长层创建模型。
2.  提供层的输入以实例化模型。
W
wizardforcel 已提交
122
3.  使用对率和标签来定义损失。
W
wizardforcel 已提交
123 124 125 126 127
4.  使用便利函数`get_total_loss()`获得全部损失。
5.  创建一个优化器。
6.  使用便利函数`slim.learning.create_train_op()``total_loss``optimizer`创建训练函数。
7.  使用上一步中定义的便捷函数`slim.learning.train()`和训练函数运行训练。

W
wizardforcel 已提交
128
笔记本`ch-02_TF_High_Level_Libraries`中提供了 MNIST 分类示例的完整代码。 TFSlim MNIST 示例的输出如下:
W
wizardforcel 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

```py
INFO:tensorflow:Starting Session.
INFO:tensorflow:Saving checkpoint to path ./slim_logs/model.ckpt
INFO:tensorflow:global_step/sec: 0
INFO:tensorflow:Starting Queues.
INFO:tensorflow:global step 100: loss = 2.2669 (0.010 sec/step)
INFO:tensorflow:global step 200: loss = 2.2025 (0.010 sec/step)
INFO:tensorflow:global step 300: loss = 2.1257 (0.010 sec/step)
INFO:tensorflow:global step 400: loss = 2.0419 (0.009 sec/step)
INFO:tensorflow:global step 500: loss = 1.9532 (0.009 sec/step)
INFO:tensorflow:global step 600: loss = 1.8733 (0.010 sec/step)
INFO:tensorflow:global step 700: loss = 1.8002 (0.010 sec/step)
INFO:tensorflow:global step 800: loss = 1.7273 (0.010 sec/step)
INFO:tensorflow:global step 900: loss = 1.6688 (0.010 sec/step)
INFO:tensorflow:global step 1000: loss = 1.6132 (0.010 sec/step)
INFO:tensorflow:Stopping Training.
INFO:tensorflow:Finished training! Saving model to disk.
final loss=1.6131552457809448
```

从输出中可以看出,便捷函数`slim.learning.train()`将训练输出保存在指定日志目录中的检查点文件中。如果重新开始训练,它将首先检查检查点是否存在,并且默认情况下将从检查点恢复训练。

W
wizardforcel 已提交
152
在撰写本文时,[TFSlim 的文档页面在此链接中被发现为空](https://www.tensorflow.org/api_docs/python/tf/contrib/slim)。 但是,[可以在此链接的源代码中找到一些文档](https://github.com/tensorflow/tensorflow/tree/r1.4/tensorflow/contrib/slim)
W
wizardforcel 已提交
153

W
wizardforcel 已提交
154
我们将使用 TFSlim 来学习如何在后面的章节中使用预训练的模型,如 VGG16 和 InceptionV3。
W
wizardforcel 已提交
155 156 157 158 159

# TFLearn

TFLearn 是 Python 中的模块化库,它构建在核心 TensorFlow 之上。

W
wizardforcel 已提交
160
TFLearn 与 TensorFlow Learn 软件包不同,后者也称为 TFLearn(TF 和 Learn 之间有一个空格)。[TFLearn 可从此链接获得](http://tflearn.org)[源代码可在 GitHub 上的此链接获得](https://github.com/tflearn/tflearn)
W
wizardforcel 已提交
161 162 163 164 165 166 167

可以使用以下命令在 Python 3 中安装 TFLearn:

```py
pip3 install tflearn
```

W
wizardforcel 已提交
168
要在其他环境或源中安装 TFLearn,请参阅[此链接](http://tflearn.org/installation/)
W
wizardforcel 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

TFLearn 中的简单工作流程如下:

1.  首先创建一个输入层。
2.  传递输入对象以创建更多层。
3.  添加输出层。
4.  使用估计器层(例如`regression`)创建网络。
5.  从上一步中创建的网络创建模型。
6.  使用`model.fit()`方法训练模型。
7.  使用训练的模型进行预测或评估。

# 创建 TFLearn 层

让我们学习如何在 TFLearn 中创建神经网络模型的层:

1.  首先创建一个输入层:

```py
input_layer = tflearn.input_data(shape=[None,num_inputs]
```

1.  传递输入对象以创建更多层:

```py
layer1 = tflearn.fully_connected(input_layer,10,
                                 activation='relu')
layer2 = tflearn.fully_connected(layer1,10,
                                 activation='relu')
```

1.  添加输出层:

```py
output = tflearn.fully_connected(layer2,n_classes,
                                 activation='softmax')
```

1.  从估计器层创建最终网络,例如`regression`

```py
net = tflearn.regression(output,
                         optimizer='adam',
                         metric=tflearn.metrics.Accuracy(),
                         loss='categorical_crossentropy'
                        )
```

TFLearn 为以下子部分中描述的层提供了几个类。

# TFLearn 核心层

TFLearn 在`tflearn.layers.core`模块中提供以下层:

| 层类 | 描述 |
| --- | --- |
| `input_data` | 该层用于指定神经网络的输入层。 |
| `fully_connected` | 该层用于指定一个层,其中所有神经元都连接到前一层中的所有神经元。 |
W
wizardforcel 已提交
226
| `dropout` | 该层用于指定丢弃正则化。输入元素由`1/keep_prob`缩放,同时保持预期的总和不变。 |
W
wizardforcel 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
| `custom_layer` | 此层用于指定要应用于输入的自定义函数。此类包装我们的自定义函数并将该函数显示为层。 |
| `reshape` | 此层将输入重新整形为指定形状的输出。 |
| `flatten` | 该层将输入张量转换为 2D 张量。 |
| `activation` | 该层将指定的激活函数应用于输入张量。 |
| `single_unit` | 该层将线性函数应用于输入。 |
| `highway` | 该层实现了完全连接的公路函数。 |
| `one_hot_encoding` | 此层将数字标签转换为二元向量单热编码表示。 |
| `time_distributed` | 该层将指定的函数应用于输入张量的每个时间步长。 |
| `multi_target_data` | 此层创建并连接多个占位符,特别是在层使用来自多个源的目标时使用。 |

# TFLearn 卷积层

TFLearn 在`tflearn.layers.conv`模块中提供以下层:

| 层类 | 描述 |
| --- | --- |
| `conv_1d` | 该层将 1D 卷积应用于输入数据 |
| `conv_2d` | 该层将 2D 卷积应用于输入数据 |
| `conv_3d` | 该层将 3D 卷积应用于输入数据 |
W
wizardforcel 已提交
246 247
| `conv_2d_transpose` | 该层将`conv2_d`的转置应用于输入数据 |
| `conv_3d_transpose` | 该层将`conv3_d`的转置应用于输入数据 |
W
wizardforcel 已提交
248
| `atrous_conv_2d` | 该层计算二维动态卷积 |
W
wizardforcel 已提交
249 250 251 252 253 254
| `grouped_conv_2d` | 该层计算深度 2D 卷积 |
| `max_pool_1d` | 该层计算 1D 最大池化 |
| `max_pool_2d` | 该层计算 2D 最大池化 |
| `avg_pool_1d` | 该层计算 1D 平均池化 |
| `avg_pool_2d` | 该层计算 2D 平均池化 |
| `upsample_2d` | 该层应用行和列 2D 重复操作 |
W
wizardforcel 已提交
255
| `upscore_layer` | 该层实现了[这个页面](http://arxiv.org/abs/1411.4038)中规定的最高分。 |
W
wizardforcel 已提交
256 257 258 259 260
| `global_max_pool` | 该层实现全局最大池化操作 |
| `global_avg_pool` | 该层实现全局平均池化操作 |
| `residual_block` | 该层实现残差块以创建深度残差网络 |
| `residual_bottleneck` | 该层实现深度残差网络的残差瓶颈块 |
| `resnext_block` | 该层实现 ResNext 块 |
W
wizardforcel 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

# TFLearn 循环层

TFLearn 在`tflearn.layers.recurrent`模块中提供以下层:

| 层类 | 描述 |
| --- | --- |
| `simple_rnn` | 该层实现了简单的循环神经网络模型 |
| `bidirectional_rnn` | 该层实现双向 RNN 模型 |
| `lstm` | 该层实现了 LSTM 模型 |
| `gru` | 该层实现 GRU 模型 |

# TFLearn 正则化层

TFLearn 在`tflearn.layers.normalization`模块中提供以下层:

| 层类 | 描述 |
| --- | --- |
| `batch_normalization` | 该层正则化每个批次的先前层激活的输出 |
| `local_response_normalization` | 该层实现 LR 正则化 |
| `l2_normalization` | 该层将 L2 归一化应用于输入张量 |

# TFLearn 嵌入层

TFLearn 在`tflearn.layers.embedding_ops`模块中只提供一层:

| 层类 | 描述 |
| --- | --- |
| `embedding` | 该层实现整数 ID 或浮点序列的嵌入函数 |

# TFLearn 合并层

TFLearn 在`tflearn.layers.merge_ops`模块中提供以下层:

| 层类 | 描述 |
| --- | --- |
| `merge_outputs` | 该层将张量列表合并为单个张量,通常用于合并相同形状的输出张量 |
W
wizardforcel 已提交
298
| `merge` | 该层将张量列表合并为单个张量;您可以指定需要进行合并的轴 |
W
wizardforcel 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

# TFLearn 估计层

TFLearn 在`tflearn.layers.estimator`模块中只提供一层:

| 层类 | 描述 |
| --- | --- |
| `regression` | 该层实现线性或逻辑回归 |

在创建回归层时,您可以指定优化程序以及损失和度量函数。

TFLearn 在`tflearn.optimizers`模块中提供以下优化器函数作为类:

*   `SGD`
*   `RMSprop`
*   `Adam`
*   `Momentum`
*   ``AdaGrad``
*   `Ftrl`
*   `AdaDelta`
*   `ProximalAdaGrad`
*   `Nesterov`

您可以通过扩展`tflearn.optimizers.Optimizer`基类来创建自定义优化器。

TFLearn 在`tflearn.metrics`模块中提供以下度量函数作为类或操作:

*   `Accuracy``accuracy_op`
*   `Top_k``top_k_op`
*   `R2``r2_op`
*   `WeightedR2``weighted_r2_op`
*   `binary_accuracy_op`

您可以通过扩展`tflearn.metrics.Metric`基类来创建自定义指标。

TFLearn 在`tflearn.objectives`模块中提供以下损失函数,称为目标:

*   `softymax_categorical_crossentropy`
*   `categorical_crossentropy`
*   `binary_crossentropy`
*   `weighted_crossentropy`
*   `mean_square`
*   `hinge_loss`
*   `roc_auc_score`
*   `weak_cross_entropy_2d`

在指定输入,隐藏和输出层时,您可以指定要应用于输出的激活函数。 TFLearn 在`tflearn.activations`模块中提供以下激活函数:

*   `linear`
*   `tanh`
*   `sigmoid`
*   `softmax`
*   `softplus`
*   `softsign`
*   `relu`
*   `relu6`

*   `leaky_relu`
*   `prelu`
*   `elu`
*   `crelu`
*   `selu`

# 创建 TFLearn 模型

从上一步创建的网络创建模型(创建 TFLearn 层部分的步骤 4):

```py
model = tflearn.DNN(net)
```

# TFLearn 模型的类型

TFLearn 提供两种不同的模型:

W
wizardforcel 已提交
374
*   `DNN`(深度神经网络)模型:此类允许您从通过层创建的网络创建多层感知机
W
wizardforcel 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
*   `SequenceGenerator`模型:该类允许您创建可以生成序列的深度神经网络

# 训练 TFLearn 模型

创建后,使用`model.fit()`方法训练模型:

```py
model.fit(X_train, 
          Y_train, 
          n_epoch=n_epochs,  
          batch_size=batch_size, 
          show_metric=True, 
          run_id='dense_model')
```

# 使用 TFLearn 模型

使用训练的模型预测或评估:

```py
score = model.evaluate(X_test, Y_test)
print('Test accuracy:', score[0])
```

笔记本`ch-02_TF_High_Level_Libraries`中提供了 TFLearn MNIST 分类示例的完整代码。 TFLearn MNIST 示例的输出如下:

```py
Training Step: 5499  | total loss: 0.42119 | time: 1.817s
| Adam | epoch: 010 | loss: 0.42119 - acc: 0.8860 -- iter: 54900/55000
Training Step: 5500  | total loss: 0.40881 | time: 1.820s
| Adam | epoch: 010 | loss: 0.40881 - acc: 0.8854 -- iter: 55000/55000
--
Test accuracy: 0.9029
```

[您可以从此链接获得有关 TFLearn 的更多信息](http://tflearn.org/)

# PrettyTensor

PrettyTensor 在 TensorFlow 上提供了一个薄包装器。 PrettyTensor 提供的对象支持可链接的语法来定义神经网络。例如,可以通过链接层来创建模型,如以下代码所示:

```py
model = (X.
         flatten().
         fully_connected(10).
         softmax_classifier(n_classes, labels=Y))
```

可以使用以下命令在 Python 3 中安装 PrettyTensor:

```py
pip3 install prettytensor
```

PrettyTensor 以名为`apply()`的方法提供了一个非常轻量级和可扩展的接口。可以使用`.apply(function, arguments)`方法将任何附加函数链接到 PrettyTensor 对象。 PrettyTensor 将调用`function`并提供当前张量作为`function`的第一个参数。

用户创建的函数可以使用`@prettytensor.register`装饰器来装饰。[详细信息在这里](https://github.com/google/prettytensor)

在 PrettyTensor 中定义和训练模型的工作流程如下:

1.  获取数据。
2.  定义超参数和参数。
3.  定义输入和输出。
4.  定义模型。
5.  定义评估程序,优化程序和训练器函数。
6.  创建跑步者对象。
7.  在 TensorFlow 会话中,使用`runner.train_model()`方法训练模型。
8.  在同一会话中,使用`runner.evaluate_model()`方法评估模型。

笔记本`ch-02_TF_High_Level_Libraries`中提供了 PrettyTensor MNIST 分类示例的完整代码。 PrettyTensor MNIST 示例的输出如下:

```py
[1] [2.5561881]
[600] [0.3553167]
Accuracy after 1 epochs 0.8799999952316284 

[601] [0.47775066]
[1200] [0.34739292]
Accuracy after 2 epochs 0.8999999761581421 

[1201] [0.19110668]
[1800] [0.17418651]
Accuracy after 3 epochs 0.8999999761581421 

[1801] [0.27229539]
[2400] [0.34908807]
Accuracy after 4 epochs 0.8700000047683716 

[2401] [0.40000191]
[3000] [0.30816519]
Accuracy after 5 epochs 0.8999999761581421 

[3001] [0.29905257]
[3600] [0.41590339]
Accuracy after 6 epochs 0.8899999856948853 

[3601] [0.32594997]
[4200] [0.36930788]
Accuracy after 7 epochs 0.8899999856948853 

[4201] [0.26780865]
[4800] [0.2911002]
Accuracy after 8 epochs 0.8899999856948853 

[4801] [0.36304188]
[5400] [0.39880857]
Accuracy after 9 epochs 0.8999999761581421 

[5401] [0.1339224]
[6000] [0.14993289]
Accuracy after 10 epochs 0.8899999856948853 
```

# Sonnet

W
wizardforcel 已提交
490
Sonnet 是一个用 Python 编写的面向对象的库。它是由 DeepMind 在 2017 年发布的。Sonnet 打算从对象中清晰地分离构建计算图的以下两个方面:
W
wizardforcel 已提交
491 492 493 494

*   对象的配置称为模块
*   对象与计算图的连接

W
wizardforcel 已提交
495
可以使用以下命令在 Python3 中安装 Sonnet:
W
wizardforcel 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

```py
pip3 install dm-sonnet
```

[可以按照此链接的说明从源安装 Sonnet](https://github.com/deepmind/sonnet/blob/master/docs/INSTALL.md)

模块被定义为抽象类`sonnet.AbstractModule`的子类。在编写本书时,Sonnet 中提供了以下模块:

| 基本模块 | `AddBias``BatchApply``BatchFlatten``BatchReshape``FlattenTrailingDimensions``Linear``MergeDims``SelectInput``SliceByDim``TileByDim``TrainableVariable` |
| --- | --- |
| 循环模块 | `DeepRNN``ModelRNN``VanillaRNN``BatchNormLSTM``GRU``LSTM` |
| Recurrent + ConvNet 模块 | `Conv1DLSTM``Conv2DLSTM` |
| ConvNet 模块 | `Conv1D``Conv2D``Conv3D``Conv1DTranspose``Conv2DTranspose``Conv3DTranspose``DepthWiseConv2D``InPlaneConv2D``SeparableConv2D` |
| ResidualNets | `Residual``ResidualCore``SkipConnectionCore` |
| 其他 | `BatchNorm``LayerNorm``clip_gradient``scale_gradient` |

我们可以通过创建`sonnet.AbstractModule`的子类来定义我们自己的新模块。从函数创建模块的另一种非推荐方法是通过传递要包装为模块的函数来创建`sonnet.Module`类的对象。

在 Sonnet 库中构建模型的工作流程如下:

1.  为从`sonnet.AbstractModule`继承的数据集和网络体系结构创建类。在我们的示例中,我们创建了一个 MNIST 类和一个 MLP 类。
2.  定义参数和超参数。
3.  从上一步中定义的数据集类定义测试和训练数据集。
4.  使用定义的网络类定义模型。例如,在我们的案例中,`model = MLP([20, n_classes])`创建了一个 MLP 网络,其中包含两层 20 和每个神经元`n_classes`的数量。
5.  使用模型为训练和测试集定义`y_hat`占位符。

1.  定义训练和测试集的损失占位符。
2.  使用训练损失占位符定义优化程序。
3.  在 TensorFlow 会话中执行所需数量的周期的损失函数以优化参数。

W
wizardforcel 已提交
527
笔记本电脑`ch-02_TF_High_Level_Libraries`中提供了 Sonnet MNIST 分类示例的完整代码。 每个类中的`__init__`方法初始化类和相关的超类。`_build`方法在调用类时创建并返回数据集或模型对象。 Sonnet MNIST 示例的输出如下:
W
wizardforcel 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

```py
Epoch : 0 Training Loss : 236.79913330078125
Epoch : 1 Training Loss : 227.3693084716797
Epoch : 2 Training Loss : 221.96337890625
Epoch : 3 Training Loss : 220.99142456054688
Epoch : 4 Training Loss : 215.5921173095703
Epoch : 5 Training Loss : 213.88958740234375
Epoch : 6 Training Loss : 203.7091064453125
Epoch : 7 Training Loss : 204.57427978515625
Epoch : 8 Training Loss : 196.17218017578125
Epoch : 9 Training Loss : 192.3954315185547
Test loss : 192.8847198486328
```

由于神经网络中计算的随机性,您的输出可能会有所不同。这包括我们对 Sonnet 模块的概述。

[有关 Sonnet 的更多详细信息,您可以浏览此链接](https://deepmind.github.io/sonnet/)

# 总结

W
wizardforcel 已提交
549
在本章中,我们浏览了一些构建在 TensorFlow 之上的高级库。我们了解了 TFEstimator,TFSlim,TFLearn,PrettyTensor 和 Sonnet。我们为所有五个实现了 MNIST 分类示例。如果您无法理解模型的细节,请不要担心,因为为 MNIST 示例构建的模型将在以下章节中再次介绍。
W
wizardforcel 已提交
550 551 552

我们总结了下表中提供的库和框架,如下表所示:

W
wizardforcel 已提交
553
| 高级库 | 文档链接 | 源代码链接 | PIP3 安装包 |
W
wizardforcel 已提交
554
| --- | --- | --- | --- |
W
wizardforcel 已提交
555 556
| TFEstimator | <https://www.tensorflow.org/get_started/estimator> | <https://github.com/tensorflow/tensorflow/tree/master/tensorflow/python/estimator> | TensorFlow 预置 |
| TFSlim | <https://github.com/tensorflow/tensorflow/tree/r1.4/tensorflow/contrib/slim> | <https://github.com/tensorflow/tensorflow/tree/r1.4/tensorflow/contrib/slim/python/slim> | TensorFlow 预置 |
W
wizardforcel 已提交
557 558 559 560 561 562
| TFLearn | <http://tflearn.org/> | <https://github.com/tflearn/tflearn> | `tflearn` |
| PrettyTensor | <https://github.com/google/prettytensor/tree/master/docs> | <https://github.com/google/prettytensor> | `prettytensor` |
| Sonnet | <https://deepmind.github.io/sonnet/> | <https://github.com/deepmind/sonnet> | `dm-sonnet` |

在下一章中,我们将了解 Keras,这是用于创建和训练 TensorFlow 模型的最流行的高级库。