TensorFlow (2) CNN卷积神经网络_ TFLearn 快速搭建深度学习模型

环境:Win8.1 TensorFlow1.0.1

软件:Anaconda3 (集成Python3及开发环境)

TensorFlow安装:pip install tensorflow (CPU版) pip install tensorflow-gpu (GPU版)

TFLearn安装:pip install tflearn


参考:

1. TFLearn: Deep learning library featuring a higher-level API for TensorFlow

2. Github: tflearn


1. 前言

在之间的博文中,我们介绍了深度学习的组成和发展,推动卷积神经网络快速发展的经典模型(AlexNet、VGG、Google Inception Net、ResNet),以及我们如何利用 TensorFlow 建立一个自己的简单 CNN 网络完成特定任务,例如 2层卷积层+2层全连接层+Softmax_CrossEntropy 完成 CIFAR-10 图像分类。随着计算资源平台的飞速发展,我们可以训练更深的网络解决更复杂问题和提高准确率,如 ResNet 使用 Residual Unit 成功训练152层深的神经网络,在 ILSVRC 2015 比赛中获得了冠军,取得3.57%的 top-5 错误率,同时参数量却比 VGGNet 低,效果非常突出。


当我们使用 TensorFlow 建立网络的一层 conv+pooling+lrn 时,可以采用最基本的定义:

[python]  view plain  copy
  1. # conv1  
  2.   with tf.variable_scope('conv1') as scope:  
  3.     kernel = _variable_with_weight_decay('weights', shape=[55364],  
  4.                                          stddev=1e-4, wd=0.0)  
  5.     conv = tf.nn.conv2d(images, kernel, [1111], padding='SAME')  
  6.     biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.0))  
  7.     bias = tf.nn.bias_add(conv, biases)  
  8.     conv1 = tf.nn.relu(bias, name=scope.name)  
  9.     _activation_summary(conv1)  
  10.   
  11.   # pool1  
  12.   pool1 = tf.nn.max_pool(conv1, ksize=[1331], strides=[1221],  
  13.                          padding='SAME', name='pool1')  
  14.   # norm1  
  15.   norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,  
  16.                     name='norm1')  


这种方式在设计较大模型时过程繁琐,需要我们手动完成各个运算符之间的连接,如此中间变量的维度变换、运算符参数选项、多个子网络连接处极易发生问题,且由于代码量规模越来越大 Debug 难度随之增大,浪费大量时间和精力。为了可以更加便捷地建立模型,我们可以使用建立在 TensorFlow 之上构建的高层次 API,例如  Keras TensorLayer ,和本文将要介绍的  TFLearn——Deep learning library featuring a higher-level API for TensorFlow


2. TFLearn


TFlearn is a modular and transparent deep learning library built on top of Tensorflow. It was designed to provide a higher-level API to TensorFlow in order to facilitate and speed-up experimentations, while remaining fully transparent and compatible with it.


TFLearn 是一个构建在 TensorFlow 之上的模块化和透明的深度学习库。它为 TensorFlow 提供高层次 API,目的是便于快速搭建试验环境,同时保持对 TensorFlow 的完全透明和兼容性。


它的特点:

  • 容易使用和易于理解的高层次 API 用于实现深度神经网络,附带教程和例子;
  • 通过高度模块化的内置神经网络层、正则化器、优化器等进行快速原型设计;
  • 对 TensorFlow 完全透明,所有函数都是基于 tensor,可以独立于 TFLearn 使用;
  • 强大的辅助函数,训练任意 TensorFlow 图,支持多输入、多输出和优化器;
  • 简单而美观的图可视化,关于权值、梯度、特征图等细节;
  • 无需人工干预,可使用多 CPU、多 GPU;
  • 高层次 API 目前支持最近大多数深度学习模型,像卷积网络、LSTM、BiRNN、BatchNorm、PReLU、残差网络、生成网络、增强学习。

Note: Latest TFLearn (v0.3) is only compatible with TensorFlow v1.0 and over.


安装:

To install TFLearn, the easiest way is to run

For the bleeding edge version (recommended):

[python]  view plain  copy
  1. pip install git+https://github.com/tflearn/tflearn.git  

For the latest stable version:

[python]  view plain  copy
  1. pip install tflearn  


Otherwise, you can also install from source by running (from source folder):

[python]  view plain  copy
  1. python setup.py install  


3. 实例

我们可以在 tflearn/examples/images/alexnet.py 下学习如何用 TFLearn 实现 AlexNet 用于 Oxford 17 类鲜花 数据集分类任务。

回忆一下之前介绍用于 ImageNet 的 AlexNet 网络:

TensorFlow (2) CNN卷积神经网络_ TFLearn 快速搭建深度学习模型_第1张图片

针对 Oxford 17类鲜花问题作出的修改:

  1. 输入图像尺寸变为 227 x 227
  2. 将 2-tower 架构改为 single-tower
  3. 最后一个分类层的输出类别数从 1000 变为 17

直接运行 alexnet.py 文件将自动下载 Oxford 17 flowers 数据集进行训练:


