logo

TensorFlow 模型构建

wangzf / 2022-07-15


目录

使用 Keras 接口有以下 3 种方式构建模型:

模型共有的方法和属性

from tf.keras.model import Model
from tf.keras.model import model_from_json, model_from_yaml

Sequential API

Sequential 模型是层(layers)的线性堆叠

from tensorflow import keras
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist

# data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# model
model = models.Sequential()
model.add(layers.Dense(units = 64, activation = "relu"))
model.add(layers.Dense(units = 10, activation = "softmax"))
model.compile(
   loss = "categorical_crossentropy",
   optimizer = "sgd",
   metrics = ["accuracy"]
)
model.fit(x_train, y_train, epochs = 5, batch_size = 32)
loss_and_metrics = model.evaluate(x_test, y_test, batch_size = 128)
classes = model.predict(x_test, batch_size = 128)

Functional API

函数式 API 特点

inputs = tf.keras.Input(shape = (28, 28, 1))
x = tf.keras.layers.Flatten()(inputs)
x = tf.keras.layers.Dense(units = 100, activation = tf.nn.relu)(x)
x = tf.keras.layers.Dense(units = 10)(x)
outputs = tf.keras.layers.Softmax()(x)
model = tf.keras.Model(inputs = inputs, outputs = outputs)

Subclassing API

import tensorflow as tf

class MyModel(tf.keras.Model):
    
    def __init__(self):
        super(MyModel, self).__init__()
        
        # 此处添加初始化的代码(包含call方法中会用到的层)例如:
        self.layer1 = tf.keras.layers.BuildInLayer()
        self.layer2 = MyCustomLayer(...)

    def call(self, input):
        # 此处添加模型调用的代码(处理输入并返回输出), 例如:
        x = layer1(input)
        self.output = layer2(x)
        return output

model = MyModel()

with tf.GradientTape() as tape:
    logits = model(images)
    loss_value = loss(logits, labels)
grads = tape.gradient(loss_value, model.trainable_variables)
optimizer.apply(zip(grads, model.trainable_variables))

回调函数-Callbacks

回调函数API:

创建回调函数:

from keras.layers import Dense, Activation
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint

# 模型建立
model = Sequenital()
model.add(Dense(10, input_dim = 784, kernel_initializer = "uniform"))
model.add(Activation("softmax"))

# 模型编译
model.compile(loss = "categorical_crossentropy", optimizer = "rmsporp")

# 模型训练
# 在训练时, 保存批量损失值
class LossHistory(keras.callbacks.Callback):
      def on_train_begin(self, logs = {}):
         self.losses = []

      def on_batch_end(self, batch, logs = {}):
         self.losses.append(logs.get("loss"))
history = LossHistory()

# 如果验证集损失下降, 在每个训练 epoch 后保存模型
checkpointer = ModelCheckpoint(filepath = "/tmp/weight.hdf5",
                               verbose = 1,
                               save_best_only = True)
model.fit(x_train, 
         y_train, 
         batch_size = 128, 
         epochs = 20, 
         verbose = 0,
         validation_data = (x_test, y_test), 
         callbacks = [history, checkpointer]
)

# 模型结果输出
print(history.losses)