verify_cifar10_alexnet8.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import tensorflow as tf
  2. import os
  3. import numpy as np
  4. from matplotlib import pyplot as plt
  5. from keras.layers import Conv2D, BatchNormalization, Activation, MaxPool2D, Dropout, Flatten, Dense
  6. from keras import Model
  7. np.set_printoptions(threshold=np.inf)
  8. cifar10 = tf.keras.datasets.cifar10
  9. (x_train, y_train), (x_test, y_test) = cifar10.load_data()
  10. x_train, x_test = x_train / 255.0, x_test / 255.0
  11. class AlexNet8(Model):
  12. def __init__(self):
  13. super(AlexNet8, self).__init__()
  14. self.c1 = Conv2D(filters=96, kernel_size=(3, 3))
  15. self.b1 = BatchNormalization()
  16. self.a1 = Activation('relu')
  17. self.p1 = MaxPool2D(pool_size=(3, 3), strides=2)
  18. self.c2 = Conv2D(filters=256, kernel_size=(3, 3))
  19. self.b2 = BatchNormalization()
  20. self.a2 = Activation('relu')
  21. self.p2 = MaxPool2D(pool_size=(3, 3), strides=2)
  22. self.c3 = Conv2D(filters=384, kernel_size=(3, 3), padding='same',
  23. activation='relu')
  24. self.c4 = Conv2D(filters=384, kernel_size=(3, 3), padding='same',
  25. activation='relu')
  26. self.c5 = Conv2D(filters=256, kernel_size=(3, 3), padding='same',
  27. activation='relu')
  28. self.p3 = MaxPool2D(pool_size=(3, 3), strides=2)
  29. self.flatten = Flatten()
  30. self.f1 = Dense(2048, activation='relu')
  31. self.d1 = Dropout(0.5)
  32. self.f2 = Dense(2048, activation='relu')
  33. self.d2 = Dropout(0.5)
  34. self.f3 = Dense(10, activation='softmax')
  35. def call(self, x):
  36. x = self.c1(x)
  37. x = self.b1(x)
  38. x = self.a1(x)
  39. x = self.p1(x)
  40. x = self.c2(x)
  41. x = self.b2(x)
  42. x = self.a2(x)
  43. x = self.p2(x)
  44. x = self.c3(x)
  45. x = self.c4(x)
  46. x = self.c5(x)
  47. x = self.p3(x)
  48. x = self.flatten(x)
  49. x = self.f1(x)
  50. x = self.d1(x)
  51. x = self.f2(x)
  52. x = self.d2(x)
  53. y = self.f3(x)
  54. return y
  55. model = AlexNet8()
  56. model.compile(optimizer='adam',
  57. loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
  58. metrics=['sparse_categorical_accuracy'])
  59. checkpoint_save_path = "./checkpoint/AlexNet8.ckpt"
  60. if os.path.exists(checkpoint_save_path + '.index'):
  61. print('-------------load the model-----------------')
  62. model.load_weights(checkpoint_save_path)
  63. cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
  64. save_weights_only=True,
  65. save_best_only=True)
  66. history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
  67. callbacks=[cp_callback])
  68. model.summary()
  69. # print(model.trainable_variables)
  70. file = open('./weights.txt', 'w')
  71. for v in model.trainable_variables:
  72. file.write(str(v.name) + '\n')
  73. file.write(str(v.shape) + '\n')
  74. file.write(str(v.numpy()) + '\n')
  75. file.close()
  76. ############################################### show ###############################################
  77. # 显示训练集和验证集的acc和loss曲线
  78. acc = history.history['sparse_categorical_accuracy']
  79. val_acc = history.history['val_sparse_categorical_accuracy']
  80. loss = history.history['loss']
  81. val_loss = history.history['val_loss']
  82. plt.subplot(1, 2, 1)
  83. plt.plot(acc, label='Training Accuracy')
  84. plt.plot(val_acc, label='Validation Accuracy')
  85. plt.title('Training and Validation Accuracy')
  86. plt.legend()
  87. plt.subplot(1, 2, 2)
  88. plt.plot(loss, label='Training Loss')
  89. plt.plot(val_loss, label='Validation Loss')
  90. plt.title('Training and Validation Loss')
  91. plt.legend()
  92. plt.show()