keras的模型学习笔记——函数模型

作者: gaoshine | 来源:发表于2017-09-18 16:32 被阅读950次

函数式(Functional)模型

Keras函数式模型接口是用户定义多输出模型、非循环有向模型或具有共享层的模型等复杂模型的途径。一句话,只要你的模型不是类似VGG一样一条路走到黑的模型,或者你的模型需要多于一个的输出,那么你总应该选择函数式模型。函数式模型是最广泛的一类模型,序贯模型(Sequential)只是它的一种特殊情况。

俺滴偶像

第一个模型:全连接网络

from keras.layers import Dense, Activation, Input
from keras.models import Model

Input是一个输入层,需要有shape的张量

inputs = Input(shape=(784,))

输入一个张量,返回一个张量

x = Dense(64, activation='relu')(inputs)
x = Dense(64,activation='relu')(x)
predictions = Dense(10,activation='softmax')(x)

生成一个函数型模型包括 输入层和三个全连接层

model = Model(inputs=inputs, outputs=predictions)

编译模型(和seqential模型一样)

model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])

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

Layer (type) Output Shape Param #

input_1 (InputLayer) (None, 784) 0


dense_9 (Dense) (None, 64) 50240


dense_10 (Dense) (None, 64) 4160


dense_11 (Dense) (None, 10) 650

Total params: 55,050
Trainable params: 55,050
Non-trainable params: 0


模型

多输入和多输出模型

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

考虑这样一个模型。我们希望预测微博上一条新闻会被转发和点赞多少次。模型的主要输入是新闻本身,也就是一个词语的序列。但我们还可以拥有额外的输入,如新闻发布的日期等。这个模型的损失函数将由两部分组成,辅助的损失函数评估仅仅基于新闻本身做出预测的情况,主损失函数评估基于新闻和额外信息的预测的情况,即使来自主损失函数的梯度发生弥散,来自辅助损失函数的信息也能够训练Embeddding和LSTM层。在模型中早点使用主要的损失函数是对于深度网络的一个良好的正则方法。

from keras.layers import Input, Embedding, LSTM, Dense,concatenate
from keras.models import Model

from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
import pandas as pd
import matplotlib.pyplot as plt


# Headline input: meant to receive sequences of 100 integers, between 1 and 10000.
# Note that we can name any layer by passing it a "name" argument.
main_input = Input(shape=(100,), dtype='int32', name='main_input')

# This embedding layer will encode the input sequence
# into a sequence of dense 512-dimensional vectors.
x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input)

# A LSTM will transform the vector sequence into a single vector,
# containing information about the entire sequence
lstm_out = LSTM(32)(x)

# 插入一个额外的损失,使得即使在主损失很高的情况下,LSTM和Embedding层也可以平滑的训练。
auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)

# 再然后,我们将LSTM与额外的输入数据串联起来组成输入,送入模型中:
auxiliary_input = Input(shape=(5,), name='aux_input')
x = concatenate([lstm_out, auxiliary_input])

# We stack a deep densely-connected network on top
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)

# And finally we add the main logistic regression layer
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的列表或字典。这里我们给loss传递单个损失函数,这个损失函数会被应用于所有输出上。
model.compile(optimizer='rmsprop', loss='binary_crossentropy',
              loss_weights=[1., 0.2])

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

# 编译完成后,我们通过传递训练数据和目标值训练该模型:

# model.fit([headline_data, additional_data], [labels, labels],epochs=50, batch_size=32)



Layer (type) Output Shape Param # Connected to

main_input (InputLayer) (None, 100) 0


embedding_3 (Embedding) (None, 100, 512) 5120000 main_input[0][0]


lstm_3 (LSTM) (None, 32) 69760 embedding_3[0][0]


aux_input (InputLayer) (None, 5) 0


concatenate_3 (Concatenate) (None, 37) 0 lstm_3[0][0]
aux_input[0][0]


dense_12 (Dense) (None, 64) 2432 concatenate_3[0][0]


dense_13 (Dense) (None, 64) 4160 dense_12[0][0]


dense_14 (Dense) (None, 64) 4160 dense_13[0][0]


main_output (Dense) (None, 1) 65 dense_14[0][0]


aux_output (Dense) (None, 1) 33 lstm_3[0][0]

Total params: 5,200,610
Trainable params: 5,200,610
Non-trainable params: 0


微博处理模型

相关文章

  • keras的模型学习笔记——函数模型

    函数式(Functional)模型 Keras函数式模型接口是用户定义多输出模型、非循环有向模型或具有共享层的模型...

  • keras模型

    Keras有两种类型的模型,序贯模型(Sequential)和函数式模型(Model),函数式模型应用更为广泛,序...

  • Keras入门--Apple的学习笔记

    Keras有两种类型的模型,序贯模型(Sequential)和函数式模型(Model),函数式模型应用更为广泛,序...

  • 构建高级模型(05)

    函数式 API tf.keras.Sequential 模型是层的简单堆叠,无法表示任意模型。使用 Keras 函...

  • 自动部署深度神经网络模型TensorFlow(Keras)到生产

    目录 Keras简介 Keras模型分类 Keras模型部署准备 默认部署Keras模型 自定义部署Keras模型...

  • Keras

    官方文档 模型 Sequential序贯模型,序贯模型是函数式模型的简略版。Keras实现了很多层,包括core核...

  • keras

    Keras设计了俩种构建模型的方式函数式模型API和顺序式模型API 顺序式模型API构建模型示例: from k...

  • Keras函数式 API

    Keras 函数式 API 是定义复杂模型(如多输出模型、有向无环图,或具有共享层的模型)的方法。 非函数式api...

  • Keras 实现 precision、recall、f1

    使用 Keras 实现 precision、recall、f1 函数定义如下: 在 Keras 网络模型使用方式:...

  • keras:f1_score作为metric,存储模型, 加载带

    本文主要关于如何存储预测模型,加载带有自定义函数的模型。 存储预测模型 在keras.callbacks 包下有个...

网友评论

    本文标题:keras的模型学习笔记——函数模型

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