DAY 13 Tensorflow 自制数据集 数据加强 断点续训

打印 上一主题 下一主题

主题 881|帖子 881|积分 2643

自制数据集代码如下:
  1. import tensorflow as tf
  2. from PIL import Image
  3. import numpy as np
  4. import os
  5. train_path = './mnist_image_label/mnist_train_jpg_60000/'
  6. train_txt = './mnist_image_label/mnist_train_jpg_60000.txt'
  7. x_train_savepath = './mnist_image_label/mnist_x_train.npy'
  8. y_train_savepath = './mnist_image_label/mnist_y_train.npy'
  9. test_path = './mnist_image_label/mnist_test_jpg_10000/'
  10. test_txt = './mnist_image_label/mnist_test_jpg_10000.txt'
  11. x_test_savepath = './mnist_image_label/mnist_x_test.npy'
  12. y_test_savepath = './mnist_image_label/mnist_y_test.npy'
  13. def generateds(path, txt):
  14.     f = open(txt, 'r')  # 以只读形式打开txt文件
  15.     contents = f.readlines()  # 读取文件中所有行
  16.     f.close()  # 关闭txt文件
  17.     x, y_ = [], []  # 建立空列表
  18.     for content in contents:  # 逐行取出
  19.         value = content.split()  # 以空格分开,图片路径为value[0] , 标签为value[1] , 存入列表
  20.         img_path = path + value[0]  # 拼出图片路径和文件名
  21.         img = Image.open(img_path)  # 读入图片
  22.         img = np.array(img.convert('L'))  # 图片变为8位宽灰度值的np.array格式
  23.         img = img / 255.  # 数据归一化 (实现预处理)
  24.         x.append(img)  # 归一化后的数据,贴到列表x
  25.         y_.append(value[1])  # 标签贴到列表y_
  26.         print('loading : ' + content)  # 打印状态提示
  27.     x = np.array(x)  # 变为np.array格式
  28.     y_ = np.array(y_)  # 变为np.array格式
  29.     y_ = y_.astype(np.int64)  # 变为64位整型
  30.     return x, y_  # 返回输入特征x,返回标签y_
  31. if os.path.exists(x_train_savepath) and os.path.exists(y_train_savepath) and os.path.exists(
  32.         x_test_savepath) and os.path.exists(y_test_savepath):
  33.     print('-------------Load Datasets-----------------')
  34.     x_train_save = np.load(x_train_savepath)
  35.     y_train = np.load(y_train_savepath)
  36.     x_test_save = np.load(x_test_savepath)
  37.     y_test = np.load(y_test_savepath)
  38.     x_train = np.reshape(x_train_save, (len(x_train_save), 28, 28))
  39.     x_test = np.reshape(x_test_save, (len(x_test_save), 28, 28))
  40. else:
  41.     print('-------------Generate Datasets-----------------')
  42.     x_train, y_train = generateds(train_path, train_txt)
  43.     x_test, y_test = generateds(test_path, test_txt)
  44.     print('-------------Save Datasets-----------------')
  45.     x_train_save = np.reshape(x_train, (len(x_train), -1))
  46.     x_test_save = np.reshape(x_test, (len(x_test), -1))
  47.     np.save(x_train_savepath, x_train_save)
  48.     np.save(y_train_savepath, y_train)
  49.     np.save(x_test_savepath, x_test_save)
  50.     np.save(y_test_savepath, y_test)
  51. model = tf.keras.models.Sequential([
  52.     tf.keras.layers.Flatten(),
  53.     tf.keras.layers.Dense(128, activation='relu'),
  54.     tf.keras.layers.Dense(10, activation='softmax')
  55. ])
  56. model.compile(optimizer='adam',
  57.               loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
  58.               metrics=['sparse_categorical_accuracy'])
  59. model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
  60. model.summary()
复制代码
第一次运行时,由于没有进行数据集的训练,以是会先实行generateds函数,然后生成.npy格式的数据集。第二次运行时,由于第一次运行已经生成了数据集,体系会检测到数据集,进而实行数据的训练。
数据加强:
我们可能会因为拍照角度,阴影的种种原因导致数据的效果并不是那么好,以是可以引入数据加强。


image_gen_train.fit(x_train)   这里的fit须要输入一个四位数据,以是须要对x.train进行reshape处理。处理后可以把6万张,28行28列的数据 新增加一个通道为1的数据。这里的通道1指的是灰度值,之后就按照batch打包送入model.fit实行训练过程。
代码:
  1. import tensorflow as tf
  2. from tensorflow.keras.preprocessing.image import ImageDataGenerator
  3. mnist = tf.keras.datasets.mnist
  4. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  5. x_train, x_test = x_train / 255.0, x_test / 255.0
  6. x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)  # 给数据增加一个维度,从(60000, 28, 28)reshape为(60000, 28, 28, 1)
  7. image_gen_train = ImageDataGenerator(
  8.     rescale=1. / 1.,  # 如为图像,分母为255时,可归至0~1
  9.     rotation_range=45,  # 随机45度旋转
  10.     width_shift_range=.15,  # 宽度偏移
  11.     height_shift_range=.15,  # 高度偏移
  12.     horizontal_flip=False,  # 水平翻转
  13.     zoom_range=0.5  # 将图像随机缩放阈量50%
  14. )
  15. image_gen_train.fit(x_train)
  16. model = tf.keras.models.Sequential([
  17.     tf.keras.layers.Flatten(),
  18.     tf.keras.layers.Dense(128, activation='relu'),
  19.     tf.keras.layers.Dense(10, activation='softmax')
  20. ])
  21. model.compile(optimizer='adam',
  22.               loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
  23.               metrics=['sparse_categorical_accuracy'])
  24. model.fit(image_gen_train.flow(x_train, y_train, batch_size=32), epochs=5, validation_data=(x_test, y_test),
  25.           validation_freq=1)
  26. model.summary()
复制代码
断点续训很简单,就是可以生存训练的结果,使你在下次预测的时候不须要重新训练数据集,直接利用存放在本地的训练结果进行预测就行。

  1. import tensorflow as tf
  2. import os
  3. mnist = tf.keras.datasets.mnist
  4. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  5. x_train, x_test = x_train / 255.0, x_test / 255.0
  6. model = tf.keras.models.Sequential([
  7.     tf.keras.layers.Flatten(),
  8.     tf.keras.layers.Dense(128, activation='relu'),
  9.     tf.keras.layers.Dense(10, activation='softmax')
  10. ])
  11. model.compile(optimizer='adam',
  12.               loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
  13.               metrics=['sparse_categorical_accuracy'])
  14. checkpoint_save_path = "./checkpoint/mnist.ckpt"
  15. if os.path.exists(checkpoint_save_path + '.index'):
  16.     print('-------------load the model-----------------')
  17.     model.load_weights(checkpoint_save_path)
  18. cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
  19.                                                  save_weights_only=True,
  20.                                                  save_best_only=True)
  21. history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
  22.                     callbacks=[cp_callback])
  23. model.summary()
复制代码

save_weights_only   只生存模型参数
save_best_only 只生存最优模型
fit中加入callback,返回给history





免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

海哥

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表