keras中文文档笔记12——协助使用Keras

预训练模型

Application应用

Kera的应用模块Application提供了带有预训练权重的Keras模型,这些模型可以用来进行预测、特征提取和finetune

模型的预训练权重将下载到~/.keras/models/并在载入模型时自动载入

可用的模型

应用于图像分类的模型,权重训练自ImageNet: Xception VGG16 VGG19 ResNet50 * InceptionV3

所有的这些模型(除了Xception)都兼容Theano和Tensorflow,并会自动基于~/.keras/keras.json的Keras的图像维度进行自动设置。例如,如果你设置data_format=”channel_last”,则加载的模型将按照TensorFlow的维度顺序来构造,即“Width-Height-Depth”的顺序

图片分类模型的示例

利用ResNet50网络进行ImageNet分类

from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np

model = ResNet50(weights='imagenet')

img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(preds, top=3)[0])
# Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458', u'African_elephant', 0.061040461)]

利用VGG16提取特征

from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np

model = VGG16(weights='imagenet', include_top=False)

img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

features = model.predict(x)

从VGG19的任意中间层中抽取特征

from keras.applications.vgg19 import VGG19
from keras.preprocessing import image
from keras.applications.vgg19 import preprocess_input
from keras.models import Model
import numpy as np

base_model = VGG19(weights='imagenet')
model = Model(inputs=base_model.input, outputs=base_model.get_layer('block4_pool').output)

img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

block4_pool_features = model.predict(x)

在新类别上精细调节inceptionV3

from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K

# create the base pre-trained model
base_model = InceptionV3(weights='imagenet', include_top=False)

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)
# and a logistic layer -- let's say we have 200 classes
predictions = Dense(200, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)

# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in base_model.layers:
    layer.trainable = False

# compile the model (should be done *after* setting layers to non-trainable)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

# train the model on the new data for a few epochs
model.fit_generator(...)

# at this point, the top layers are well trained and we can start fine-tuning
# convolutional layers from inception V3. We will freeze the bottom N layers
# and train the remaining top layers.

# let's visualize layer names and layer indices to see how many layers
# we should freeze:
for i, layer in enumerate(base_model.layers):
   print(i, layer.name)

# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 172 layers and unfreeze the rest:
for layer in model.layers[:172]:
   layer.trainable = False
for layer in model.layers[172:]:
   layer.trainable = True

# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy')

# we train our model again (this time fine-tuning the top 2 inception blocks
# alongside the top Dense layers
model.fit_generator(...)

在定制的输入tensor上构建InceptionV3

from keras.applications.inception_v3 import InceptionV3
from keras.layers import Input

# this could also be the output a different Keras model or layer
input_tensor = Input(shape=(224, 224, 3))  # this assumes K.image_data_format() == 'channels_last'

model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=True)

Xception模型

keras.applications.xception.Xception(include_top=True, weights='imagenet',input_tensor=None, input_shape=None,pooling=None, classes=1000)

Xception V1 模型, 权重由ImageNet训练而言

在ImageNet上,该模型取得了验证集top1 0.790和top5 0.945的正确率

注意,该模型目前仅能以TensorFlow为后端使用,由于它依赖于”SeparableConvolution”层,目前该模型只支持channels_last的维度顺序(width, height, channels)

默认输入图片大小为299x299

VGG16模型

keras.applications.vgg16.VGG16(include_top=True, weights='imagenet',input_tensor=None, input_shape=None,pooling=None,classes=1000)

VGG16模型,权重由ImageNet训练而来

该模型再Theano和TensorFlow后端均可使用,并接受channels_first和channels_last两种输入维度顺序

模型的默认输入尺寸时224x224

VGG19模型

keras.applications.vgg19.VGG19(include_top=True, weights='imagenet',input_tensor=None, input_shape=None,pooling=None,classes=1000)

VGG19模型,权重由ImageNet训练而来

该模型在Theano和TensorFlow后端均可使用,并接受channels_first和channels_last两种输入维度顺序

模型的默认输入尺寸时224x224

ResNet50模型

keras.applications.resnet50.ResNet50(include_top=True, weights='imagenet',
                                input_tensor=None, input_shape=None,
                                pooling=None,
                                classes=1000)

50层残差网络模型,权重训练自ImageNet

该模型在Theano和TensorFlow后端均可使用,并接受channels_first和channels_last两种输入维度顺序

模型的默认输入尺寸时224x224

InceptionV3模型

keras.applications.inception_v3.InceptionV3(include_top=True,weights='imagenet',input_tensor=None,input_shape=None,pooling=None,classes=1000)

InceptionV3网络,权重训练自ImageNet

该模型在Theano和TensorFlow后端均可使用,并接受channels_first和channels_last两种输入维度顺序

模型的默认输入尺寸时299x299

常用数据库

CIFAR10 小图片分类数据集