TensorFlow (2) CNN卷积神经网络_ TFLearn 快速搭建深度学习模型_第2张图片


提示:Oxford 17 flowers 是从 VGG官网  通过 TFLearn 内置 oxflower17.py 下载、解压、分类整理的,由于网络因素下载过程通常狗带,可以选择自行下载 17flowers.tgz 文件置于 17flowers 文件下,同时需要修改 oxflower17.py 下 maybe_download 函数:

[python]  view plain  copy
  1. def maybe_download(filename, source_url, work_directory):  
  2.     if not os.path.exists(work_directory):  
  3.         os.mkdir(work_directory)  
  4.     filepath = os.path.join(work_directory, filename)  
  5.     if not os.path.exists(filepath):  
  6.         print("Downloading Oxford 17 category Flower Dataset, Please "  
  7.               "wait...")  
  8.         filepath, _ = urllib.request.urlretrieve(source_url + filename,  
  9.                                                  filepath, reporthook)  
  10.         statinfo = os.stat(filepath)  
  11.         print(('Succesfully downloaded', filename, statinfo.st_size, 'bytes.'))  
  12.       
  13.     # 将解压和分类整理函数置于if语句外,否则运行程序时检测不到上图16类文件图片  
  14.     untar(filepath, work_directory)  
  15.     build_class_directories(os.path.join(work_directory, 'jpg'))  
  16.       
  17.     return filepath  

可在 TensorBoard 中查看训练过程的准确率、loss 值变化。


TensorFlow (2) CNN卷积神经网络_ TFLearn 快速搭建深度学习模型_第3张图片TensorFlow (2) CNN卷积神经网络_ TFLearn 快速搭建深度学习模型_第4张图片

附上 alexnet.py 源码:

[python]  view plain  copy
  1. # -*- coding: utf-8 -*-  
  2.   
  3. """ AlexNet. 
  4.  
  5. Applying 'Alexnet' to Oxford's 17 Category Flower Dataset classification task. 
  6.  
  7. References: 
  8.     - Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton. ImageNet 
  9.     Classification with Deep Convolutional Neural Networks. NIPS, 2012. 
  10.     - 17 Category Flower Dataset. Maria-Elena Nilsback and Andrew Zisserman. 
  11.  
  12. Links: 
  13.     - [AlexNet Paper](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf) 
  14.     - [Flower Dataset (17)](http://www.robots.ox.ac.uk/~vgg/data/flowers/17/) 
  15.  
  16. """  
  17.   
  18. from __future__ import division, print_function, absolute_import  
  19.   
  20. import tflearn  
  21. from tflearn.layers.core import input_data, dropout, fully_connected  
  22. from tflearn.layers.conv import conv_2d, max_pool_2d  
  23. from tflearn.layers.normalization import local_response_normalization  
  24. from tflearn.layers.estimator import regression  
  25.   
  26. import tflearn.datasets.oxflower17 as oxflower17  
  27. X, Y = oxflower17.load_data(one_hot=True, resize_pics=(227227))  
  28.   
  29. # Building 'AlexNet'  
  30. network = input_data(shape=[None2272273])  
  31. network = conv_2d(network, 9611, strides=4, activation='relu')  
  32. network = max_pool_2d(network, 3, strides=2)  
  33. network = local_response_normalization(network)  
  34. network = conv_2d(network, 2565, activation='relu')  
  35. network = max_pool_2d(network, 3, strides=2)  
  36. network = local_response_normalization(network)  
  37. network = conv_2d(network, 3843, activation='relu')  
  38. network = conv_2d(network, 3843, activation='relu')  
  39. network = conv_2d(network, 2563, activation='relu')  
  40. network = max_pool_2d(network, 3, strides=2)  
  41. network = local_response_normalization(network)  
  42. network = fully_connected(network, 4096, activation='tanh')  
  43. network = dropout(network, 0.5)  
  44. network = fully_connected(network, 4096, activation='tanh')  
  45. network = dropout(network, 0.5)  
  46. network = fully_connected(network, 17, activation='softmax')  
  47. network = regression(network, optimizer='momentum',  
  48.                      loss='categorical_crossentropy',  
  49.                      learning_rate=0.001)  
  50.   
  51. # Training  
  52. model = tflearn.DNN(network, checkpoint_path='model_alexnet',  
  53.                     max_checkpoints=1, tensorboard_verbose=2)  
  54. model.fit(X, Y, n_epoch=1000, validation_set=0.1, shuffle=True,  
  55.           show_metric=True, batch_size=64, snapshot_step=200,  
  56.           snapshot_epoch=False, run_id='alexnet_oxflowers17')  


4. 总结

使用 TFLearn 高层次 API 相比直接使用 TensorFlow 实现深度学习模型具有使用更简单、构建更快速、可视化更方便等特点,从此无需手动处理各个运算符之间的连接,解放了程序员们的生产力(心疼一秒=-=),提高了模型设计和优化效率。


另外,通过 TFLearn 还可以实现其他经典深度学习模型如 VGG、Inception、NIN、ResNet 等,对比原始论文学习,相信会更加高效。

你可能感兴趣的:(Tensenflow)