You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

DenseNet100-cifar10 4.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import time
  2. import multiprocessing
  3. import tensorflow as tf
  4. import os
  5. os.environ['TL_BACKEND'] = 'tensorflow'
  6. import tensorlayer as tl
  7. from .densenet import densenet
  8. tl.logging.set_verbosity(tl.logging.DEBUG)
  9. X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3), plotable=False)
  10. # get the network
  11. net = densenet("densenet-100")
  12. # training settings
  13. batch_size = 128
  14. n_epoch = 500
  15. learning_rate = 0.0001
  16. print_freq = 5
  17. n_step_epoch = int(len(y_train) / batch_size)
  18. n_step = n_epoch * n_step_epoch
  19. shuffle_buffer_size = 128
  20. train_weights = net.trainable_weights
  21. optimizer = tl.optimizers.Adam(learning_rate)
  22. metrics = tl.metric.Accuracy()
  23. def generator_train():
  24. inputs = X_train
  25. targets = y_train
  26. if len(inputs) != len(targets):
  27. raise AssertionError("The length of inputs and targets should be equal")
  28. for _input, _target in zip(inputs, targets):
  29. # yield _input.encode('utf-8'), _target.encode('utf-8')
  30. yield _input, _target
  31. def generator_test():
  32. inputs = X_test
  33. targets = y_test
  34. if len(inputs) != len(targets):
  35. raise AssertionError("The length of inputs and targets should be equal")
  36. for _input, _target in zip(inputs, targets):
  37. # yield _input.encode('utf-8'), _target.encode('utf-8')
  38. yield _input, _target
  39. def _map_fn_train(img, target):
  40. # 1. Randomly crop a [height, width] section of the image.
  41. img = tf.image.random_crop(img, [24, 24, 3])
  42. # 2. Randomly flip the image horizontally.
  43. img = tf.image.random_flip_left_right(img)
  44. # 3. Randomly change brightness.
  45. img = tf.image.random_brightness(img, max_delta=63)
  46. # 4. Randomly change contrast.
  47. img = tf.image.random_contrast(img, lower=0.2, upper=1.8)
  48. # 5. Subtract off the mean and divide by the variance of the pixels.
  49. img = tf.image.per_image_standardization(img)
  50. target = tf.reshape(target, ())
  51. return img, target
  52. def _map_fn_test(img, target):
  53. # 1. Crop the central [height, width] of the image.
  54. img = tf.image.resize_with_pad(img, 24, 24)
  55. # 2. Subtract off the mean and divide by the variance of the pixels.
  56. img = tf.image.per_image_standardization(img)
  57. img = tf.reshape(img, (24, 24, 3))
  58. target = tf.reshape(target, ())
  59. return img, target
  60. # dataset API and augmentation
  61. train_ds = tf.data.Dataset.from_generator(
  62. generator_train, output_types=(tf.float32, tf.int32)
  63. ) # , output_shapes=((24, 24, 3), (1)))
  64. train_ds = train_ds.map(_map_fn_train,num_parallel_calls=multiprocessing.cpu_count())
  65. # train_ds = train_ds.repeat(n_epoch)
  66. train_ds = train_ds.shuffle(shuffle_buffer_size)
  67. train_ds = train_ds.prefetch(buffer_size=4096)
  68. train_ds = train_ds.batch(batch_size)
  69. # value = train_ds.make_one_shot_iterator().get_next()
  70. test_ds = tf.data.Dataset.from_generator(
  71. generator_test, output_types=(tf.float32, tf.int32)
  72. ) # , output_shapes=((24, 24, 3), (1)))
  73. # test_ds = test_ds.shuffle(shuffle_buffer_size)
  74. test_ds = test_ds.map(_map_fn_test,num_parallel_calls=multiprocessing.cpu_count())
  75. # test_ds = test_ds.repeat(n_epoch)
  76. test_ds = test_ds.prefetch(buffer_size=4096)
  77. test_ds = test_ds.batch(batch_size)
  78. # value_test = test_ds.make_one_shot_iterator().get_next()
  79. class WithLoss(tl.layers.Module):
  80. def __init__(self, net, loss_fn):
  81. super(WithLoss, self).__init__()
  82. self._net = net
  83. self._loss_fn = loss_fn
  84. def forward(self, data, label):
  85. out = self._net(data)
  86. loss = self._loss_fn(out, label)
  87. return loss
  88. net_with_loss = WithLoss(net, loss_fn=tl.cost.softmax_cross_entropy_with_logits)
  89. net_with_train = tl.models.TrainOneStep(net_with_loss, optimizer, train_weights)
  90. for epoch in range(n_epoch):
  91. start_time = time.time()
  92. net.set_train()
  93. train_loss, train_acc, n_iter = 0, 0, 0
  94. for X_batch, y_batch in train_ds:
  95. X_batch = tl.ops.convert_to_tensor(X_batch.numpy(), dtype=tl.float32)
  96. y_batch = tl.ops.convert_to_tensor(y_batch.numpy(), dtype=tl.int64)
  97. _loss_ce = net_with_train(X_batch, y_batch)
  98. train_loss += _loss_ce
  99. n_iter += 1
  100. _logits = net(X_batch)
  101. metrics.update(_logits, y_batch)
  102. train_acc += metrics.result()
  103. metrics.reset()
  104. print("Epoch {} of {} took {}".format(epoch + 1, n_epoch, time.time() - start_time))
  105. print(" train loss: {}".format(train_loss / n_iter))
  106. print(" train acc: {}".format(train_acc / n_iter))

TensorLayer3.0 是一款兼容多种深度学习框架为计算后端的深度学习库。计划兼容TensorFlow, Pytorch, MindSpore, Paddle.