metrics.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. acc_meter = metrics.Accuracy()
  23. loss_meter = metrics.Mean()
  24. for step, (x,y) in enumerate(db):
  25. with tf.GradientTape() as tape:
  26. # [b, 28, 28] => [b, 784]
  27. x = tf.reshape(x, (-1, 28*28))
  28. # [b, 784] => [b, 10]
  29. out = network(x)
  30. # [b] => [b, 10]
  31. y_onehot = tf.one_hot(y, depth=10)
  32. # [b]
  33. loss = tf.reduce_mean(tf.losses.categorical_crossentropy(y_onehot, out, from_logits=True))
  34. loss_meter.update_state(loss)
  35. grads = tape.gradient(loss, network.trainable_variables)
  36. optimizer.apply_gradients(zip(grads, network.trainable_variables))
  37. if step % 100 == 0:
  38. print(step, 'loss:', loss_meter.result().numpy())
  39. loss_meter.reset_states()
  40. # evaluate
  41. if step % 500 == 0:
  42. total, total_correct = 0., 0
  43. acc_meter.reset_states()
  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. acc_meter.update_state(y, pred)
  58. print(step, 'Evaluate Acc:', total_correct/total, acc_meter.result().numpy())