1, 准备数据
cifar2 数据集为 cifar10 数据集的子集, 只包括前两种类别 airplane 和 automobile.
训练集有 airplane 和 automobile 图片各 5000 张, 测试集有 airplane 和 automobile 图片各 1000 张.
cifar2 任务的目标是训练一个模型来对飞机 airplane 和机动车 automobile 两种图片进行分类.
我们准备的 Cifar2 数据集的文件结构如下所示.
在 tensorflow 中准备图片数据的常用方案有两种, 第一种是使用 tf.keras 中的 ImageDataGenerator 工具构建图片数据生成器.
第二种是使用 tf.data.Dataset 搭配 tf.image 中的一些图片处理方法构建数据管道.
第一种方法更为简单, 其使用范例可以参考以下文章.
https://zhuanlan.zhihu.com/p/67466552
第二种方法是 TensorFlow 的原生方法, 更加灵活, 使用得当的话也可以获得更好的性能.
我们此处介绍第二种方法.
- import tensorflow as tf
- from tensorflow.keras import datasets,layers,models
- BATCH_SIZE = 100
- def load_image(img_path,size = (32,32)):
- label = tf.constant(1,tf.int8) if tf.strings.regex_full_match(img_path,".*/automobile/.*") \
- else tf.constant(0,tf.int8)
- img = tf.io.read_file(img_path)
- img = tf.image.decode_jpeg(img) #注意此处为 jpeg 格式
- img = tf.image.resize(img,size)/255.0
- return(img,label)
- # 使用并行化预处理 num_parallel_calls 和预存数据 prefetch 来提升性能
- ds_train = tf.data.Dataset.list_files("./data/cifar2/train/*/*.jpg") \
- .map(load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE) \
- .shuffle(buffer_size = 1000).batch(BATCH_SIZE) \
- .prefetch(tf.data.experimental.AUTOTUNE)
- ds_test = tf.data.Dataset.list_files("./data/cifar2/test/*/*.jpg") \
- .map(load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE) \
- .batch(BATCH_SIZE) \
- .prefetch(tf.data.experimental.AUTOTUNE)
- for x,y in ds_train.take(1):
- print(x.shape,y.shape)
- (100, 32, 32, 3) (100,)
2, 定义模型
使用 Keras 接口有以下 3 种方式构建模型: 使用 Sequential 按层顺序构建模型, 使用函数式 API 构建任意结构模型, 继承 Model 基类构建自定义模型.
此处选择使用函数式 API 构建模型.
- tf.keras.backend.clear_session() #清空会话
- inputs = layers.Input(shape=(32,32,3))
- x = layers.Conv2D(32,kernel_size=(3,3))(inputs)
- x = layers.MaxPool2D()(x)
- x = layers.Conv2D(64,kernel_size=(5,5))(x)
- x = layers.MaxPool2D()(x)
- x = layers.Dropout(rate=0.1)(x)
- x = layers.Flatten()(x)
- x = layers.Dense(32,activation='relu')(x)
- outputs = layers.Dense(1,activation = 'sigmoid')(x)
- model = models.Model(inputs = inputs,outputs = outputs)
- model.summary()
3, 训练模型
训练模型通常有 3 种方法, 内置 fit 方法, 内置 train_on_batch 方法, 以及自定义训练循环. 此处我们选择最常用也最简单的内置 fit 方法.
- import datetime
- logdir = "./data/keras_model/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
- tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)
- model.compile(
- optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
- loss=tf.keras.losses.binary_crossentropy,
- metrics=["accuracy"]
- )
- history = model.fit(ds_train,epochs= 10,validation_data=ds_test,
- callbacks = [tensorboard_callback],workers = 4)
- Epoch 1/10
- 100/100 [==============================] - 2205s 22s/step - loss: 0.4632 - accuracy: 0.7786 - val_loss: 0.3375 - val_accuracy: 0.8620
- Epoch 2/10
- 100/100 [==============================] - 11s 110ms/step - loss: 0.3346 - accuracy: 0.8565 - val_loss: 0.2617 - val_accuracy: 0.8965
- Epoch 3/10
- 100/100 [==============================] - 11s 111ms/step - loss: 0.2687 - accuracy: 0.8883 - val_loss: 0.2183 - val_accuracy: 0.9165
- Epoch 4/10
- 100/100 [==============================] - 11s 110ms/step - loss: 0.2171 - accuracy: 0.9128 - val_loss: 0.1811 - val_accuracy: 0.9280
- Epoch 5/10
- 100/100 [==============================] - 11s 114ms/step - loss: 0.1860 - accuracy: 0.9268 - val_loss: 0.1798 - val_accuracy: 0.9265
- Epoch 6/10
- 100/100 [==============================] - 11s 112ms/step - loss: 0.1646 - accuracy: 0.9358 - val_loss: 0.1818 - val_accuracy: 0.9260
- Epoch 7/10
- 100/100 [==============================] - 11s 113ms/step - loss: 0.1443 - accuracy: 0.9426 - val_loss: 0.1740 - val_accuracy: 0.9290
- Epoch 8/10
- 100/100 [==============================] - 11s 113ms/step - loss: 0.1301 - accuracy: 0.9469 - val_loss: 0.1635 - val_accuracy: 0.9325
- Epoch 9/10
- 100/100 [==============================] - 11s 112ms/step - loss: 0.1096 - accuracy: 0.9585 - val_loss: 0.1758 - val_accuracy: 0.9315
- Epoch 10/10
- 100/100 [==============================] - 11s 113ms/step - loss: 0.0961 - accuracy: 0.9628 - val_loss: 0.1595 - val_accuracy: 0.9415
4, 评估模型
- # %load_ext tensorboard
- # %tensorboard --logdir ./data/keras_model
- from tensorboard import notebook
- notebook.list()
- # 在 tensorboard 中查看模型
- notebook.start("--logdir ./data/keras_model")
或者我们自己绘图: 首先我们构造数据
- import pandas as pd
- dfhistory = pd.DataFrame(history.history)
- dfhistory.index = range(1,len(dfhistory) + 1)
- dfhistory.index.name = 'epoch'
- dfhistory
然后绘制:
- %matplotlib inline
- %config InlineBackend.figure_format = 'svg'
- import matplotlib.pyplot as plt
- def plot_metric(history, metric):
- train_metrics = history.history[metric]
- val_metrics = history.history['val_'+metric]
- epochs = range(1, len(train_metrics) + 1)
- plt.plot(epochs, train_metrics, 'bo--')
- plt.plot(epochs, val_metrics, 'ro-')
- plt.title('Training and validation'+ metric)
- plt.xlabel("Epochs")
- plt.ylabel(metric)
- plt.legend(["train_"+metric, 'val_'+metric])
- plt.show()
- plot_metric(history,"loss")
- plot_metric(history,"accuracy")
评估模型:
- # 可以使用 evaluate 对数据进行评估
- val_loss,val_accuracy = model.evaluate(ds_test,workers=4)
- print(val_loss,val_accuracy)
- 20/20 [==============================] - 2s 80ms/step - loss: 0.1595 - accuracy: 0.9415
- 0.15954092144966125 0.9415000081062317
5, 使用模型
可以使用 model.predict(ds_test) 进行预测.
也可以使用 model.predict_on_batch(x_test) 对一个批量进行预测.
- model.predict(ds_test)
- array([[1.1052408e-01],
- [3.4282297e-02],
- [2.7046111e-04],
- ...,
- [2.7544077e-03],
- [3.4654222e-04],
- [9.9993896e-01]], dtype=float32)
- for x,y in ds_test.take(1):
- print(model.predict_on_batch(x[0:20]))
- [[9.8728174e-01]
- [2.0267103e-02]
- [9.0806475e-03]
- [9.9996555e-01]
- [4.5376007e-02]
- [1.2818890e-03]
- [1.8698535e-03]
- [2.2900696e-03]
- [8.6169255e-01]
- [6.2768459e-06]
- [1.2383183e-02]
- [4.3949869e-02]
- [7.9778886e-01]
- [9.9822074e-01]
- [9.9993134e-01]
- [8.6685091e-02]
- [3.7480664e-02]
- [9.9652690e-01]
- [9.2210865e-01]
- [1.6160560e-03]]
6, 保存模型
推荐使用 TensorFlow 原生方式保存模型.
- # 保存权重, 该方式仅仅保存权重张量
- model.save_weights('./data/tf_model_weights.ckpt',save_format = "tf")
- # 保存模型结构与模型参数到文件, 该方式保存的模型具有跨平台性便于部署
- model.save('./data/tf_model_savedmodel', save_format="tf")
- print('export saved model.')
- model_loaded = tf.keras.models.load_model('./data/tf_model_savedmodel')
- model_loaded.evaluate(ds_test)
参考:
开源电子书地址: https://lyhue1991.github.io/eat_tensorflow2_in_30_days/
GitHub 项目地址: https://github.com/lyhue1991/eat_tensorflow2_in_30_days
来源: https://www.cnblogs.com/xiximayou/p/12643017.html