如果你了解过TensorFlow框架,会发现这个深度学习库需要我们自己定义所有的计算节点,通过将图片进行卷积处理、建立卷积网络、建立池化层网络、建立全连接层等步骤,实现一个卷积神经网络,让人头大。
而TFLearn是一个建立在TensorFlow之上的模块化的、透明的深度学习库,比TensorFlow提供了更高层次的API,可以让我们快速地进行实验。
安装TFLearn
需要在Tensorflow 1.0以上版本的基础上安装TFLearn,然后根据系统选择不同的二进制文件进行安装,所有请安装Tensorflow。
# Ubuntu/Linux 64-bit, 仅限CPU, Python 3.3
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp33-cp33m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, 已启用GPU, Python 3.3
# 需要CUDA工具包8.0和CuDNN v5
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp33-cp33m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, 仅限CPU, Python 3.4
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp34-cp34m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, 已启用GPU, Python 3.4
# 需要CUDA工具包8.0和CuDNN v5
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp34-cp34m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, 仅限CPU, Python 3.5
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp35-cp35m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, 已启用GPU, Python 3.5
# 需要CUDA工具包8.0和CuDNN v5
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, 仅限CPU, Python 3.6
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp36-cp36m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, 已启用GPU, Python 3.6
# 需要CUDA工具包8.0和CuDNN v5
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp36-cp36m-linux_x86_64.whl
# Mac OS X, 仅限CPU, Python 3.4 or 3.5:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.1.0-py3-none-any.whl
# Mac OS X, 已启用GPU, Python 3.4 or 3.5:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow_gpu-1.1.0-py3-none-any.whl
然后使用下面命令安装TensorFlow。
# Python 3
$ sudo pip3 install $TF_BINARY_URL
然后就可以开始安装TFLearn了,要安装TFLearn,最简单的方法是从下面选一个方式运行。
# 最新的版本
$ pip3 install git+https://github.com/tflearn/tflearn.git
# 最新的稳定版本
$ pip3 install tflearn
# 在源文件夹通过运行命令从源安装
$ python3 setup.py install
使用TFLearn实现线性回归
在看TFLearn的入门教程之前,不如先直接使用TFLearn做一个用来预测数据的线性回归模型。线性回归大概来说就是先通过直线方程公式计算出所有个体的直线方程,然后在这些直线方程的结果中找到并画出一条直线。
理解了线性回归之后,我们就可以尝试使用TFLearn去实现一个线性回归模型。
import tflearn
# 回归数据
X = [3.38,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1]
Y = [1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3]
# 线性回归图
input_ = tflearn.input_data(shape=[None])
linear = tflearn.single_unit(input_)
# 优化器,目标(`optimizer`)和评价指标(`metric`)
regression = tflearn.regression(linear, optimizer='sgd', loss='mean_square', metric='R2', learning_rate=0.01)
# 使用`DNN`(深度神经网络)模型类训练模型
m = tflearn.DNN(regression)
m.fit(X, Y, n_epoch=1000, show_metric=True, snapshot_epoch=False)
print("回归结果:")
# `get_weights`方法获取模型的权重值
print("Y = " + str(m.get_weights(linear.W)) + "*X + " + str(m.get_weights(linear.b)))
print("x的测试预测 = 3.2, 3.3, 3.4:")
print(m.predict([3.2, 3.3, 3.4]))
执行上面的代码后,你会得到下面的这样的输出。
$ python3 LinearRegression.py
2019-09-26 16:20:39.020965: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
---------------------------------
Run id: 9SMM2Q
Log directory: /tmp/tflearn_logs/
---------------------------------
Training samples: 17
Validation samples: 0
--
Training Step: 1000 | total loss: 0.15402 | time: 0.002s
| SGD | epoch: 1000 | loss: 0.15402 - R2: 0.9734 -- iter: 17/17
--
回归结果:
Y = [0.259189]*X + [0.7446459]
x的测试预测 = 3.2, 3.3, 3.4:
[1.5740507 1.5999696 1.6258886]
在模型成功建立以后,我们通过下面的命令运行并启动Tensorboard服务以可视化网络和性能。
$ tensorboard --logdir='/tmp/tflearn_logs'
TensorBoard 1.12.0 at http://coding.ide:6006 (Press CTRL+C to quit)
在浏览器访问“127.0.0.1:6006”,即可打开下面的web页面,可视化的查看网络和性能。
TFLearn入门
首先,我们使用TFLearn高级API快速神经网络构建和训练,然后展示TFLearn层,内置操作和帮助程序如何直接使Tensorflow受益于任何模型实现。
TFLearn引入了高级API,该API使神经网络的构建和训练变得快速而轻松。而且该API直观、和Tensorflow完全兼容。
图层
图层是TFLearn的核心功能,尽管使用Tensorflow指定参数完全定义模型可能既耗时又重复,但TFLearn带来了代表抽象操作集的“层”,从而使神经网络的构建更加方便。
例如,建立一个卷积层的过程如下:
- 创建并初始化权重和偏差变量
- 对传入张量应用卷积
- 卷积后添加激活函数
- 等等…
在Tensorflow中,编写此类操作是非常复杂的。
with tf.name_scope('conv1'):
W = tf.Variable(tf.random_normal([5, 5, 1, 32]), dtype=tf.float32, name='Weights')
b = tf.Variable(tf.random_normal([32]), dtype=tf.float32, name='biases')
x = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
x = tf.add_bias(x, b)
x = tf.nn.relu(x)
在TFLearn中,只需要一行足矣。
tflearn.conv_2d(x, 32, 5, activation='relu', name='conv1')
当前可以使用core
、conv
、recurrent
、embedding
、normalization
、merge
和estimator
这些图层。
内置操作
除了分层概念之外,TFLearn还提供了许多在构建神经网络时要使用的操作。这些操作正常是要作为layers
参数的一部分存在,但为方便起见,它们也可以在其他Tensorflow graph(定义一个图)中独立使用。
在实践中,仅提供指定参数名称作为参数就足够了(例如对于conv_2d
,为activation = 'relu'
或regularizer = 'L2'
),但也可以提供一个函数以进行自定义。
当前可以使用activations
、objectives
、optimizers
、metrics
、initializations
和losses
这些内置操作。
以下是一些上面内置操作的使用示例。
# 图层内的激活和正则化
fc2 = tflearn.fully_connected(fc1, 32, activation='tanh', regularizer='L2')
# 相当于Tensorflow的
fc2 = tflearn.fully_connected(fc1, 32)
tflearn.add_weights_regularization(fc2, loss='L2')
fc2 = tflearn.tanh(fc2)
# 优化器,目标(`optimizer`)和评价指标(`metric`)
reg = tflearn.regression(fc4, optimizer='rmsprop', metric='accuracy', loss='categorical_crossentropy')
# 也可以在外部定义操作,以进行更深入的自定义
momentum = tflearn.optimizers.Momentum(learning_rate=0.1, weight_decay=0.96, decay_step=200)
top5 = tflearn.metrics.Top_k(k=5)
reg = tflearn.regression(fc4, optimizer=momentum, metric=top5, loss='categorical_crossentropy')
训练、评估与预测
训练功能是TFLearn的另一个核心功能。在Tensorflow中,没有用于训练网络的预构建API,因此TFLearn集成了一组功能,可以轻松处理任何神经网络训练,无论输入、输出和优化器的数量如何。
在使用TFlearn层时,许多参数已经提前被安排好了,因此使用DNN
(深度神经网络)模型类很容易训练模型。
network = ... (some layers) ...
network = regression(network, optimizer='sgd', loss='categorical_crossentropy')
model = DNN(network)
model.fit(X, Y)
也可以直接调用它进行预测或评估。
network = ...
model = DNN(network)
model.load('model.tflearn')
model.predict(X)
想了解更多细节的话,可以阅读dnn
和estimator
的文档。
可视化
虽然编写Tensorflow模型并添加张量tensorboard(功能强大的可视化工具)摘要不是很容易,但TFLearn能够自我管理许多有用的日志。
当前,TFLearn支持详细级别以自动管理摘要:
- 0:损耗和公制(最佳速度)
- 1:损失,指标和渐变
- 2:损失,指标,渐变和权重
- 3:损失,指标,渐变,权重,激活和稀疏度(最佳可视化)
使用DNN
模型类,只需要指定详细参数即可。
model = DNN(network, tensorboard_verbose=3)
然后,可以运行Tensorboard以可视化网络和性能。
$ tensorboard --logdir='/tmp/tflearn_logs'
图形
损失和准确性(多次运行)
图层
权重持久性
要保存或恢复模型,只需调用DNN
模型类的save
或load
方法即可。
# 保存模型
model.save('my_model.tflearn')
# 恢复模型
model.load('my_model.tflearn')
检索图层变量既可以使用图层名称完成,也可以直接使用添加到图层返回的Tensor
(张量)中的W
或b
属性来完成。
# 创建一个图层
fc1 = fully_connected(input_layer, 64, name="fc_layer_1")
# 使用`Tensor`属性,图层将使用权重属性为返回的Tensor增压
fc1_weights_var = fc1.W
fc1_biases_var = fc1.b
# 使用Tensor(张量)名称
fc1_vars = tflearn.get_layer_variables_by_name("fc_layer_1")
fc1_weights_var = fc1_vars[0]
fc1_biases_var = fc1_vars[1]
为了获取或设置这些变量的值,TFLearn模型类实现了get_weights
和set_weights
方法。
input_data = tflearn.input_data(shape=[None, 784])
fc1 = tflearn.fully_connected(input_data, 64)
fc2 = tflearn.fully_connected(fc1, 10, activation='softmax')
net = tflearn.regression(fc2)
model = DNN(net)
# 获取fc2的权重值
model.get_weights(fc2.W)
# 为fc2分配新的随机权重
model.set_weights(fc2.W, numpy.random.rand(64, 10))
我们还可以直接使用TensorFlow的eval
或assign
操作来获取或设置这些变量的值。更多内容可以阅读weights_persistence.py
文档。
微调
在许多情况下,微调针对新任务的预训练模型可能很有用。因此,在TFLearn中定义模型时,您可以指定要还原的图权重或不希望还原的权重(加载预先训练的模型时)。
可以使用图层功能的restore
参数处理(仅适用于具有权重的图层)。
# 权重将默认恢复
fc_layer = tflearn.fully_connected(input_layer, 32)
# 如果指定,重量将不会恢复
fc_layer = tflearn.fully_connected(input_layer, 32, restore='False')
所有不需要还原的权重都将添加到tf.GraphKeys.EXCL_RESTORE_VARS
集合中,并且在加载预先训练的模型时,这些变量还原将被忽略。这个finetuning.py示例显示了如何通过恢复除最后一个完全连接的层以外的所有权重来微调新任务上的网络,然后在新的数据集上训练新模型。
数据管理
TFLearn支持numpy
数组数据。此外,它还支持HDF5处理大型数据集。HDF5
是用于存储和管理数据的数据模型,库和文件格式。它支持无限多种数据类型,并且为灵活高效的I/O以及大量和复杂的数据而设计。
TFLearn可以直接使用HDF5格式的数据。
# 加载hdf5数据集
h5f = h5py.File('data.h5', 'r')
X, Y = h5f['MyLargeData']
... 定义网络 ...
# 使用HDF5数据模型来训练模型
model = DNN(network)
model.fit(X, Y)
更多信息可以阅读hdf5.py
例子。
数据预处理和数据扩充
在训练模型时通常会执行数据预处理和数据扩充,因此TFLearn提供了包装器以轻松处理它。还要注意,TFLearn数据流设计有计算管道,以加快训练速度(通过在GPU执行模型训练时在CPU上预处理数据)。
# 实时图像预处理
img_prep = tflearn.ImagePreprocessing()
# 零中心(在整个数据集中计算平均值)
img_prep.add_featurewise_zero_center()
# STD规范化(对整个数据集计算std)
img_prep.add_featurewise_stdnorm()
# 实时数据扩充
img_aug = tflearn.ImageAugmentation()
# 随机翻转图像
img_aug.add_random_flip_leftright()
# 将这些方法添加到`input_data`层中
network = input_data(shape=[None, 32, 32, 3],
data_preprocessing=img_prep,
data_augmentation=img_aug)
范围和权重共享
所有图层都基于variable_op_scope
构建,这使得在多个层之间轻松共享变量并使TFLearn适用于分布式训练。所有带有内部变量的层都支持scope
自变量来将变量放置在下面;具有相同范围名称的图层将共享相同的权重。
# 定义模型构建器
def my_model(x):
x = tflearn.fully_connected(x, 32, scope='fc1')
x = tflearn.fully_connected(x, 32, scope='fc2')
x = tflearn.fully_connected(x, 2, scope='out')
# 2个不同的计算图,但共享相同的权重
with tf.device('/gpu:0'):
# 强制所有变量驻留在CPU上
with tf.arg_scope([tflearn.variables.variable], device='/cpu:0'):
model1 = my_model(placeholder_X)
# 为下一个模型重用变量
tf.get_variable_scope().reuse_variables()
with tf.device('/gpu:1'):
with tf.arg_scope([tflearn.variables.variable], device='/cpu:0'):
model2 = my_model(placeholder_X)
# 现在可以通过多个GPU训练模型
...
图像初始化
训练时限制资源或分配更多或更少的GPU RAM内存可能很有用。为此,可以使用图形初始化程序在运行之前配置图形。
tflearn.init_graph(set_seed=8888, num_cores=16, gpu_memory_fraction=0.5)
更多内容可以阅读config
文档。
转载:https://blog.csdn.net/hekaiyou/article/details/101456519