keras_train.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import os
  2. os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
  3. import tensorflow as tf
  4. from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
  5. from tensorflow import keras
  6. def preprocess(x, y):
  7. # [0~255] => [-1~1]
  8. x = 2 * tf.cast(x, dtype=tf.float32) / 255. - 1.
  9. y = tf.cast(y, dtype=tf.int32)
  10. return x,y
  11. batchsz = 128
  12. # [50k, 32, 32, 3], [10k, 1]
  13. (x, y), (x_val, y_val) = datasets.cifar10.load_data()
  14. y = tf.squeeze(y)
  15. y_val = tf.squeeze(y_val)
  16. y = tf.one_hot(y, depth=10) # [50k, 10]
  17. y_val = tf.one_hot(y_val, depth=10) # [10k, 10]
  18. print('datasets:', x.shape, y.shape, x_val.shape, y_val.shape, x.min(), x.max())
  19. train_db = tf.data.Dataset.from_tensor_slices((x,y))
  20. train_db = train_db.map(preprocess).shuffle(10000).batch(batchsz)
  21. test_db = tf.data.Dataset.from_tensor_slices((x_val, y_val))
  22. test_db = test_db.map(preprocess).batch(batchsz)
  23. sample = next(iter(train_db))
  24. print('batch:', sample[0].shape, sample[1].shape)
  25. class MyDense(layers.Layer):
  26. # to replace standard layers.Dense()
  27. def __init__(self, inp_dim, outp_dim):
  28. super(MyDense, self).__init__()
  29. self.kernel = self.add_variable('w', [inp_dim, outp_dim])
  30. # self.bias = self.add_variable('b', [outp_dim])
  31. def call(self, inputs, training=None):
  32. x = inputs @ self.kernel
  33. return x
  34. class MyNetwork(keras.Model):
  35. def __init__(self):
  36. super(MyNetwork, self).__init__()
  37. self.fc1 = MyDense(32*32*3, 256)
  38. self.fc2 = MyDense(256, 128)
  39. self.fc3 = MyDense(128, 64)
  40. self.fc4 = MyDense(64, 32)
  41. self.fc5 = MyDense(32, 10)
  42. def call(self, inputs, training=None):
  43. """
  44. :param inputs: [b, 32, 32, 3]
  45. :param training:
  46. :return:
  47. """
  48. x = tf.reshape(inputs, [-1, 32*32*3])
  49. # [b, 32*32*3] => [b, 256]
  50. x = self.fc1(x)
  51. x = tf.nn.relu(x)
  52. # [b, 256] => [b, 128]
  53. x = self.fc2(x)
  54. x = tf.nn.relu(x)
  55. # [b, 128] => [b, 64]
  56. x = self.fc3(x)
  57. x = tf.nn.relu(x)
  58. # [b, 64] => [b, 32]
  59. x = self.fc4(x)
  60. x = tf.nn.relu(x)
  61. # [b, 32] => [b, 10]
  62. x = self.fc5(x)
  63. return x
  64. network = MyNetwork()
  65. network.compile(optimizer=optimizers.Adam(lr=1e-3),
  66. loss=tf.losses.CategoricalCrossentropy(from_logits=True),
  67. metrics=['accuracy'])
  68. network.fit(train_db, epochs=15, validation_data=test_db, validation_freq=1)
  69. network.evaluate(test_db)
  70. network.save_weights('ckpt/weights.ckpt')
  71. del network
  72. print('saved to ckpt/weights.ckpt')
  73. network = MyNetwork()
  74. network.compile(optimizer=optimizers.Adam(lr=1e-3),
  75. loss=tf.losses.CategoricalCrossentropy(from_logits=True),
  76. metrics=['accuracy'])
  77. network.load_weights('ckpt/weights.ckpt')
  78. print('loaded weights from file.')
  79. network.evaluate(test_db)