该数据库具有50,000个32*32的彩色图片作为训练集,10,000个图片作为测试集。图片一共有10个类别。
使用方法

from keras.datasets import cifar10
(X_train, y_train), (X_test, y_test) = cifar10.load_data()

CIFAR100 小图片分类数据库

该数据库具有50,000个32*32的彩色图片作为训练集,10,000个图片作为测试集。图片一共有100个类别,每个类别有600张图片。这100个类别又分为20个大类。
使用方法

from keras.datasets import cifar100
(X_train, y_train), (X_test, y_test) = cifar100.load_data(label_mode='fine')

IMDB影评倾向分类

本数据库含有来自IMDB的25,000条影评,被标记为正面/负面两种评价。影评已被预处理为词下标构成的序列。方便起见,单词的下标基于它在数据集中出现的频率标定,例如整数3所编码的词为数据集中第3常出现的词。这样的组织方法使得用户可以快速完成诸如“只考虑最常出现的10,000个词,但不考虑最常出现的20个词”这样的操作

按照惯例,0不代表任何特定的词,而用来编码任何未知单词
使用方法

from keras.datasets import imdb
(X_train, y_train), (X_test, y_test) = imdb.load_data(path="imdb.npz",nb_words=None,skip_top=0,maxlen=None,test_split=0.1)seed=113,start_char=1,oov_char=2,index_from=3)

路透社新闻主题分类

本数据库包含来自路透社的11,228条新闻,分为了46个主题。与IMDB库一样,每条新闻被编码为一个词下标的序列。
使用方法

from keras.datasets import reuters
(X_train, y_train), (X_test, y_test) = reuters.load_data(path="reuters.npz",nb_words=None,skip_top=0,maxlen=None,test_split=0.2,seed=113,start_char=1,oov_char=2,index_from=3)

参数的含义与IMDB同名参数相同,唯一多的参数是: test_split,用于指定从原数据中分割出作为测试集的比例。该数据库支持获取用于编码序列的词下标:

word_index = reuters.get_word_index(path="reuters_word_index.json")

上面代码的返回值是一个以单词为关键字,以其下标为值的字典。例如,word_index[‘giraffe’]的值可能为1234

MNIST手写数字识别

本数据库有60,000个用于训练的28*28的灰度手写数字图片,10,000个测试图片
使用方法

from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()

Boston房屋价格回归数据集

本数据集由StatLib库取得,由CMU维护。每个样本都是1970s晚期波士顿郊区的不同位置,每条数据含有13个属性,目标值是该位置房子的房价中位数(千dollar)。
使用方法

from keras.datasets import boston_housing
(x_train, y_train), (x_test, y_test) = boston_housing.load_data()

模型可视化

keras.utils.vis_utils模块提供了画出Keras模型的函数(利用graphviz)

该函数将画出模型结构图,并保存成图片:

from keras.utils import plot_model
plot_model(model, to_file='model.png')

我们也可以直接获取一个pydot.Graph对象,然后按照自己的需要配置它,例如,如果要在ipython中展示图片

from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot

SVG(model_to_dot(model).create(prog='dot', format='svg'))

【Tips】依赖 pydot-ng 和 graphviz,若出现错误,用命令行输入pip install pydot-ng & brew install graphviz

工具

本模块提供了一系列有用工具

CustomObjectScope

keras.utils.generic_utils.CustomObjectScope()

提供定制类的作用域,在该作用域内全局定制类能够被更改,但在作用域结束后将回到初始状态。 以with声明开头的代码将能够通过名字访问定制类的实例,在with的作用范围,这些定制类的变动将一直持续,在with作用域结束后,全局定制类的实例将回归其在with作用域前的状态。

with CustomObjectScope({"MyObject":MyObject}):
    layer = Dense(..., W_regularizer="MyObject")
    # save, load, etc. will recognize custom object by name

HDF5Matrix

keras.utils.io_utils.HDF5Matrix(datapath, dataset, start=0, end=None, normalizer=None)

这是一个使用HDF5数据集代替Numpy数组的方法

提供start和end参数可以进行切片,另外,还可以提供一个正规化函数或匿名函数,该函数将会在每片数据检索时自动调用。

x_data = HDF5Matrix('input/file.hdf5', 'data')
model.predict(x_data)

to_categorical

to_categorical(y, num_classes=None)

将类别向量(从0到nb_classes的整数向量)映射为二值类别矩阵, 用于应用到以categorical_crossentropy为目标函数的模型中.

normalize

normalize(x, axis=-1, order=2)

对numpy数组规范化,返回规范化后的数组

convert_all_kernels_in_model

convert_all_kernels_in_model(model)

将模型中全部卷积核在Theano和TensorFlow模式中切换

plot_model

plot_model(model, to_file='model.png', show_shapes=False, show_layer_names=True)

绘制模型图

