dropout.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. def preprocess(x, y):
  6. x = tf.cast(x, dtype=tf.float32) / 255.
  7. y = tf.cast(y, dtype=tf.int32)
  8. return x,y
  9. batchsz = 128
  10. (x, y), (x_val, y_val) = datasets.mnist.load_data()
  11. print('datasets:', x.shape, y.shape, x.min(), x.max())
  12. db = tf.data.Dataset.from_tensor_slices((x,y))
  13. db = db.map(preprocess).shuffle(60000).batch(batchsz).repeat(10)
  14. ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
  15. ds_val = ds_val.map(preprocess).batch(batchsz)
  16. network = Sequential([layers.Dense(256, activation='relu'),
  17. layers.Dropout(0.5), # 0.5 rate to drop
  18. layers.Dense(128, activation='relu'),
  19. layers.Dropout(0.5), # 0.5 rate to drop
  20. layers.Dense(64, activation='relu'),
  21. layers.Dense(32, activation='relu'),
  22. layers.Dense(10)])
  23. network.build(input_shape=(None, 28*28))
  24. network.summary()
  25. optimizer = optimizers.Adam(lr=0.01)
  26. for step, (x,y) in enumerate(db):
  27. with tf.GradientTape() as tape:
  28. # [b, 28, 28] => [b, 784]
  29. x = tf.reshape(x, (-1, 28*28))
  30. # [b, 784] => [b, 10]
  31. out = network(x, training=True)
  32. # [b] => [b, 10]
  33. y_onehot = tf.one_hot(y, depth=10)
  34. # [b]
  35. loss = tf.reduce_mean(tf.losses.categorical_crossentropy(y_onehot, out, from_logits=True))
  36. loss_regularization = []
  37. for p in network.trainable_variables:
  38. loss_regularization.append(tf.nn.l2_loss(p))
  39. loss_regularization = tf.reduce_sum(tf.stack(loss_regularization))
  40. loss = loss + 0.0001 * loss_regularization
  41. grads = tape.gradient(loss, network.trainable_variables)
  42. optimizer.apply_gradients(zip(grads, network.trainable_variables))
  43. if step % 100 == 0:
  44. print(step, 'loss:', float(loss), 'loss_regularization:', float(loss_regularization))
  45. # evaluate
  46. if step % 500 == 0:
  47. total, total_correct = 0., 0
  48. for step, (x, y) in enumerate(ds_val):
  49. # [b, 28, 28] => [b, 784]
  50. x = tf.reshape(x, (-1, 28*28))
  51. # [b, 784] => [b, 10]
  52. out = network(x, training=True)
  53. # [b, 10] => [b]
  54. pred = tf.argmax(out, axis=1)
  55. pred = tf.cast(pred, dtype=tf.int32)
  56. # bool type
  57. correct = tf.equal(pred, y)
  58. # bool tensor => int tensor => numpy
  59. total_correct += tf.reduce_sum(tf.cast(correct, dtype=tf.int32)).numpy()
  60. total += x.shape[0]
  61. print(step, 'Evaluate Acc with drop:', total_correct/total)
  62. total, total_correct = 0., 0
  63. for step, (x, y) in enumerate(ds_val):
  64. # [b, 28, 28] => [b, 784]
  65. x = tf.reshape(x, (-1, 28*28))
  66. # [b, 784] => [b, 10]
  67. out = network(x, training=False)
  68. # [b, 10] => [b]
  69. pred = tf.argmax(out, axis=1)
  70. pred = tf.cast(pred, dtype=tf.int32)
  71. # bool type
  72. correct = tf.equal(pred, y)
  73. # bool tensor => int tensor => numpy
  74. total_correct += tf.reduce_sum(tf.cast(correct, dtype=tf.int32)).numpy()
  75. total += x.shape[0]
  76. print(step, 'Evaluate Acc without drop:', total_correct/total)