resnet18_train.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import tensorflow as tf
  2. from tensorflow.keras import layers, optimizers, datasets, Sequential
  3. import os
  4. from resnet import resnet18
  5. os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
  6. tf.random.set_seed(2345)
  7. def preprocess(x, y):
  8. # 将数据映射到-1~1
  9. x = 2*tf.cast(x, dtype=tf.float32) / 255. - 1
  10. y = tf.cast(y, dtype=tf.int32) # 类型转换
  11. return x,y
  12. (x,y), (x_test, y_test) = datasets.cifar10.load_data() # 加载数据集
  13. y = tf.squeeze(y, axis=1) # 删除不必要的维度
  14. y_test = tf.squeeze(y_test, axis=1) # 删除不必要的维度
  15. print(x.shape, y.shape, x_test.shape, y_test.shape)
  16. train_db = tf.data.Dataset.from_tensor_slices((x,y)) # 构建训练集
  17. # 随机打散,预处理,批量化
  18. train_db = train_db.shuffle(1000).map(preprocess).batch(512)
  19. test_db = tf.data.Dataset.from_tensor_slices((x_test,y_test)) #构建测试集
  20. # 随机打散,预处理,批量化
  21. test_db = test_db.map(preprocess).batch(512)
  22. # 采样一个样本
  23. sample = next(iter(train_db))
  24. print('sample:', sample[0].shape, sample[1].shape,
  25. tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))
  26. def main():
  27. # [b, 32, 32, 3] => [b, 1, 1, 512]
  28. model = resnet18() # ResNet18网络
  29. model.build(input_shape=(None, 32, 32, 3))
  30. model.summary() # 统计网络参数
  31. optimizer = optimizers.Adam(lr=1e-4) # 构建优化器
  32. for epoch in range(100): # 训练epoch
  33. for step, (x,y) in enumerate(train_db):
  34. with tf.GradientTape() as tape:
  35. # [b, 32, 32, 3] => [b, 10],前向传播
  36. logits = model(x)
  37. # [b] => [b, 10],one-hot编码
  38. y_onehot = tf.one_hot(y, depth=10)
  39. # 计算交叉熵
  40. loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
  41. loss = tf.reduce_mean(loss)
  42. # 计算梯度信息
  43. grads = tape.gradient(loss, model.trainable_variables)
  44. # 更新网络参数
  45. optimizer.apply_gradients(zip(grads, model.trainable_variables))
  46. if step %50 == 0:
  47. print(epoch, step, 'loss:', float(loss))
  48. total_num = 0
  49. total_correct = 0
  50. for x,y in test_db:
  51. logits = model(x)
  52. prob = tf.nn.softmax(logits, axis=1)
  53. pred = tf.argmax(prob, axis=1)
  54. pred = tf.cast(pred, dtype=tf.int32)
  55. correct = tf.cast(tf.equal(pred, y), dtype=tf.int32)
  56. correct = tf.reduce_sum(correct)
  57. total_num += x.shape[0]
  58. total_correct += int(correct)
  59. acc = total_correct / total_num
  60. print(epoch, 'acc:', acc)
  61. if __name__ == '__main__':
  62. main()