当前位置:   article > 正文

制作自己的数据集_制作数据集

制作数据集

目录

自制数据集,解决本领域应用

​编辑

​编辑

数据增强,扩充数据集

断点续训,存取模型

​编辑参数提取,把参数存入文本

acc/loss可视化,查看训练效果

编写一个应用程序(神经网络接口),给图识物


当你有了本领域的数据集 又有了标签 你怎么给x_train,y_train,x_test,x_test赋值呢

——自制数据集

当你数据量过少,模型见识不足,泛化力会弱

——数据增强

当每次模型训练都从0开始,很不方便

——断点续训,实时保存最优模型

神经网络训练的目的是获取各层神经网络的最优参数,只要拿到这些参数就能在其他地方快速实现神经网络的前向传播,因此需要记录这些参数

——参数提取,参数存入文本

——acc/loss可视化

——给图识物的例子

#############################################################################

自制数据集,解决本领域应用

图片:黑底白字灰度图,每张图28行28列的像素点,每个像素点都是0~255之间的整数,纯黑色0,纯白色255

标签:txt中放的是图片名和对应的标签,中间用空格隔开

 实际上txt中,

 现在自写代码对x_train,y_train,x_test,x_test赋值

 

  1. train_path = './mnist_image_label/mnist_train_jpg_60000/'
  2. train_txt = './mnist_image_label/mnist_train_jpg_60000.txt'
  3. x_train_savepath = './mnist_image_label/mnist_x_train.npy'
  4. y_train_savepath = './mnist_image_label/mnist_y_train.npy'
  5. test_path = './mnist_image_label/mnist_test_jpg_10000/'
  6. test_txt = './mnist_image_label/mnist_test_jpg_10000.txt'
  7. x_test_savepath = './mnist_image_label/mnist_x_test.npy'
  8. y_test_savepath = './mnist_image_label/mnist_y_test.npy'
  9. def generateds(path, txt):
  10. f = open(txt, 'r') # 以只读形式打开txt文件
  11. contents = f.readlines() # 读取文件中所有行
  12. f.close() # 关闭txt文件
  13. x, y_ = [], [] # 建立空列表
  14. for content in contents: # 逐行取出
  15. value = content.split() # 以空格分开,图片路径为value[0] , 标签为value[1] , 存入列表
  16. img_path = path + value[0] # 拼出图片路径和文件名
  17. img = Image.open(img_path) # 读入图片
  18. img = np.array(img.convert('L')) # 图片变为8位宽灰度值的np.array格式
  19. img = img / 255. # 数据归一化 (实现预处理)
  20. x.append(img) # 归一化后的数据,贴到列表x
  21. y_.append(value[1]) # 标签贴到列表y_
  22. print('loading : ' + content) # 打印状态提示
  23. x = np.array(x) # 变为np.array格式
  24. y_ = np.array(y_) # 变为np.array格式
  25. y_ = y_.astype(np.int64) # 变为64位整型
  26. return x, y_ # 返回输入特征x,返回标签y_

生成数据集.npy文件

总代码

  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()

数据增强,扩充数据集

 

因为第4维是图片像素点颜色RGB, 有很多种表示方法,比如 rgba 四个数值表示,或者一个灰度值表示. 故统一用一个数组表示, 相比原来的数值标量, 就等于增加了一个维度 图中使用了(60000,28,28,1)即表示变成了灰度图片
1 增加维度是为了使数据和网络结构匹配,就是说 和真实的图片能一样

2 增加维度的,因为可能不是灰度图片


断点续训,存取模型

断点续训:在进行神经网络训练过程中由于一些因素导致训练无法进行,需要保存当前的训练结果下次接着训练

读取已有的模型

保存现有的模型

是否保留模型参数save_weights_only=True

是否保留最优模型save_best_only=True 

history里储存了loss和metrics的结果,用于后面可视化

  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. # 读取模型
  15. checkpoint_save_path = "./checkpoint/mnist.ckpt"
  16. if os.path.exists(checkpoint_save_path + '.index'):
  17. print('-------------load the model-----------------')
  18. model.load_weights(checkpoint_save_path)
  19. # 保存模型
  20. cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
  21. save_weights_only=True,
  22. save_best_only=True)
  23. history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
  24. callbacks=[cp_callback])
  25. model.summary()

生成文件

 

 此时再次运行程序 可以看到如图代码,说明网络是接续上一次保存的模型继续运行


参数提取,把参数存入文本

查看刚才保存的网络模型的参数

