当前位置:   article > 正文

拓展神经网络八股(入门级)

拓展神经网络八股(入门级)

自制数据集

minst等数据集是别人打包好的,如果是本领域的数据集。自制数据集。

替换

把图片路径和标签文件输入到函数里,并返回输入特征和标签

只需要把图片灰度值数据拼接到特征列表,标签添加到标签列表,提取操作函数如下:

  1. def generateds(path, txt):
  2. f = open(txt, 'r')
  3. contents = f.readlines() #读取所有行
  4. f.close()
  5. x, y_ = [], []
  6. for content in contents:
  7. value = content.split()
  8. img_path = path + value[0]#找到图片索引路径
  9. img = Image.open(img_path) #图片打开
  10. img = np.array(img.convert('L')) # 图片变为8位灰度的npy格式的数据集
  11. img = img / 255.
  12. x.append(img)
  13. y_.append(value[1])
  14. print('loading:' + content) # 打印状态提示
  15. x = np.array(x)
  16. y_ = np.array(y_)
  17. y_ = y_astype(np.int64)
  18. return x, y_

 完整代码

  1. import tensorflow as tf
  2. from PIL import Image
  3. import numpy as np
  4. import os
  5. train_path = './fashion_image_label/fashion_train_jpg_60000/'
  6. train_txt = './fashion_image_label/fashion_train_jpg_60000.txt'
  7. x_train_savepath = './fashion_image_label/fashion_x_train.npy'
  8. y_train_savepath = './fashion_image_label/fahion_y_train.npy'
  9. test_path = './fashion_image_label/fashion_test_jpg_10000/'
  10. test_txt = './fashion_image_label/fashion_test_jpg_10000.txt'
  11. x_test_savepath = './fashion_image_label/fashion_x_test.npy'
  12. y_test_savepath = './fashion_image_label/fashion_y_test.npy'
  13. def generateds(path, txt):
  14. f = open(txt, 'r')
  15. contents = f.readlines() # 按行读取
  16. f.close()
  17. x, y_ = [], []
  18. for content in contents:
  19. value = content.split() # 以空格分开,存入数组
  20. img_path = path + value[0]
  21. img = Image.open(img_path)
  22. img = np.array(img.convert('L'))
  23. img = img / 255.
  24. x.append(img)
  25. y_.append(value[1])
  26. print('loading : ' + content)
  27. x = np.array(x)
  28. y_ = np.array(y_)
  29. y_ = y_.astype(np.int64)
  30. return 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()

数据增强

如果数据量过少,模型见识不足。增加数据,提高泛化力。

用来应对因为拍照角度不同引起的图片变形

image_gen_train=tf,keras.preprocessing,image.ImageDataGenneratorP(...)

image_gen)train,fit(x_train)

  1. import tensorflow as tf
  2. from tensorflow.keras.preprocessing.image import ImageDataGenerator
  3. fashion = tf.keras.datasets.fashion_mnist
  4. (x_train, y_train), (x_test, y_test) = fashion.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) # 给数据增加一个维度,使数据和网络结构匹配
  7. image_gen_train = ImageDataGenerator(
  8. rescale=1. / 1., # 如为图像,分母为255时,可归至01
  9. rotation_range=45, # 随机45度旋转
  10. width_shift_range=.15, # 宽度偏移
  11. height_shift_range=.15, # 高度偏移
  12. horizontal_flip=True, # 水平翻转
  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()

 因为是标准MINST数据集,因此在准确度上看不出来,需要在具体应用中才能体现

断点续训

实时保存最优模型

 保存模型参数可以使用tensorflow提供的ModelCheckpoint(filepath=checkpoint_save,

                              save_weight_only,sabe_best_only)

参数提取

获取各层网络最优参数,可以在各个平台实现应用

model.trainable_variables 返回模型中可训练参数

acc/loss可视化

查看训练效果

history=model.fit()

  1. import tensorflow as tf
  2. import os
  3. import numpy as np
  4. from matplotlib import pyplot as plt
  5. np.set_printoptions(threshold=np.inf)
  6. fashion = tf.keras.datasets.fashion_mnist
  7. (x_train, y_train), (x_test, y_test) = fashion.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/fashion.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. acc = history.history['sparse_categorical_accuracy']
  37. val_acc = history.history['val_sparse_categorical_accuracy']
  38. loss = history.history['loss']
  39. val_loss = history.history['val_loss']
  40. plt.subplot(1, 2, 1) 画出第一列
  41. plt.plot(acc, label='Training Accuracy')
  42. plt.plot(val_acc, label='Validation Accuracy')
  43. plt.title('Training and Validation Accuracy')
  44. plt.legend()
  45. plt.subplot(1, 2, 2) #画出第二列
  46. plt.plot(loss, label='Training Loss')
  47. plt.plot(val_loss, label='Validation Loss')
  48. plt.title('Training and Validation Loss')
  49. plt.legend()
  50. plt.show()

应用程序

给图识物

给出一张图片,输出预测结果

1.复现模型 Sequential加载模型

2.加载参数 load_weights(model_save_path)

3.预测结果

我们需要对颜色取反,我们的训练图片是黑底白字

减少了背景噪声的影响

  1. from PIL import Image
  2. import numpy as np
  3. import tensorflow as tf
  4. type = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
  5. model_save_path = './checkpoint/fashion.ckpt'
  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. preNum = int(input("input the number of test pictures:"))
  13. for i in range(preNum):
  14. image_path = input("the path of test picture:")
  15. img = Image.open(image_path)
  16. img=img.resize((28,28),Image.ANTIALIAS)
  17. img_arr = np.array(img.convert('L'))
  18. img_arr = 255 - img_arr #每个像素点= 255 - 各自点当前灰度值
  19. img_arr = img_arr/255.0
  20. x_predict = img_arr[tf.newaxis,...]
  21. result = model.predict(x_predict)
  22. pred=tf.argmax(result, axis=1)
  23. print('\n')
  24. print(type[int(pred)])

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

闽ICP备14008679号