1 import os 2 import datetime 3 import tensorflow as tf 4 import matplotlib.pyplot as plt 5 import io 6 from tensorflow.keras import datasets, layers, Sequential, optimizers 7 8 os.environ[‘TF_CPP_MIN_LOG_LEVEL‘] = ‘2‘ 9 tf.random.set_seed(2345) 10 11 conv_layers = [ 12 # unit1 13 layers.Conv2D(6, kernel_size=[5, 5], strides=1, padding=‘valid‘, activation=tf.nn.sigmoid), 14 layers.MaxPool2D(pool_size=[2, 2], padding=‘same‘, strides=2), 15 16 # unit2 17 layers.Conv2D(16, kernel_size=[5, 5], strides=1, padding=‘valid‘, activation=tf.nn.sigmoid), 18 layers.MaxPool2D(pool_size=[2, 2], padding=‘same‘, strides=2), 19 ] 20 21 22 def preprocess(x, y): 23 x = tf.cast(x, dtype=tf.float32) / 255 24 # x = tf.reshape(x, [32, 32]) 25 y = tf.cast(y, dtype=tf.int32) 26 # y = tf.one_hot(y, depth=10) 27 return x, y 28 29 30 def plot_to_image(figure): 31 """Converts the matplotlib plot specified by ‘figure‘ to a PNG image and 32 returns it. The supplied figure is closed and inaccessible after this call.""" 33 # Save the plot to a PNG in memory. 34 buf = io.BytesIO() 35 plt.savefig(buf, format=‘png‘) 36 # Closing the figure prevents it from being displayed directly inside 37 # the notebook. 38 plt.close(figure) 39 buf.seek(0) 40 # Convert PNG buffer to TF image 41 image = tf.image.decode_png(buf.getvalue(), channels=4) 42 # Add the batch dimension 43 image = tf.expand_dims(image, 0) 44 return image 45 46 47 def image_grid(images): 48 """Return a 5x5 grid of the MNIST images as a matplotlib figure.""" 49 # Create a figure to contain the plot. 50 figure = plt.figure(figsize=(10, 10)) 51 for i in range(25): 52 # Start next subplot. 53 plt.subplot(5, 5, i + 1, title=‘name‘) 54 plt.xticks([]) 55 plt.yticks([]) 56 plt.grid(False) 57 plt.imshow(images[i], cmap=plt.cm.binary) 58 59 return figure 60 61 62 def main(): 63 (x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data() 64 print("x_train.shape:", x_train.shape, "y_train.shape:", y_train.shape) 65 print("x_test.shape:", x_test.shape, ‘y_test.shape:‘, y_test.shape) 66 y_test = tf.squeeze(y_test, axis=1) 67 y_train = tf.squeeze(y_train, axis=1) 68 train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)) 69 train_db = train_db.shuffle(1000).map(preprocess).batch(256) 70 71 test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)) 72 test_db = test_db.map(preprocess).batch(256) 73 74 sample_train = next(iter(train_db)) 75 sample_test = next(iter(test_db)) 76 print("sample_train[0].shape:", sample_train[0].shape, "sample_train[1].shape:", sample_train[1].shape) 77 print("sample_test[0].shape:", sample_test[0].shape, "sample_test[1].shape:", sample_test[1].shape) 78 79 conv_net = Sequential(conv_layers) 80 fc_net = Sequential([ 81 layers.Dense(120, activation=tf.nn.tanh), 82 layers.Dense(84, activation=tf.nn.tanh), 83 layers.Dense(10, activation=None), 84 ]) 85 conv_net.build(input_shape=[None, 32, 32, 3]) 86 fc_net.build(input_shape=[None, 400]) 87 88 optimizer = optimizers.Adam(lr=1e-4) 89 variables = conv_net.trainable_variables + fc_net.trainable_variables 90 91 current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") 92 log_dir = ‘logs/‘ + current_time 93 summary_writer = tf.summary.create_file_writer(log_dir) 94 sample_img = next(iter(train_db))[0] 95 # get first image instance 96 sample_img = sample_img[0] 97 sample_img = tf.reshape(sample_img, [1, 32, 32, 3]) 98 with summary_writer.as_default(): 99 tf.summary.image("Training sample:", sample_img, step=0) 100 101 for epoch in range(2000): 102 for step, (x, y) in enumerate(train_db): 103 with tf.GradientTape() as tape: 104 # [b, 32, 32, 3]->[b, 5,5,16] 105 out = conv_net(x) 106 # [b,5,5,16]->[b,400] 107 out = tf.reshape(out, [-1, 400]) 108 # [b, 16, 16, 5]->[b, 10] 109 logits = fc_net(out) 110 y_onehot = tf.one_hot(y, depth=10) 111 loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True) 112 loss = tf.reduce_mean(loss) 113 grads = tape.gradient(loss, variables) 114 optimizer.apply_gradients(zip(grads, variables)) 115 116 if step % 100 == 0: 117 print(epoch, step, ‘loss:‘, float(loss)) 118 with summary_writer.as_default(): 119 tf.summary.scalar(‘train-loss‘, float(loss), step=epoch) 120 total_num = 0 121 total_correct = 0 122 for x, y in test_db: 123 out = conv_net(x) 124 out = tf.reshape(out, [-1, 400]) 125 logits = fc_net(out) 126 prob = tf.nn.softmax(logits, axis=1) 127 pred = tf.argmax(prob, axis=1) 128 pred = tf.cast(pred, dtype=tf.int32) 129 # y = tf.cast(y, dtype=tf.int32) 130 correct = tf.cast(tf.equal(pred, y), dtype=tf.int32) 131 correct = tf.reduce_sum(correct) 132 133 total_num += x.shape[0] 134 total_correct += int(correct) 135 acc = total_correct / total_num 136 val_images = x[:25] 137 val_images = tf.reshape(val_images, [-1, 32, 32, 3]) 138 with summary_writer.as_default(): 139 tf.summary.scalar(‘test-acc‘, float(acc), step=epoch) 140 tf.summary.image("val-onebyone-images:", val_images, max_outputs=25, step=epoch) 141 142 val_images = tf.reshape(val_images, [-1, 32, 32]) 143 figure = image_grid(val_images) 144 tf.summary.image(‘val-images:‘, plot_to_image(figure), step=epoch) 145 print(epoch, ‘acc:‘, acc) 146 147 148 if __name__ == ‘__main__‘: 149 main()
网络结构和数据还是上一篇的网络结构和数据,增加了tensorboard可视化。附上代码
原文:https://www.cnblogs.com/bsyu/p/12180226.html