tf2.0中有三种主流模型创建方法:顺序式模型创建方法、函数式模型创建方法和子类式模型创建方法;前两者用于创建静态图神经网络模型,最后者用于创建动态图神经网络模型。
该方法使用 tf.keras.models.Sequential() 创建仅由顺序连接的单层堆栈组成的简单神经网络模型,Sequential() 中输入神经网络层定义数组。如下所示:
import tensorflow as tf
tf.keras.models.Sequential([
tf.keras.layers.InputLayer((28, 28)),
tf.keras.layers.Dense(300, activation='relu'),
tf.keras.layers.Dense(200, activation='relu'),
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
函数式创建方法,可以帮我们创建具有分支结构、多个输入或多个输出的神经网络。
import tensorflow as tf
from tensorflow.keras from layers
input_ = layers.Input((28,28))
hidden1 = layers.Dense(30, activation='relu', name='hidden1')(input_)
hidden2 = layers.Dense(30, activation='relu', name='hidden2')(hidden1)
hidden3 = layers.Dense(30, activation='relu', name='hidden3')(hidden2)
hidden4 = layers.Dense(30, activation='relu', name='hidden4')(input_)
concat = layers.Concatenate()([input_, hidden3, hidden4])
output = layers.Dense(1, activation='sigmoid')(concat)
model = tf.keras.Model(inputs=[input_], outputs=[output])
model.summary()
import tensorflow as tf
from tensorflow.keras from layers
input_A = layers.Input((10, 10), name='inputA')
input_B = layers.Input((15,15), name='inputB')
hidden1 = layers.Dense(30, activation='relu', name='hidden1')(input_A)
hidden2 = layers.Dense(30, activation='relu', name='hidden2')(hidden1)
concat = layers.Concatenate()([input_A, hidden2])
output = layers.Dense(1, activation='sigmoid')(concat)
model = tf.keras.Model(inputs=[input_A, input_B], outputs=[output])
model.summary()
# 模型训练
X_train = {'inputA': X_train_A, 'inputB': X_train_B}
model.fit(X_train, y_train)
import tensorflow as tf
from tensorflow.keras from layers
input_A = layers.Input((10, 10), name='inputA')
input_B = layers.Input((15,15), name='inputB')
hidden1 = layers.Dense(30, activation='relu', name='hidden1')(input_A)
hidden2 = layers.Dense(30, activation='relu', name='hidden2')(hidden1)
concat = layers.Concatenate()([input_A, hidden2])
output_1 = layers.Dense(1, activation='sigmoid')(concat)
output_2 = layers.Dense(1, activation='sigmoid')(hidden2)
model = tf.keras.Model(inputs=[input_A, input_B], outputs=[output_1, output_2])
model.summary()
# 模型训练
X_train = {'inputA': X_train_A, 'inputB': X_train_B}
y_train = {'output_1': y_train_1, 'output_2': y_train_2}
model.fit(X_train, y_train)
涉及循环、变化的形状、条件分支和其他动态行为时,可使用本方法构造动态图神经网络模型。子类式创建方法,只需对tf.keras.Model类进行子类化,并在构造函数中创建所需的层,然后再 call() 方法中执行所需的计算即可。