原文做者:aircrafthtml
原文连接:https://www.cnblogs.com/DOMLX/p/9769301.html前端
Keras是什么?python
若是尚未配置keras能够这个博客配置:c++
Dense
()函数--全链接层keras.layers.core.Dense ( units, 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 )
若不懂卷积概念可看:深度学习(二)神经网络中的卷积和反卷积原理编程
keras.layers.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)
2D 卷积层 (例如对图像的空间卷积)。json
该层建立了一个卷积核, 该卷积核对层输入进行卷积, 以生成输出张量。 若是 use_bias
为 True, 则会建立一个偏置向量并将其添加到输出中。 最后,若是 activation
不是 None
,它也会应用于输出。后端
当使用该层做为模型第一层时,须要提供 input_shape
参数 (整数元组,不包含样本表示的轴),例如, input_shape=(128, 128, 3)
表示 128x128 RGB 图像, 在 data_format="channels_last"
时。网络
参数机器学习
dilation_rate
值 != 1 二者不兼容。"valid"
或 "same"
(大小写敏感)。channels_last
(默认) 或 channels_first
之一,表示输入中维度的顺序。 channels_last
对应输入尺寸为 (batch, height, width, channels)
, channels_first
对应输入尺寸为 (batch, channels, height, width)
。 它默认为从 Keras 配置文件 ~/.keras/keras.json
中 找到的 image_data_format
值。 若是你从未设置它,将使用 "channels_last"。dilation_rate
值 != 1 与 指定 stride 值 != 1 二者不兼容。a(x) = x
)。kernel
权值矩阵的初始化器 (详见 initializers)。kernel
权值矩阵的正则化函数 (详见 regularizer)。kernel
权值矩阵的约束函数 (详见 constraints)。输入尺寸ide
(samples, channels, rows, cols)
。(samples, rows, cols, channels)
。输出尺寸
(samples, filters, new_rows, new_cols)
。(samples, new_rows, new_cols, filters)
。
别看上面的参数一堆吓死人,其实咱们在实际运用的时候用的就只有几个而已:
inputs = Input(shape=(n_ch,patch_height,patch_width)) conv1 = Conv2D(32, (3, 3), activation='relu', padding='same',data_format='channels_first')(inputs) #这个小括号填inputs是表明这层模型链接在inputs以后
固然还能够用kears内置的序贯模型add添加构成模型图:
model = Sequential() # Dense(64) is a fully-connected layer with 64 hidden units. # in the first layer, you must specify the expected input data shape: # here, 20-dimensional vectors. model.add(Dense(64, activation='relu', input_dim=20))
若不懂池化概念可看:深度学习(一)神经网络中的池化与反池化原理
keras.layers.pooling.MaxPooling2D( pool_size=(2, 2), strides=None, padding='valid', data_format=None )
仍是同样的好多东西默认就好了,下面就是一个2*2的池化层:
pool1 = MaxPooling2D((2, 2))(conv1)
model.compile
()函数--配置模型
model.compile(optimizer, loss, metrics=None, sample_weight_mode=None)
编译用来配置模型的学习过程,其参数有
optimizer:字符串(预约义优化器名)或优化器对象,参考优化器
loss:字符串(预约义损失函数名)或目标函数,参考损失函数
metrics:列表,包含评估模型在训练和测试时的网络性能的指标,典型用法是metrics=['accuracy']
sample_weight_mode:若是你须要按时间步为样本赋权(2D权矩阵),将该值设为“temporal”。默认为“None”,表明按样本赋权(1D权)。在下面fit函数的解释中有相关的参考内容。
kwargs:使用TensorFlow做为后端请忽略该参数,若使用Theano做为后端,kwargs的值将会传递给 K.function
示例代码:
model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['accuracy'])
fit
()函数--模型运行函数
fit(self, x, y, batch_size=32, epochs=10, verbose=1, callbacks=None, validation_split=0.0,
validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0 )
x:输入数据。若是模型只有一个输入,那么x的类型是numpy array,若是模型有多个输入,那么x的类型应当为list,list的元素是对应于各个输入的numpy array
y:标签,numpy array
batch_size:整数,指定进行梯度降低时每一个batch包含的样本数。训练时一个batch的样本会被计算一次梯度降低,使目标函数优化一步。
epochs:整数,训练的轮数,每一个epoch会把训练集轮一遍。
verbose:日志显示,0为不在标准输出流输出日志信息,1为输出进度条记录,2为每一个epoch输出一行记录
callbacks:list,其中的元素是keras.callbacks.Callback的对象。这个list中的回调函数将会在训练过程当中的适当时机被调用,参考回调函数
validation_split:0~1之间的浮点数,用来指定训练集的必定比例数据做为验证集。验证集将不参与训练,并在每一个epoch结束后测试的模型的指标,如损失函数、精确度等。注意,validation_split的划分在shuffle以前,所以若是你的数据自己是有序的,须要先手工打乱再指定validation_split,不然可能会出现验证集样本不均匀。
validation_data:形式为(X,y)的tuple,是指定的验证集。此参数将覆盖validation_spilt。
shuffle:布尔值或字符串,通常为布尔值,表示是否在训练过程当中随机打乱输入样本的顺序。若为字符串“batch”,则是用来处理HDF5数据的特殊状况,它将在batch内部将数据打乱。
class_weight:字典,将不一样的类别映射为不一样的权值,该参数用来在训练过程当中调整损失函数(只能用于训练)
sample_weight:权值的numpy array,用于在训练时调整损失函数(仅用于训练)。能够传递一个1D的与样本等长的向量用于对样本进行1对1的加权,或者在面对时序数据时,传递一个的形式为(samples,sequence_length)的矩阵来为每一个时间步上的样本赋不一样的权。这种状况下请肯定在编译模型时添加了sample_weight_mode='temporal'。
initial_epoch: 从该参数指定的epoch开始训练,在继续以前的训练时有用。
参数虽多,可是不少均可以省略看代码示例:
model.fit(patches_imgs_train, patches_masks_train, epochs=N_epochs, batch_size=batch_size, verbose=1, shuffle=True, validation_split=0.1, callbacks=[checkpointer])
kears predict()函数--测试数据
predictions = model.predict(patches_imgs_test, batch_size=32, verbose=2) print("predicted images size :") print(predictions.shape)
# 加载训练好的模型
model.load_weights('./weights.h5')
Dropout(x)
X能够取0--1之间,表明百分比抛弃数据
Dropout(0.5)随机抛弃百分之五十的数据
UpSampling2D(size=(2, 2))
size(x,y)
x表明行放大倍数 这里取2的话表明原来的一行变成了两行 (就是一行那么粗,变成了两行那么粗)
y表明列放大倍数 这里取2的话表明原来的一列变成了两行 (就是一列那么粗,变成了两列那么粗)
size(2,2)其实就等于将原图放大四倍(水平两倍,垂直两倍) 32*32 变成 62*64的图像
inputs = Input((n_ch, patch_height, patch_width)) conv1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(inputs) conv1 = Dropout(0.2)(conv1) conv1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(conv1) up1 = UpSampling2D(size=(2, 2))(conv1) # conv2 = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(up1) conv2 = Dropout(0.2)(conv2) conv2 = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(conv2) pool1 = MaxPooling2D(pool_size=(2, 2))(conv2) # conv3 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(pool1) conv3 = Dropout(0.2)(conv3) conv3 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(conv3) pool2 = MaxPooling2D(pool_size=(2, 2))(conv3) # conv4 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(pool2) conv4 = Dropout(0.2)(conv4) conv4 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(conv4) pool3 = MaxPooling2D(pool_size=(2, 2))(conv4) # conv5 = Convolution2D(128, 3, 3, activation='relu', border_mode='same')(pool3) conv5 = Dropout(0.2)(conv5) conv5 = Convolution2D(128, 3, 3, activation='relu', border_mode='same')(conv5) # up2 = merge([UpSampling2D(size=(2, 2))(conv5), conv4], mode='concat', concat_axis=1) conv6 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(up2) conv6 = Dropout(0.2)(conv6) conv6 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(conv6) # up3 = merge([UpSampling2D(size=(2, 2))(conv6), conv3], mode='concat', concat_axis=1) conv7 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(up3) conv7 = Dropout(0.2)(conv7) conv7 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(conv7) # up4 = merge([UpSampling2D(size=(2, 2))(conv7), conv2], mode='concat', concat_axis=1) conv8 = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(up4) conv8 = Dropout(0.2)(conv8) conv8 = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(conv8) # pool4 = MaxPooling2D(pool_size=(2, 2))(conv8) conv9 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(pool4) conv9 = Dropout(0.2)(conv9) conv9 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(conv9) # conv10 = Convolution2D(2, 1, 1, activation='relu', border_mode='same')(conv9) conv10 = core.Reshape((2,patch_height*patch_width))(conv10) conv10 = core.Permute((2,1))(conv10) ############
conv10 = core.Activation('softmax')(conv10) model = Model(input=inputs, output=conv10)
将模型的输入和输出给model函数就会本身组建模型运行图结构
keras.layers.embeddings.Embedding( input_dim, output_dim, embeddings_initializer='uniform',
embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None)
关于embeding做用的详细介绍:http://spaces.ac.cn/archives/4122/
keras.layers.normalization.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True,
scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros',
moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None,
beta_constraint=None, gamma_constraint=None)
该层在每一个batch上将前一层的激活值从新规范化,即便得其输出数据的均值接近0,其标准差接近1
data_format="channels_first
的2D卷积后,通常会设axis=1。
任意,当使用本层为模型首层时,指定input_shape
参数时有意义。
与输入shape相同
plot(model, to_file='./'+name_experiment+'/'+name_experiment + '_model.png')
checkpointer = ModelCheckpoint(filepath='./'+name_experiment+'/'+name_experiment +'_best_weights.h5', verbose=1, monitor='val_loss', mode='auto', save_best_only=True) model.fit(patches_imgs_train, patches_masks_train, epochs=N_epochs, batch_size=batch_size, verbose=1, shuffle=True, validation_split=0.1, callbacks=[checkpointer])
ModelCheckpoint函数能够指定必定训练次数后保存中间训练的最佳参数
ModelCheckpoint函数做为model.fit()函数中回调函数使用
Merge层提供了一系列用于融合两个层或两个张量的层对象和方法。以大写首字母开头的是Layer类,以小写字母开头的是张量的函数。小写字母开头的张量函数在内部其实是调用了大写字母开头的层。
keras.layers.Add()用法
keras.layers.Add()
添加输入列表的图层。
该层接收一个相同shape列表张量,并返回它们的和,shape不变。
import keras input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input2 = keras.layers.Input(shape=(32,)) x2 = keras.layers.Dense(8, activation='relu')(input2) added = keras.layers.Add()([x1, x2]) # equivalent to added = keras.layers.add([x1, x2]) out = keras.layers.Dense(4)(added) model = keras.models.Model(inputs=[input1, input2], outputs=out)
keras.layers.Subtract()用法
keras.layers.Subtract()
两个输入的层相减。
它将大小至少为2,相同Shape的列表张量做为输入,并返回一个张量(输入[0] - 输入[1]),也是相同的Shape。
import keras input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input2 = keras.layers.Input(shape=(32,)) x2 = keras.layers.Dense(8, activation='relu')(input2) # Equivalent to subtracted = keras.layers.subtract([x1, x2]) subtracted = keras.layers.Subtract()([x1, x2]) out = keras.layers.Dense(4)(subtracted) model = keras.models.Model(inputs=[input1, input2], outputs=out)
keras.layers.Multiply()用法
keras.layers.Multiply()
该层接收一个列表的同shape张量,并返回它们的逐元素积的张量,shape不变。
keras.layers.Average()用法
keras.layers.Average()
该层接收一个列表的同shape张量,并返回它们的逐元素均值,shape不变。
keras.layers.Maximum()用法
keras.layers.Maximum()
该层接收一个列表的同shape张量,并返回它们的逐元素最大值,shape不变。
keras.layers.Concatenate(axis=-1)参数
keras.layers.Concatenate(axis=-1)
该层接收一个列表的同shape张量,并返回它们的按照给定轴相接构成的向量。
keras.layers.Dot(axes, normalize=False)参数
keras.layers.Dot(axes, normalize=False)
计算两个tensor中样本的张量乘积。例如,若是两个张量a
和b
的shape都为(batch_size, n),则输出为形如(batch_size,1)的张量,结果张量每一个batch的数据都是a[i,:]和b[i,:]的矩阵(向量)点积。
keras.layers.add(inputs)参数
keras.layers.add(inputs)
Add层的函数式包装
输入列表张量之和
import keras input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input2 = keras.layers.Input(shape=(32,)) x2 = keras.layers.Dense(8, activation='relu')(input2) added = keras.layers.add([x1, x2]) out = keras.layers.Dense(4)(added) model = keras.models.Model(inputs=[input1, input2], outputs=out)
keras.layers.subtract(inputs)参数
keras.layers.subtract(inputs)
Subtract层的函数式包装
输入张量列表的差异
import keras input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input2 = keras.layers.Input(shape=(32,)) x2 = keras.layers.Dense(8, activation='relu')(input2) subtracted = keras.layers.subtract([x1, x2]) out = keras.layers.Dense(4)(subtracted) model = keras.models.Model(inputs=[input1, input2], outputs=out)
keras.layers.multiply(inputs)参数
keras.layers.multiply(inputs)
Multiply的函数式包装
输入列表张量之逐元素积
keras.layers.average(inputs)参数
keras.layers.average(inputs)
Average的函数包装
输入列表张量之逐元素均值
keras.layers.maximum(inputs)参数
keras.layers.maximum(inputs)
Maximum的函数包装
输入列表张量之逐元素均值
keras.layers.concatenate(inputs, axis=-1)参数
keras.layers.concatenate(inputs, axis=-1)
Concatenate的函数包装
keras.layers.dot(inputs, axes, normalize=False)参数
keras.layers.dot(inputs, axes, normalize=False)
Dot的函数包装
keras.layers.core.Activation(activation)
激活层对一个层的输出施加激活函数
任意,当使用激活层做为第一层时,要指定input_shape
与输入shape相同
keras.layers.core.Dropout(rate, noise_shape=None, seed=None)
为输入数据施加Dropout。Dropout将在训练过程当中每次更新参数时按必定几率(rate)随机断开输入神经元,Dropout层用于防止过拟合。
rate:0~1的浮点数,控制须要断开的神经元的比例
noise_shape:整数张量,为将要应用在输入上的二值Dropout mask的shape,例如你的输入为(batch_size, timesteps, features),而且你但愿在各个时间步上的Dropout mask都相同,则可传入noise_shape=(batch_size, 1, features)。
seed:整数,使用的随机数种子
keras.layers.core.Flatten()
Flatten层用来将输入“压平”,即把多维的输入一维化,经常使用在从卷积层到全链接层的过渡。Flatten不影响batch的大小。
model = Sequential() model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 32, 32))) # now: model.output_shape == (None, 64, 32, 32) model.add(Flatten()) # now: model.output_shape == (None, 65536)
keras.layers.core.Reshape(target_shape)
Reshape层用来将输入shape转换为特定的shape
任意,但输入的shape必须固定。当使用该层为模型首层时,须要指定input_shape
参数
(batch_size,)+target_shape
# as first layer in a Sequential model model = Sequential() model.add(Reshape((3, 4), input_shape=(12,))) # now: model.output_shape == (None, 3, 4) # note: `None` is the batch dimension # as intermediate layer in a Sequential model model.add(Reshape((6, 2))) # now: model.output_shape == (None, 6, 2) # also supports shape inference using `-1` as dimension model.add(Reshape((-1, 2, 2))) # now: model.output_shape == (None, 3, 2, 2)
keras.layers.core.Permute(dims)
Permute层将输入的维度按照给定模式进行重排,例如,当须要将RNN和CNN网络链接时,可能会用到该层。
model = Sequential() model.add(Permute((2, 1), input_shape=(10, 64))) # now: model.output_shape == (None, 64, 10) # note: `None` is the batch dimension
任意,当使用激活层做为第一层时,要指定input_shape
与输入相同,可是其维度按照指定的模式从新排列
keras.layers.core.RepeatVector(n)
RepeatVector层将输入重复n次
形如(nb_samples, features)的2D张量
形如(nb_samples, n, features)的3D张量
model = Sequential() model.add(Dense(32, input_dim=32)) # now: model.output_shape == (None, 32) # note: `None` is the batch dimension model.add(RepeatVector(3)) # now: model.output_shape == (None, 3, 32)
keras.layers.core.Lambda(function, output_shape=None, mask=None, arguments=None)
本函数用以对上一层的输出施以任何Theano/TensorFlow表达式
function:要实现的函数,该函数仅接受一个变量,即上一层的输出
output_shape:函数应该返回的值的shape,能够是一个tuple,也能够是一个根据输入shape计算输出shape的函数
mask: 掩膜
arguments:可选,字典,用来记录向函数中传递的其余关键字参数
# add a x -> x^2 layer model.add(Lambda(lambda x: x ** 2))
# add a layer that returns the concatenation # of the positive part of the input and # the opposite of the negative part def antirectifier(x): x -= K.mean(x, axis=1, keepdims=True) x = K.l2_normalize(x, axis=1) pos = K.relu(x) neg = K.relu(-x) return K.concatenate([pos, neg], axis=1) def antirectifier_output_shape(input_shape): shape = list(input_shape) assert len(shape) == 2 # only valid for 2D tensors shape[-1] *= 2 return tuple(shape) model.add(Lambda(antirectifier, output_shape=antirectifier_output_shape))
任意,当使用该层做为第一层时,要指定input_shape
由output_shape
参数指定的输出shape,当使用tensorflow时可自动推断
keras.layers.core.ActivityRegularization(l1=0.0, l2=0.0)
通过本层的数据不会有任何变化,但会基于其激活值更新损失函数值
l1:1范数正则因子(正浮点数)
l2:2范数正则因子(正浮点数)
任意,当使用该层做为第一层时,要指定input_shape
与输入shape相同
keras.layers.core.Masking(mask_value=0.0)
使用给定的值对输入的序列信号进行“屏蔽”,用以定位须要跳过的时间步
对于输入张量的时间步,即输入张量的第1维度(维度从0开始算,见例子),若是输入张量在该时间步上都等于mask_value
,则该时间步将在模型接下来的全部层(只要支持masking)被跳过(屏蔽)。
若是模型接下来的一些层不支持masking,却接受到masking过的数据,则抛出异常。
考虑输入数据x
是一个形如(samples,timesteps,features)的张量,现将其送入LSTM层。由于你缺乏时间步为3和5的信号,因此你但愿将其掩盖。这时候应该:
赋值x[:,3,:] = 0.
,x[:,5,:] = 0.
在LSTM层以前插入mask_value=0.
的Masking
层
model = Sequential() model.add(Masking(mask_value=0., input_shape=(timesteps, features))) model.add(LSTM(32))
参考网址连接:https://keras-cn.readthedocs.io/en/latest/
如有兴趣交流分享技术,可关注本人公众号,里面会不按期的分享各类编程教程,和共享源码,诸如研究分享关于c/c++,python,前端,后端,opencv,halcon,opengl,机器学习深度学习之类有关于基础编程,图像处理和机器视觉开发的知识