tf.keras.Sequential 模型只适用于多层简单堆叠网络,不能表示复杂模型。
使用 Keras functional API 可以构建有复杂拓扑结构的模型。比如:
使用函数式API构建模型要求:
示例:
登录后复制
from __future__ import absolute_import, division, print_functionimport tensorflow as tfimport numpy as
npfrom tensorflow.keras import layerstrain_x = np.random.random((1000, 72))train_y = np
.random.random((1000, 10))val_x = np.random.random((200, 72))val_y = np.random.random((200, 10))
input_x = tf.keras.Input(shape=(72,)) # 实例化Keras张量hidden1 = layers.Dense(32, activation='relu')
(input_x)hidden2 = layers.Dense(16, activation='relu')(hidden1)pred = layers.Dense(10,
activation='softmax')(hidden2)model = tf.keras.Model(inputs=input_x,
outputs=pred)model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
loss=tf.keras.losses.categorical_crossentropy,
metrics=['accuracy'])model.fit(train_x, train_y, batch_size=32,
epochs=5)1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.
登录后复制
from __future__ import absolute_import, division, print_functionimport tensorflow as tfimport numpy as
npfrom tensorflow.keras import layersclass MyModel(tf.keras.Model): def __init__(self, num_classes=10):
super(MyModel, self).__init__(name='my_model') self.num_classes = num_classes
self.layer1 = layers.Dense(32, activation='relu') self.layer2 = layers.Dense(num_classes,
activation='softmax') def call(self, inputs): h1 = self.layer1(inputs)
out = self.layer2(h1) return out def compute_output_shape(self, input_shape):
shape = tf.TensorShape(input_shape).as_list() shape[-1] = self.num_classes
return tf.TensorShape(shape)model = MyModel(num_classes=10)model.compile(optimizer=tf.keras.optimizers.
RMSprop(0.001), loss=tf.keras.losses.categorical_crossentropy,
metrics=['accuracy'])train_x = np.random.random((1000, 72))train_y = np.random.random((1000, 10))model
.fit(train_x, train_y, batch_size=16, epochs=5)1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.
22.23.24.25.26.27.28.29.30.31.
通过对 tf.keras.layers.Layer 进行子类化并通过下面方法创建自定义层:
from __future__ import absolute_import, division, print_functionimport tensorflow as tfimport numpy as
npimport tensorflow.keras as kerasfrom tensorflow.keras import layersclass
MyLayer(keras.layers.Layer): def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape): shape = tf.TensorShape((input_shape[1], self.output_dim))
# Create a trainable weight variable for this layer.
self.kernel = self.add_weight(name='kernel',
shape=shape, initializer='uniform',
trainable=True) # Be sure to call this at the end
super(MyLayer, self).build(input_shape) def call(self, inputs):
return tf.matmul(inputs, self.kernel) def compute_output_shape(self, input_shape):
shape = tf.TensorShape(input_shape).as_list() shape[-1] = self.output_dim
return tf.TensorShape(shape) def get_config(self):
base_config = super(MyLayer, self).get_config() base_config['output_dim'] = self.output_dim
return base_config @classmethod def from_config(cls, config):
return cls(**config)# Create a model using the custom layermodel = keras.Sequential([MyLayer(10),
keras.layers.Activation('softmax')])# The compile step specifies the training configurationmodel.
compile(optimizer=tf.compat.v1.train.RMSPropOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])train_x = np.random.random((1000, 72))train_y = np.random.random((1000, 10))
# Trains for 5 epochs.model.fit(train_x, train_y, batch_size=32, epochs=5)1.2.3.4.5.6.7.8.9.10.11.12.13.14.
15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.
51.52.53.54.
回调用于在训练期间自定义和扩展其行为。 可以编写自己的自定义回调或使用包含以下内置的tf.keras.callbacks:
使用回调是将其传递给模型的fit方法:
登录后复制
callbacks = [ # Interrupt training if `val_loss` stops improving for over 2 epochs
keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
# Write TensorBoard logs to `./logs` directory keras.callbacks.TensorBoard(log_dir='./logs')]1.2.3.4.5.6.
示例:
登录后复制
callbacks = [ tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
tf.keras.callbacks.TensorBoard(log_dir='./logs')]model.fit(train_x, train_y, batch_size=16, epochs=5,
callbacks=callbacks, validation_data=(val_x, val_y))1.2.3.4.5.6.
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删