本文摘自 http://keras-cn.readthedocs.io/en/latest/layers/about_layer/,链接异常请阅读原文查看
常用层对应于core模块,core内部定义了一系列常用的网络层,包括全连接、激活层等
为什么叫“泛型模型”,请查看一些基本概念
Keras的泛型模型为Model
,即广义的拥有输入和输出的模型,我们使用Model
来初始化一个泛型模型
from keras.models import Modelfrom keras.layers import Input, Dense
a = Input(shape=(32,))
b = Dense(32)(a)
model = Model(input=a, output=b)
在这里,我们的模型以a
为输入,以b
为输出,同样我们可以构造拥有多输入和多输出的模型
model = Model(input=[a1, a2], output=[b1, b3, b3])
model.layers
:组成模型图的各个层model.inputs
:模型的输入张量列表model.outputs
:模型的输出张量列表compile(self, optimizer, loss, metrics=[], loss_weights=None, sample_weight_mode=None)
本函数编译模型以供训练,参数有
metrics=['accuracy']
如果要在多输出模型中为不同的输出指定不同的指标,可像该参数传递一个字典,例如metrics={'ouput_a': 'accuracy'}
fit
函数的解释中有相关的参考内容。【Tips】如果你只是载入模型并利用其predict,可以不用进行compile。在Keras中,compile主要完成损失函数和优化器的一些配置,是为训练服务的。predict会在内部进行符号函数的编译工作(通过调用_make_predict_function生成函数)【@白菜,@我是小将】
fit(self, x, y, batch_size=32, nb_epoch=10, verbose=1, callbacks=[], validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None)
本函数用以训练模型,参数有:
sample_weight_mode='temporal'
。fit
函数返回一个History
的对象,其History.history
属性记录了损失函数和其他指标的数值随epoch变化的情况,如果有验证集的话,也包含了验证集的这些指标变化情况
evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None)
本函数按batch计算在某些输入数据上模型的误差,其参数有:
fit
一样,是numpy array或numpy array的listfit
的同名参数fit
的同名参数,但只能取0或1fit
的同名参数本函数返回一个测试误差的标量值(如果模型没有其他评价指标),或一个标量的list(如果模型还有其他的评价指标)。model.metrics_names
将给出list中各个值的含义。
如果没有特殊说明,以下函数的参数均保持与fit
的同名参数相同的含义
如果没有特殊说明,以下函数的verbose参数(如果有)均只能取0或1
predict(self, x, batch_size=32, verbose=0)
本函数按batch获得输入数据对应的输出,其参数有:
函数的返回值是预测值的numpy array
train_on_batch(self, x, y, class_weight=None, sample_weight=None)
本函数在一个batch的数据上进行一次参数更新
函数返回训练误差的标量值或标量值的list,与evaluate的情形相同。
test_on_batch(self, x, y, sample_weight=None)
本函数在一个batch的样本上对模型进行评估
函数的返回与evaluate的情形相同
predict_on_batch(self, x)
本函数在一个batch的样本上对模型进行测试
函数返回模型在一个batch上的预测结果
fit_generator(self, generator, samples_per_epoch, nb_epoch, verbose=1, callbacks=[], validation_data=None, nb_val_samples=None, class_weight={}, max_q_size=10)
利用Python的生成器,逐个生成数据的batch并进行训练。生成器与模型将并行执行以提高效率。例如,该函数允许我们在CPU上进行实时的数据提升,同时在GPU上进行模型训练
函数的参数是:
samples_per_epoch
时,记一个epoch结束validation_data
是生成器时使用,用以限制在每个epoch结束时用来验证模型的验证集样本数,功能类似于samples_per_epoch
函数返回一个History
对象
例子
def generate_arrays_from_file(path):
while 1:
f = open(path) for line in f: # create numpy arrays of input data
# and labels, from each line in the file
x, y = process_line(line) yield (x, y)
f.close()
model.fit_generator(generate_arrays_from_file('/my_file.txt'),
samples_per_epoch=10000, nb_epoch=10)
evaluate_generator(self, generator, val_samples, max_q_size=10)
本函数使用一个生成器作为数据源,来评估模型,生成器应返回与test_on_batch
的输入数据相同类型的数据。
函数的参数是:
predict_generator(self, generator, val_samples, max_q_size=10, nb_worker=1, pickle_safe=False)
从一个生成器上获取数据并进行预测,生成器应返回与predict_on_batch
输入类似的数据
函数的参数是:
get_layer(self, name=None, index=None)
本函数依据模型中层的下标或名字获得层对象,泛型模型中层的下标依据自底向上,水平遍历的顺序。
函数的返回值是层对象
所有的Keras层对象都有如下方法:
layer.get_weights()
:返回层的权重(numpy array)layer.set_weights(weights)
:从numpy array中将权重加载到该层中,要求numpy array的形状与* layer.get_weights()
的形状相同layer.get_config()
:返回当前层配置信息的字典,层也可以借由配置信息重构from keras.utils.layer_utils import layer_from_config
config = layer.get_config()
layer = layer_from_config(config)
如果层仅有一个计算节点(即该层不是共享层),则可以通过下列方法获得输入张量、输出张量、输入数据的形状和输出数据的形状:
layer.input
layer.output
layer.input_shape
layer.output_shape
如果该层有多个计算节点(参考层计算节点和共享层)。可以使用下面的方法
layer.get_input_at(node_index)
layer.get_output_at(node_index)
layer.get_input_shape_at(node_index)
layer.get_output_shape_at(node_index)
常用层对应于core模块,core内部定义了一系列常用的网络层,包括全连接、激活层等
keras.layers.core.Dense(output_dim, init='glorot_uniform', activation='linear', weights=None, W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, input_dim=None)
Dense就是常用的全连接层,这里是一个使用示例:
# as first layer in a sequential model:model = Sequential()
model.add(Dense(32, input_dim=16))# now the model will take as input arrays of shape (*, 16)# and output arrays of shape (*, 32)# this is equivalent to the above:model = Sequential()
model.add(Dense(32, input_shape=(16,)))# after the first layer, you don't need to specify# the size of the input anymore:model.add(Dense(32))
weights
参数时才有意义。input_shape
参数。形如(nb_samples, input_dim)的2D张量
形如 (nb_samples, output_dim)的2D张量
keras.layers.core.Activation(activation)
激活层对一个层的输出施加激活函数
任意,当使用激活层作为第一层时,要指定input_shape
与输入shape相同
keras.layers.core.Dropout(p)
为输入数据施加Dropout。Dropout将在训练过程中每次更新参数时随机断开一定百分比(p)的输入神经元连接,Dropout层用于防止过拟合。
keras.layers.core.SpatialDropout2D(p, dim_ordering='default')
SpatialDropout2D与Dropout的作用类似,但它断开的是整个2D特征图,而不是单个神经元。如果一张特征图的相邻像素之间有很强的相关性(通常发生在低层的卷积层中),那么普通的dropout无法正则化其输出,否则就会导致明显的学习率下降。这种情况下,SpatialDropout2D能够帮助提高特征图之间的独立性,应该用其取代普通的Dropout
~/.keras/keras.json
配置的image_dim_ordering
值‘th’模式下,输入形如(samples,channels,rows,cols)的4D张量
‘tf’模式下,输入形如(samples,rows,cols,channels)的4D张量
注意这里的输入shape指的是函数内部实现的输入shape,而非函数接口应指定的input_shape
,请参考下面提供的例子。
与输入相同
keras.layers.core.SpatialDropout3D(p, dim_ordering='default')
SpatialDropout3D与Dropout的作用类似,但它断开的是整个3D特征图,而不是单个神经元。如果一张特征图的相邻像素之间有很强的相关性(通常发生在低层的卷积层中),那么普通的dropout无法正则化其输出,否则就会导致明显的学习率下降。这种情况下,SpatialDropout2D能够帮助提高特征图之间的独立性,应该用其取代普通的Dropout
~/.keras/keras.json
配置的image_dim_ordering
值‘th’模式下,输入应为形如(samples,channels,input_dim1,input_dim2, input_dim3)的5D张量
‘tf’模式下,输入应为形如(samples,input_dim1,input_dim2, input_dim3,channels)的5D张量
与输入相同
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 modelmodel = 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 modelmodel.add(Reshape((6, 2)))# now: model.output_shape == (None, 6, 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 dimensionmodel.add(RepeatVector(3))# now: model.output_shape == (None, 3, 32)
keras.engine.topology.Merge(layers=None, mode='sum', concat_axis=-1, dot_axes=-1, output_shape=None, node_indices=None, tensor_indices=None, name=None)
Merge层根据给定的模式,将一个张量列表中的若干张量合并为一个单独的张量
mode=concat
时指定需要串联的轴mode=dot
时,指定要消去的轴model1 = Sequential()
model1.add(Dense(32))
model2 = Sequential()
model2.add(Dense(32))
merged_model = Sequential()
merged_model.add(Merge([model1, model2], mode='concat', concat_axis=1)
- ____TODO__: would this actually work? it needs to.__# achieve this with get_source_inputs in Sequential.
keras.layers.core.Lambda(function, output_shape=None, arguments={})
本函数用以对上一层的输入实现任何Theano/TensorFlow表达式
# add a x -> x^2 layermodel.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 partdef 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
keras.layers.core.ActivityRegularization(l1=0.0, l2=0.0)
经过本层的数据不会有任何变化,但会基于其激活值更新损失函数值
任意,当使用该层作为第一层时,要指定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.
mask_value=0.
的Masking
层model = Sequential()
model.add(Masking(mask_value=0., input_shape=(timesteps, features)))
model.add(LSTM(32))
keras.layers.core.Highway(init='glorot_uniform', transform_bias=-2, activation='linear', weights=None, W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, input_dim=None)
Highway层建立全连接的Highway网络,这是LSTM在前馈神经网络中的推广
weights
参数时有意义。input_shape
参数。形如(nb_samples, input_dim)的2D张量
形如(nb_samples, output_dim)的2D张量
全连接的Maxout层
MaxoutDense
层以nb_features
个Dense(input_dim,output_dim)
线性层的输出的最大值为输出。MaxoutDense
可对输入学习出一个凸的、分段线性的激活函数。
形如(nb_samples, input_dim)的2D张量
形如(nb_samples, output_dim)的2D张量
Maxout Networks
keras.layers.core.TimeDistributedDense(output_dim, init='glorot_uniform', activation='linear', weights=None, W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, input_dim=None, input_length=None)
为输入序列的每个时间步信号(即维度1)建立一个全连接层,当RNN网络设置为return_sequence=True
时尤其有用
TImeDistributed
完成此功能model.add(TimeDistributed(Dense(32)))
weights
参数时有意义。input_shape
参数。形如 (nb_sample, time_dimension, input_dim)
的3D张量
形如 (nb_sample, time_dimension, output_dim)
的3D张量