Keras工具库详解(三)

3.Keras函数式模型使用详解

Keras函数式模型是用户定义多输出模型、非循环有向模型或具有共享层的模型等复杂模型的途径。一句话,只要你的模型不是类似VGG一样一条路走到黑的模型,或者你的模型需要多于一个的输出,那么你总应该选择函数式模型。函数式模型是最广泛的一类模型,序贯模型只是函数式模型的一种特殊情况。
由于序贯模型是特殊情况那下面我们由简单的序贯模型开始,看函数式模型如何完成全连接网络

from keras.layers import Input, Dense#输入层,稠密层
from keras.models import Model

# This returns a tensor构建输入层
inputs = Input(shape=(784,))

#把输入送给下一层
# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)
#把上层X送给下层得到X
x = Dense(64, activation='relu')(x)
#把X送给激活函数得到预测值
predictions = Dense(10, activation='softmax')(x)

#把操作的头与尾给到model
# This creates a model that includes
# the Input layer and three Dense layers
model = Model(inputs=inputs, outputs=predictions)
#编译
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
#开始训练
model.fit(data, labels)  # starts training

多输入多输出情况
使用函数式模型的一个典型场景是搭建多输入、多输出的模型。举个例子我们希望预测Twitter上一条新闻会被转发和点赞多少次。模型的主要输入是新闻本身,也就是一个词语的序列。但我们还可以拥有额外的输入,如新闻发布的日期等。这个模型的损失函数将由两部分组成,辅助的损失函数评估仅仅基于新闻本身做出预测的情况,主损失函数评估基于新闻和额外信息的预测的情况,即使来自主损失函数的梯度发生弥散,来自辅助损失函数的信息也能够训练Embeddding和LSTM层。在模型中早点使用主要的损失函数是对于深度网络的一个良好的正则方法。总而言之,该模型框图如下:
在这里插入图片描述
让我们用函数式模型来实现这个框图主要的输入接收新闻本身,即一个整数的序列(每个整数编码了一个词)。这些整数位于1到10,000之间(即我们的字典有10,000个词)。这个序列有100个单词。如下面代码完成从

main_input(InputLayer)到lstm_1(LSTM)模块构建
from keras.layers import Input, Embedding, LSTM, Dense 
from keras.models import Model 
main_input = Input(shape=(100,), dtype='int32', name='main_input')
x=Embedding(output_dim=512,input_dim=10000,input_length=100)(main_input)
lstm_out = LSTM(32)(x)

然后,我们插入一个额外的损失,使得即使在主损失很高的情况下,LSTM和Embedding层也可以平滑的训练。也就是完成aux_output(Dense)模块构建

auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)

再然后增加额外的输入,我们将LSTM与额外的输入数据串联起来组成输入,送入模型中

auxiliary_input=Input(shape=(5,),name='aux_input')
x = keras.layers.concatenate([lstm_out, auxiliary_input])
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
main_output = Dense(1, activation='sigmoid', name='main_output')(x)

最后,我们定义整个2输入,2输出的模型:

model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])

模型定义完毕,下一步编译模型。我们给额外的损失赋0.2的权重。我们可以通过关键字参数loss_weights或loss来为不同的输出设置不同的损失函数或权值。这两个参数均可为Python的列表或字典。

model.compile(optimizer='rmsprop', loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'}, loss_weights={'main_output': 1., 'aux_output': 0.2})

传递训练数据和目标值训练给该模型

model.fit({'main_input': headline_data, 'aux_input': additional_data}, {'main_output': labels, 'aux_output': labels}, epochs=50, batch_size=32)

猜你喜欢

转载自blog.csdn.net/Dulpee/article/details/84890532