forward_tensor.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import os
  2. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  3. import matplotlib
  4. from matplotlib import pyplot as plt
  5. # Default parameters for plots
  6. matplotlib.rcParams['font.size'] = 20
  7. matplotlib.rcParams['figure.titlesize'] = 20
  8. matplotlib.rcParams['figure.figsize'] = [9, 7]
  9. matplotlib.rcParams['font.family'] = ['STKaiTi']
  10. matplotlib.rcParams['axes.unicode_minus']=False
  11. import tensorflow as tf
  12. from tensorflow import keras
  13. from tensorflow.keras import datasets
  14. # x: [60k, 28, 28],
  15. # y: [60k]
  16. (x, y), _ = datasets.mnist.load_data()
  17. # x: [0~255] => [0~1.]
  18. x = tf.convert_to_tensor(x, dtype=tf.float32) / 255.
  19. y = tf.convert_to_tensor(y, dtype=tf.int32)
  20. print(x.shape, y.shape, x.dtype, y.dtype)
  21. print(tf.reduce_min(x), tf.reduce_max(x))
  22. print(tf.reduce_min(y), tf.reduce_max(y))
  23. train_db = tf.data.Dataset.from_tensor_slices((x,y)).batch(128)
  24. train_iter = iter(train_db)
  25. sample = next(train_iter)
  26. print('batch:', sample[0].shape, sample[1].shape)
  27. # [b, 784] => [b, 256] => [b, 128] => [b, 10]
  28. # [dim_in, dim_out], [dim_out]
  29. w1 = tf.Variable(tf.random.truncated_normal([784, 256], stddev=0.1))
  30. b1 = tf.Variable(tf.zeros([256]))
  31. w2 = tf.Variable(tf.random.truncated_normal([256, 128], stddev=0.1))
  32. b2 = tf.Variable(tf.zeros([128]))
  33. w3 = tf.Variable(tf.random.truncated_normal([128, 10], stddev=0.1))
  34. b3 = tf.Variable(tf.zeros([10]))
  35. lr = 1e-3
  36. losses = []
  37. for epoch in range(20): # iterate db for 10
  38. for step, (x, y) in enumerate(train_db): # for every batch
  39. # x:[128, 28, 28]
  40. # y: [128]
  41. # [b, 28, 28] => [b, 28*28]
  42. x = tf.reshape(x, [-1, 28*28])
  43. with tf.GradientTape() as tape: # tf.Variable
  44. # x: [b, 28*28]
  45. # h1 = x@w1 + b1
  46. # [b, 784]@[784, 256] + [256] => [b, 256] + [256] => [b, 256] + [b, 256]
  47. h1 = x@w1 + tf.broadcast_to(b1, [x.shape[0], 256])
  48. h1 = tf.nn.relu(h1)
  49. # [b, 256] => [b, 128]
  50. h2 = h1@w2 + b2
  51. h2 = tf.nn.relu(h2)
  52. # [b, 128] => [b, 10]
  53. out = h2@w3 + b3
  54. # compute loss
  55. # out: [b, 10]
  56. # y: [b] => [b, 10]
  57. y_onehot = tf.one_hot(y, depth=10)
  58. # mse = mean(sum(y-out)^2)
  59. # [b, 10]
  60. loss = tf.square(y_onehot - out)
  61. # mean: scalar
  62. loss = tf.reduce_mean(loss)
  63. # compute gradients
  64. grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])
  65. # print(grads)
  66. # w1 = w1 - lr * w1_grad
  67. w1.assign_sub(lr * grads[0])
  68. b1.assign_sub(lr * grads[1])
  69. w2.assign_sub(lr * grads[2])
  70. b2.assign_sub(lr * grads[3])
  71. w3.assign_sub(lr * grads[4])
  72. b3.assign_sub(lr * grads[5])
  73. if step % 100 == 0:
  74. print(epoch, step, 'loss:', float(loss))
  75. losses.append(float(loss))
  76. plt.figure()
  77. plt.plot(losses, color='C0', marker='s', label='训练')
  78. plt.xlabel('Epoch')
  79. plt.legend()
  80. plt.ylabel('MSE')
  81. plt.savefig('forward.svg')
  82. # plt.show()