TensorLayer 是为研究人员和工程师设计的一款基于Google TensorFlow开发的深度学习与强化学习库。 它提供高级别的(Higher-Level)深度学习API,这样不仅可以加快研究人员的实验速度,也能够减少工程师在实际开发当中的重复工作。 TensorLayer非常易于修改和扩展,这使它可以同时用于机器学习的研究与应用
由于用TensorFlow的迁移学习太过繁琐,在网上看到有人使用TensorLayer,于是想拿来试一试
TensorLayer的安装
对于Windows用户,很简单,在电脑上已经安装TensorFlow的情况下,只需要:
pip install tensorlayer
如果下载速度过慢,可以使用清华大学的镜像:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorlayer
本人在tensorflow 1.10.0版本下安装tensorlayer,但在使用时提示最新版2.0.0的TL需要2.0.0以上版本的TF
即TL的版本不能高于TF
所以接下来:
pip uninstall tensorlayer
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorlayer==1.9.1
选择安装上面官中文档里的1.9.1版本tensorlayer,可成功使用
TensorLayer的初步使用
目前来看,TensorLayer由于版本过多,导致官方文档和源码都很难对应起来,非常混乱。
但TL可以与TF联合使用的机制以及代码的简洁性还是很吸引人,实际上TL和Keras还是比较相似,所以安装半天,又回到原点。
Keras大法好!
如下是TensorLayer源码注释里给的实例程序:使用VGG-16作迁移学习
直接粘贴过来,将就看吧。。。
"""Pre-trained VGG-16 model.
Parameters
------------
x : placeholder
shape [None, 224, 224, 3], value range [0, 255].
end_with : str
The end point of the model. Default ``fc3_relu`` i.e. the whole model.
reuse : boolean
Whether to reuse the model.
Examples
---------
Classify ImageNet classes with VGG16, see `tutorial_models_vgg16.py <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_models_vgg16.py>`__
>>> x = tf.placeholder(tf.float32, [None, 224, 224, 3])
>>> # get the whole model
>>> vgg = tl.models.VGG16(x)
>>> # restore pre-trained VGG parameters
>>> sess = tf.InteractiveSession()
>>> vgg.restore_params(sess)
>>> # use for inferencing
>>> probs = tf.nn.softmax(vgg.outputs)
Extract features with VGG16 and Train a classifier with 100 classes
>>> x = tf.placeholder(tf.float32, [None, 224, 224, 3])
>>> # get VGG without the last layer
>>> vgg = tl.models.VGG16(x, end_with='fc2_relu')
>>> # add one more layer
>>> net = tl.layers.DenseLayer(vgg, 100, name='out')
>>> # initialize all parameters
>>> sess = tf.InteractiveSession()
>>> tl.layers.initialize_global_variables(sess)
>>> # restore pre-trained VGG parameters
>>> vgg.restore_params(sess)
>>> # train your own classifier (only update the last layer)
>>> train_params = tl.layers.get_variables_with_name('out')
Reuse model
>>> x1 = tf.placeholder(tf.float32, [None, 224, 224, 3])
>>> x2 = tf.placeholder(tf.float32, [None, 224, 224, 3])
>>> # get VGG without the last layer
>>> vgg1 = tl.models.VGG16(x1, end_with='fc2_relu')
>>> # reuse the parameters of vgg1 with different input
>>> vgg2 = tl.models.VGG16(x2, end_with='fc2_relu', reuse=True)
>>> # restore pre-trained VGG parameters (as they share parameters, we don’t need to restore vgg2)
>>> sess = tf.InteractiveSession()
>>> vgg1.restore_params(sess)
"""