tensorflow 2.0 keras高层接口 之 API-metrics&compile&fit

7.1 keras高层API

  • Keras
  • metrics
    • 完整代码
  • compile & fit
    • 完整代码

Keras

这里说的 Keras 指的是 tf.keras。
实际上 Keras 是高层的 wrapper。

使用的 keras 主要是用其五个功能。

  1. datasets
  2. layers
  3. losses
  4. metrics
  5. optimizers

metrics

事实上此 API 没有方便很多,可以自己实现
记录 loss 与 accuracy ,做平均。 功能为 metrics。

使用步骤:

  1. Metrics 新建测量池
acc_meter = metrics.Accuracy()

loss_meter = metrics.Mean()
  1. update_state 添加数据
acc_meter.update_state(y, pred)

loss_meter.update_state(loss)
  1. result().numpy() 得到结果
acc_meter.result().numpy()

loss_meter.result().numpy()
  1. reset_states 清零 上个时间戳的数据就不会被记录进来
acc_meter.reset_states()

loss_meter.reset_states()

完整代码

import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import os

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'


def preprocess(x, y):
    x = tf.cast(x, dtype=tf.float32) / 255.
    y = tf.cast(y, dtype=tf.int32)

    return x, y


batchsz = 128
(x, y), (x_val, y_val) = datasets.mnist.load_data()
print('datasets:', x.shape, y.shape, x.min(), x.max())

db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(60000).batch(batchsz).repeat(10)

ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz)

network = Sequential([layers.Dense(256, activation='relu'),
                      layers.Dense(128, activation='relu'),
                      layers.Dense(64, activation='relu'),
                      layers.Dense(32, activation='relu'),
                      layers.Dense(10)])
network.build(input_shape=(None, 28 * 28))
network.summary()

optimizer = optimizers.Adam(lr=0.01)

acc_meter = metrics.Accuracy()
loss_meter = metrics.Mean()

for step, (x, y) in enumerate(db):

    with tf.GradientTape() as tape:
        # [b, 28, 28] => [b, 784]
        x = tf.reshape(x, (-1, 28 * 28))
        # [b, 784] => [b, 10]
        out = network(x)
        # [b] => [b, 10]
        y_onehot = tf.one_hot(y, depth=10)
        # [b]
        loss = tf.reduce_mean(
            tf.losses.categorical_crossentropy(
                y_onehot, out, from_logits=True))

        loss_meter.update_state(loss)

    grads = tape.gradient(loss, network.trainable_variables)
    optimizer.apply_gradients(zip(grads, network.trainable_variables))

    if step % 100 == 0:
        print(step, 'loss:', loss_meter.result().numpy())
        loss_meter.reset_states()

    # evaluate
    if step % 500 == 0:
        total, total_correct = 0., 0
        acc_meter.reset_states()

        for step, (x, y) in enumerate(ds_val):
            # [b, 28, 28] => [b, 784]
            x = tf.reshape(x, (-1, 28 * 28))
            # [b, 784] => [b, 10]
            out = network(x)

            # [b, 10] => [b]
            pred = tf.argmax(out, axis=1)
            pred = tf.cast(pred, dtype=tf.int32)
            # bool type
            correct = tf.equal(pred, y)
            # bool tensor => int tensor => numpy
            total_correct += tf.reduce_sum(tf.cast(correct,
                                                   dtype=tf.int32)).numpy()
            total += x.shape[0]

            acc_meter.update_state(y, pred)

        print(
            step,
            'Evaluate Acc:',
            total_correct / total,
            acc_meter.result().numpy())

compile & fit

快捷训练方法
过程:

  1. compile 装载
    1. 指定 optimizer
    2. 指定 loss
    3. 指定 评估标准
network.compile(optimizer=optimizers.Adam(lr=0.01),   # optimizer
                loss=tf.losses.CategoricalCrossentropy(from_logits=True),   # loss
                metrics=['accuracy']   # test
                )
  1. fit 完成标准 train
    1. 指定 训练集 db
    2. 指定 epochs
    3. 指定 validation_data 测试集
    4. 指定 validation_freq 测试频率 可以提前停机停止训练 保存
network.fit(db, epochs=5, validation_data=ds_val, validation_freq=2)
  1. evaluate 测试
network.evaluate(ds_val)
  1. predict 预测
sample = next(iter(ds_val))
x = sample[0]
y = sample[1]  # one-hot
pred = network.predict(x)  # [b, 10]
# convert back to number
y = tf.argmax(y, axis=1)
pred = tf.argmax(pred, axis=1)

print(pred)
print(y)

完整代码

import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


def preprocess(x, y):
    """
    x is a simple image, not a batch
    """
    x = tf.cast(x, dtype=tf.float32) / 255.
    x = tf.reshape(x, [28 * 28])
    y = tf.cast(y, dtype=tf.int32)
    y = tf.one_hot(y, depth=10)
    return x, y


batchsz = 128
(x, y), (x_val, y_val) = datasets.mnist.load_data()
print('datasets:', x.shape, y.shape, x.min(), x.max())

db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(60000).batch(batchsz)
ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz)

sample = next(iter(db))
print(sample[0].shape, sample[1].shape)

network = Sequential([layers.Dense(256, activation='relu'),
                      layers.Dense(128, activation='relu'),
                      layers.Dense(64, activation='relu'),
                      layers.Dense(32, activation='relu'),
                      layers.Dense(10)])
network.build(input_shape=(None, 28 * 28))
network.summary()

network.compile(optimizer=optimizers.Adam(lr=0.01),
                loss=tf.losses.CategoricalCrossentropy(from_logits=True),
                metrics=['accuracy']   # test
                )

network.fit(db, epochs=10, validation_data=ds_val, validation_freq=2)

network.evaluate(ds_val)

sample = next(iter(ds_val))
x = sample[0]
y = sample[1]  # one-hot
pred = network.predict(x)  # [b, 10]
# convert back to number
y = tf.argmax(y, axis=1)
pred = tf.argmax(pred, axis=1)

print(pred)
print(y)

你可能感兴趣的:(tensorflow,深度学习,tensorflow)