函数式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