美文网首页
keras学习笔记

keras学习笔记

作者: 赵小闹闹 | 来源:发表于2018-08-09 21:01 被阅读242次
    • 参考keras 中文文档

    1.在多张GPU卡上使用Keras

    以TnesorFlow后端,可以使用数据并行的方式。数据并行将目标模型在多个设备上各复制一份,并使用每个设备上的复制品处理整个数据集的不同部分数据。
    from keras.utils import multi_gpu_model

    # Replicates `model` on 8 GPUs.
    # This assumes that your machine has 8 available GPUs.
    parallel_model = multi_gpu_model(model, gpus=8)
    parallel_model.compile(loss='categorical_crossentropy',
                           optimizer='rmsprop')
    
    # This `fit` call will be distributed on 8 GPUs.
    # Since the batch size is 256, each GPU will process 32 samples.
    parallel_model.fit(x, y, epochs=20, batch_size=256)
    

    2. "batch", "epoch"和"sample"的含义

    Sample:样本,数据集中的一条数据。例如图片数据集中的一张图片
    Batch:中文为批,一个batch由若干条数据构成。batch是进行网络优化的基本单位,网络参数的每一轮优化需要使用一个batch。batch越大则对输入数据分布模拟的越好,反应在网络训练上,则体现为能让网络训练的方向“更加正确”。但另一方面,一个batch也只能让网络的参数更新一次,因此网络参数的迭代会较慢。在测试网络的时候,应该在条件的允许的范围内尽量使用更大的batch,这样计算效率会更高。
    Epoch,epoch可译为“轮次”。如果说每个batch对应网络的一次更新的话,一个epoch对应的就是网络的一轮更新。每一轮更新中网络更新的次数可以随意,但通常会设置为遍历一遍数据集。因此一个epoch的含义是模型完整的看了一遍数据集。

    3. 保存Keras模型

    可以使用model.save(filepath)将Keras模型和权重保存在一个HDF5文件中,该文件将包含:

    • 模型的结构,以便重构该模型
    • 模型的权重
    • 训练配置(损失函数,优化器等)
    • 优化器的状态,以便于从上次训练中断的地方开始
      使用keras.models.load_model(filepath)来重新实例化你的模型
    from keras.models import load_model
    model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
    del model  # deletes the existing model
    # returns a compiled model
    # identical to the previous one
    model = load_model('my_model.h5')
    

    如果需要保存模型的权重,可通过下面的代码利用HDF5进行保存。注意,在使用前需要确保你已安装了HDF5和其Python库h5py

    model.save_weights('my_model_weights.h5')
    

    如果你需要在代码中初始化一个完全相同的模型,请使用:

    model.load_weights('my_model_weights.h5')
    

    如果你需要加载权重到不同的网络结构(有些层一样)中,例如fine-tune或transfer-learning,你可以通过层名字来加载模型:

    model.load_weights('my_model_weights.h5', by_name=True)
    

    例如:仅加载层名字相同的参数。

    """
    假如原模型为:
        model = Sequential()
        model.add(Dense(2, input_dim=3, name="dense_1"))
        model.add(Dense(3, name="dense_2"))
        ...
        model.save_weights(fname)
    """
    # new model
    model = Sequential()
    model.add(Dense(2, input_dim=3, name="dense_1"))  # will be loaded
    model.add(Dense(10, name="new_dense"))  # will not be loaded
    
    # load weights from first model; will only affect the first layer, dense_1.
    model.load_weights(fname, by_name=True)
    

    获取中间层的输出

    可以建立一个Keras的函数来达到这一目的:

    from keras import backend as K
    
    # with a Sequential model
    get_3rd_layer_output = K.function([model.layers[0].input],
                                      [model.layers[3].output])
    layer_output = get_3rd_layer_output([X])[0]
    

    注意,如果你的模型在训练和测试两种模式下不完全一致,例如你的模型中含有Dropout层,批规范化(BatchNormalization)层等组件,你需要在函数中传递一个learning_phase的标记,像这样:

    get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()],
                                      [model.layers[3].output])
    # output in test mode = 0
    layer_output = get_3rd_layer_output([X, 0])[0]
    # output in train mode = 1
    layer_output = get_3rd_layer_output([X, 1])[0]
    

    数据集分割与洗乱

    如果在model.fit中设置validation_spilt的值,则可将数据分为训练集和验证集,原数据在进行验证集分割前并没有被shuffle,所以这里的验证集严格的就是你输入数据最末的x%。
    如果model.fit的shuffle参数为真,训练的数据就会被随机洗乱。不设置时默认为真。训练数据会在每个epoch的训练中都重新洗乱一次。验证集的数据不会被洗乱

    在每个epoch后记录训练/测试的loss和正确率

    model.fit在运行结束后返回一个History对象,其中含有的history属性包含了训练过程中损失函数的值以及其他度量指标。

    hist = model.fit(X, y, validation_split=0.2)
    print(hist.history)
    

    “冻结”网络的层

    “冻结”一个层指的是该层将不参加网络训练,即该层的权重永不会更新。在进行fine-tune时我们经常会需要这项操作。
    可以通过向层的构造函数传递trainable参数来指定一个层是不是可训练的,如:

    frozen_layer = Dense(32,trainable=False)
    

    此外,也可以通过将层对象的trainable属性设为True或False来为已经搭建好的模型设置要冻结的层。 在设置完后,需要运行compile来使设置生效,例如:

    x = Input(shape=(32,))
    layer = Dense(32)
    layer.trainable = False
    y = layer(x)
    
    frozen_model = Model(x, y)
    # in the model below, the weights of `layer` will not be updated during training
    frozen_model.compile(optimizer='rmsprop', loss='mse')
    
    layer.trainable = True
    trainable_model = Model(x, y)
    # with this model the weights of the layer will be updated during training
    # (which will also affect the above model since it uses the same layer instance)
    trainable_model.compile(optimizer='rmsprop', loss='mse')
    
    frozen_model.fit(data, labels)  # this does NOT update the weights of `layer`
    trainable_model.fit(data, labels)  # this updates the weights of `layer`
    

    从Sequential模型中去除一个层

    通过调用.pop()来去除模型的最后一个层,反复调用n次即可去除模型后面的n个层

    model = Sequential()
    model.add(Dense(32, activation='relu', input_dim=784))
    model.add(Dense(32, activation='relu'))
    
    print(len(model.layers))  # "2"
    
    model.pop()
    print(len(model.layers))  # "1"
    

    在Keras中使用预训练的模型

    通过keras.applications载入这些模型:

    from keras.applications.vgg16 import VGG16
    from keras.applications.vgg19 import VGG19
    from keras.applications.resnet50 import ResNet50
    from keras.applications.inception_v3 import InceptionV3
    
    model = VGG16(weights='imagenet', include_top=True)
    

    序列模型

    model = Sequential()
    #定义各层
    model.add()
    #编译
    model.compile(optimizer='rmsprop',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])
    #训练
    model.fit()
    
    • 常用Sequential属性

    • model.layers是添加到模型上的层的list

    函数式(Functional)模型

    只要你的模型不是类似VGG一样一条路走到黑的模型,或者你的模型需要多于一个的输出,那么你总应该选择函数式模型。函数式模型是最广泛的一类模型,序贯模型(Sequential)只是它的一种特殊情况。函数式模型称作Functional,但它的类名是Model

    使用函数式模型的一个典型场景是搭建多输入、多输出的模型


    keras 常用层

    Dense层是全连接层

    所实现的运算是output = activation(dot(input, kernel)+bias)也就是激活函数(wx+b)
    第一个参数是指输出的维度。

    卷积层

    Conv2D层

    keras.layers.convolutional.Conv2D(filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None)
    

    二维卷积层,即对图像的空域卷积。该层对二维输入进行滑动窗卷积

    • filters:卷积核的数目(即输出的维度)
    • kernel_size:卷积核
    • strides:步长,任何不为1的strides均与任何不为1的dilation_rate均不兼容。
    • padding:补0策略,“valid”代表只进行有效的卷积,即对边界数据不处理。“same”代表保留边界处的卷积结果,通常会导致输出shape与输入shape相同。
    • activation:激活函数,如果不指定该参数,将不会使用任何激活函数,极线性激活函数。
    • dilation_rate: 指定dilated convolution中的膨胀比例。任何不为1的dilation_rate均与任何不为1的strides均不兼容。(没明白)
    • use_bias:布尔值,是否使用偏置项
    • data_format:字符串,“channels_first”或“channels_last”之一,代表图像的通道维的位置。tensorflow对应“channels_last”,thoneo对应“channels_first”。以128x128的RGB图像为例,“channels_first”应将数据组织为(3,128,128),而“channels_last”应将数据组织为(128,128,3)。不指定时,默认为channels_last,也就是把维数放在后面。

    Conv2DTranspose层

    该层是转置的卷积操作(反卷积)

    Conv3D层

    三维卷积对三维的输入进行滑动窗卷积,也就是视频。

    Cropping2D层

    对2D输入(图像)进行裁剪,将在空域维度,即宽和高的方向上裁剪。

    ZeroPadding2D层

    对2D输入(如图片)的边界填充0,以控制卷积以后特征图的大小


    池化层

    MaxPooling2D层

    为空域信号施加最大值池化

    keras.layers.pooling.MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None)
    

    pool_size:整数或长为2的整数tuple,代表在两个方向(竖直,水平)上的下采样因子,如取(2,2)将使图片在两个维度上均变为原长的一半。为整数意为各个维度值相同且为该数字。

    AveragePooling2D层

    为空域信号施加平均值池化

    GlobalMaxPooling2D层

    为空域信号施加全局最大值池化

    相关文章

      网友评论

          本文标题:keras学习笔记

          本文链接:https://www.haomeiwen.com/subject/fahcbftx.html