三种建模方法
Sequential方法 顺序模型 函数模型 子类化模型
函数式API方法
Model子类化自定义模型
一、Sequential model
#第一种Sequential model、
from tensorflow.keras import layers
import tensorflow as tf
model = tf.keras.Sequential()
model.add(layers.Dense(64, activation='relu')) #第一层
model.add(layers.Dense(64, activation='relu')) #第二层
model.add(layers.Dense(10)) #第三层
#可以继续添加
#第二种
model = tf.keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(32,)), #第一层
layers.Dense(64, activation='relu'), #第二层
layers.Dense(10) #第三层
#可以继续添加
])
#
model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
import numpy as np
data = np.random.random((1000,32))
labels = np.random.random((1000,10))
#模型训练
model.fit(data, labels, epochs=10, batch_size=32)
二、Functional model
函数式模型是一种创建模型的方法,该模型比tf.keras.Sequential更灵活。函数式模型可以处理具有非线性拓扑的模型,具有共享层的模型以及具有多个输入或输出的模型等等
深度学习模型通常是层的有向无环图(DAG)的主要思想。因此,函数式模型是一种构建层图的方法。
举个例子: “”" (input: 32-dimensional vectors)
↧ [Dense (64 units, relu activation)]
↧ [Dense (64 units, relu activation)]
↧ [Dense (10 units, softmax activation)]
↧ (output: logits of a probability distribution over 10 classes) “”"
inputs = tf.keras.Input(shape=(32,))
x = layers.Dense(64, activation='relu')(inputs) #第一层
x = layers.Dense(64, activation='relu')(x) #第二层
predictions = layers.Dense(10)(x) #第三层
model = tf.keras.Model(inputs=inputs, outputs=predictions)
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
import tensorflow as tf
data = np.random.random((1000,32))
labels = np.random.random((1000,10))
model.fit(data, labels, batch_size=1, epochs=5)
模型子类化
通过子类化tf.keras.Model和定义自己的前向传播模型来构建完全可定制的模型。和eager execution模式相辅相成。