regularization.py 2.5 KB

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