在断点续训基础上增加了参数提取 ,打印出所有参数w并存入weights.txt

  1. import tensorflow as tf
  2. import os
  3. import numpy as np # 导入包
  4. np.set_printoptions(threshold=np.inf)
  5. mnist = tf.keras.datasets.mnist
  6. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  7. x_train, x_test = x_train / 255.0, x_test / 255.0
  8. model = tf.keras.models.Sequential([
  9. tf.keras.layers.Flatten(),
  10. tf.keras.layers.Dense(128, activation='relu'),
  11. tf.keras.layers.Dense(10, activation='softmax')
  12. ])
  13. model.compile(optimizer='adam',
  14. loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
  15. metrics=['sparse_categorical_accuracy'])
  16. checkpoint_save_path = "./checkpoint/mnist.ckpt"
  17. if os.path.exists(checkpoint_save_path + '.index'):
  18. print('-------------load the model-----------------')
  19. model.load_weights(checkpoint_save_path)
  20. cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
  21. save_weights_only=True,
  22. save_best_only=True)
  23. history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
  24. callbacks=[cp_callback])
  25. model.summary()
  26. # 打印所有参数并存入weights.txt文件
  27. print(model.trainable_variables)
  28. file = open('./weights.txt', 'w')
  29. for v in model.trainable_variables:
  30. file.write(str(v.name) + '\n')
  31. file.write(str(v.shape) + '\n')
  32. file.write(str(v.numpy()) + '\n')
  33. file.close()

生成文件

 具体内容

 

 


acc/loss可视化,查看训练效果

 

  1. import tensorflow as tf
  2. import os
  3. import numpy as np
  4. from matplotlib import pyplot as plt # 加入画图模块pyplot
  5. np.set_printoptions(threshold=np.inf)
  6. mnist = tf.keras.datasets.mnist
  7. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  8. x_train, x_test = x_train / 255.0, x_test / 255.0
  9. model = tf.keras.models.Sequential([
  10. tf.keras.layers.Flatten(),
  11. tf.keras.layers.Dense(128, activation='relu'),
  12. tf.keras.layers.Dense(10, activation='softmax')
  13. ])
  14. model.compile(optimizer='adam',
  15. loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
  16. metrics=['sparse_categorical_accuracy'])
  17. checkpoint_save_path = "./checkpoint/mnist.ckpt"
  18. if os.path.exists(checkpoint_save_path + '.index'):
  19. print('-------------load the model-----------------')
  20. model.load_weights(checkpoint_save_path)
  21. cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
  22. save_weights_only=True,
  23. save_best_only=True)
  24. history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
  25. callbacks=[cp_callback])
  26. model.summary()
  27. print(model.trainable_variables)
  28. file = open('./weights.txt', 'w')
  29. for v in model.trainable_variables:
  30. file.write(str(v.name) + '\n')
  31. file.write(str(v.shape) + '\n')
  32. file.write(str(v.numpy()) + '\n')
  33. file.close()
  34. ############################################### show ###############################################
  35. # 显示训练集和验证集的acc和loss曲线
  36. # 提取model.fit中的训练集准确率,测试集准确率,训练集损失函数数值,测试集损失函数数值
  37. acc = history.history['sparse_categorical_accuracy']
  38. val_acc = history.history['val_sparse_categorical_accuracy']
  39. loss = history.history['loss']
  40. val_loss = history.history['val_loss']
  41. # 划分一行两列 画出第一列
  42. plt.subplot(1, 2, 1)
  43. # 画出acc和val_acc数据
  44. plt.plot(acc, label='Training Accuracy')
  45. plt.plot(val_acc, label='Validation Accuracy')
  46. # 设置图标题
  47. plt.title('Training and Validation Accuracy')
  48. # 画出图例
  49. plt.legend()
  50. # # 划分一行两列 画出第二列
  51. plt.subplot(1, 2, 2)
  52. # 画出loss和val_acc数据
  53. plt.plot(loss, label='Training Loss')
  54. plt.plot(val_loss, label='Validation Loss')
  55. # 设置图标题
  56. plt.title('Training and Validation Loss')
  57. # 画出图例
  58. plt.legend()
  59. plt.show()


编写一个应用程序(神经网络接口),给图识物

 TensorFlow给了predict,他能根据输入特征,得出输出参数

 预处理

灰度处理

 变成只有黑色和白色的高对比度图片

 把小于200的变成255,其他的变成0 —— 二值化,保留图片特征的同时,滤去了噪声,识别效果会更好

  1. from PIL import Image
  2. import numpy as np
  3. import tensorflow as tf
  4. model_save_path = './checkpoint/mnist.ckpt'
  5. # 复现网络
  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.load_weights(model_save_path)
  12. # 询问要执行多少次图像识别任务
  13. preNum = int(input("input the number of test pictures:"))
  14. # 读入要识别的图片
  15. for i in range(preNum):
  16. image_path = input("the path of test picture:")
  17. img = Image.open(image_path)
  18. img = img.resize((28, 28), Image.ANTIALIAS)
  19. img_arr = np.array(img.convert('L'))
  20. # 每个像素点颜色取反,使图片满足了神经网络对输入分割的要求,也称 预处理
  21. img_arr = 255 - img_arr
  22. # 归一化
  23. img_arr = img_arr / 255.0
  24. print("img_arr:",img_arr.shape)
  25. x_predict = img_arr[tf.newaxis, ...]
  26. print("x_predict:",x_predict.shape)
  27. result = model.predict(x_predict)
  28. pred = tf.argmax(result, axis=1)
  29. print('\n')
  30. tf.print(pred)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/475463
推荐阅读
相关标签
  

闽ICP备14008679号