custom_object_scope

custom_object_scope()

提供定制类的作用域,在该作用域内全局定制类能够被更改,但在作用域结束后将回到初始状态。 以with声明开头的代码将能够通过名字访问定制类的实例,在with的作用范围,这些定制类的变动将一直持续,在with作用域结束后,全局定制类的实例将回归其在with作用域前的状态。

本函数返回CustomObjectScope对象

with custom_object_scope({"MyObject":MyObject}):
    layer = Dense(..., W_regularizer="MyObject")
    # save, load, etc. will recognize custom object by name

get_custom_objects

get_custom_objects()

检索全局定制类,推荐利用custom_object_scope更新和清理定制对象,但get_custom_objects可被直接用于访问_GLOBAL_CUSTOM_OBJECTS。本函数返回从名称到类别映射的全局字典。

get_custom_objects().clear()
get_custom_objects()["MyObject"] = MyObject

serialize_keras_object

serialize_keras_object(instance)

将keras对象序列化

deserialize_keras_object

eserialize_keras_object(identifier, module_objects=None, custom_objects=None, printable_module_name='object')

从序列中恢复keras对象

get_file

get_file(fname, origin, untar=False, md5_hash=None, file_hash=None, cache_subdir='datasets', hash_algorithm='auto', extract=False, archive_format='auto', cache_dir=None)

从给定的URL中下载文件, 可以传递MD5值用于数据校验(下载后或已经缓存的数据均可)

默认情况下文件会被下载到~/.keras中的cache_subdir文件夹,并将其文件名设为fname,因此例如一个文件example.txt最终将会被存放在`~/.keras/datasets/example.txt~

tar,tar.gz.tar.bz和zip格式的文件可以被提取,提供哈希码可以在下载后校验文件。命令喊程序shasum和sha256sum可以计算哈希值。

Keras后端

Keras提供了两种后端引擎Theano/Tensorflow,并将其函数统一封装,使得用户可以以同一个接口调用不同后端引擎的函数

  • Theano是一个开源的符号主义张量操作框架,由蒙特利尔大学LISA/MILA实验室开发。
  • TensorFlow是一个符号主义的张量操作框架,由Google开发。
  • CNTK是一个由微软开发的商业级工具包。

切换后端

注意:Windows用户请把$Home换为%USERPROFILE%

如果你至少运行过一次Keras,你将在下面的目录下找到Keras的配置文件:

$HOME/.keras/keras.json

如果该目录下没有该文件,你可以手动创建一个

文件的默认配置如下:

{
    "image_data_format": "channels_last",
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}

将backend字段的值改写为你需要使用的后端:theano或tensorflow或者CNTK,即可完成后端的切换。

我们也可以通过定义环境变量KERAS_BACKEND来覆盖上面配置文件中定义的后端:

KERAS_BACKEND=tensorflow python -c "from keras import backend;"
Using TensorFlow backend.

使用抽象的Keras后端来编写代码

如果你希望你编写的Keras模块能够同时在Theano和TensorFlow两个后端上使用,你可以通过Keras后端接口来编写代码,这里是一个简介:

from keras import backend as K

下面的代码实例化了一个输入占位符,等价于tf.placeholder() ,T.matrix(),T.tensor3()等

input = K.placeholder(shape=(2, 4, 5))
# also works:
input = K.placeholder(shape=(None, 4, 5))
# also works:
input = K.placeholder(ndim=3)

下面的代码实例化了一个共享变量(shared),等价于tf.variable()或 theano.shared()

val = np.random.random((3, 4, 5))
var = K.variable(value=val)

# all-zeros variable:
var = K.zeros(shape=(3, 4, 5))
# all-ones:
var = K.ones(shape=(3, 4, 5))

大多数你需要的张量操作都可以通过统一的Keras后端接口完成,而不关心具体执行这些操作的是Theano还是TensorFlow

a = b + c * K.abs(d)
c = K.dot(a, K.transpose(b))
a = K.sum(b, axis=2)
a = K.softmax(b)
a = concatenate([b, c], axis=-1)
# etc...

Kera后端函数

太多了, 此处省略n字……

Scikit-Learn接口包装器

我们可以通过包装器将Sequential模型(仅有一个输入)作为Scikit-Learn工作流的一部分,相关的包装器定义在keras.wrappers.scikit_learn.py中

目前,有两个包装器可用:

  • keras.wrappers.scikit_learn.KerasClassifier(build_fn=None,
    **sk_params)实现了sklearn的分类器接口
  • keras.wrappers.scikit_learn.KerasRegressor(build_fn=None,
    **sk_params)实现了sklearn的回归器接口

当使用scikit-learn的grid_search接口时,合法的可转换参数是你可以传递给sk_params的参数,包括训练参数。即,你可以使用grid_search来搜索最佳的batch_size或nb_epoch以及其他模型参数。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值