使用Functional Api构造简洁的keras模型

本文介绍了如何使用Keras的Functional API创建复杂的模型,包括multi-input/output模型、共享层和自定义Layer。通过示例展示了残差网络、共享层和VGG19的节点复用。此外,还讨论了Functional API与Model subclassing的混合使用,以及模型的保存和序列化。
摘要由CSDN通过智能技术生成

函数式api是什么

一种创建keras模型的方式,可以很简洁的实现layer共享、multi-input、multi-output模型。本文主要内容来自官方示例

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

inputs = keras.Input(shape=(784,))
x = layers.Dense(64, activation="relu")(inputs)
x = layers.Dense(64, activation="relu")(x)
outputs = layers.Dense(10)(x)
model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model")
model.summary()

在这里插入图片描述
对于train、evaluate、inference过程,keras.Model内置了fit和evaluate方法,用户也可以自行设计
keras.Model模型的保存非常简单:

model.save("path_to_my_model")
del model
# Recreate the exact same model purely from the file:
model = keras.models.load_model("path_to_my_model")

被储存的内容有:

  • 模型结构
  • 权重
  • training config:model在compile后调用save会存储
  • optimizer and its state:上次训练停止时的优化器的状态

keras.Model是callable的

官方示例:

def get_model():
    inputs = keras.Input(shape=(128,))
    outputs = layers.Dense(1)(inputs)
    return keras.Model(inputs, outputs)


model1 = get_model()
model2 = get_model()
model3 = get_model()

inputs = keras.Input(shape=(128,))
y1 = model1(inputs)
y2 = model2(inputs)
y3 = model3(inputs)
outputs = layers.average([y1, y2, y3])
ensemble_model = keras.Model(inputs=inputs, outputs=outputs)

multi-input/output模型

使用keras.Model很容易实现此类模型:

  • 三个输入:title_input, boy_input, tags_input
  • title和body先经embedding层,将每个word映射为高维向量
  • title和body的向量序列分别经LSTM得到两个向量title_features ,body_features
  • 拼接title_features,body_features,tags_input得到一个向量
  • 投影两次得到两个输出priority_pred、department_pred
  • model = keras.Model(inputs=[title_input, body_input, tags_input],outputs=[priority_pred, department_pred],)
num_tags = 12  # Number of unique issue tags
num_words = 10000  # Size of vocabulary obtained when preprocessing text data
num_departments = 4  # Number of departments for predictions

title_input = keras.Input(
    shape=(None,), name="title"
)  # Variable-length sequence of ints
body_input = keras.Input(shape=(None,), name="body")  # Variable-length sequence of ints
tags_input = keras.Input(
    shape=(num_tags,), name="tags"
)  # Binary vectors of size `num_tags`

# Embed each word in the title into a 64-dimensional vector
title_features = layers.Embedding(num_words, 64)(title_input)
# Embed each word in the text into a 64-dimensional vector
body_features = layers.Embedding
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值