1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
| import tensorflow as tf from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
class FashionMnist(): out_featrues1 = 12 out_featrues2 = 24 con_neurons = 512
def __init__(self, path): """ 构造方法 :param path:指定数据集路径 :return: """ self.sess = tf.Session() self.data = read_data_sets(path, one_hot=True)
def init_weight_variable(self, shape): """ 初始化权重方法 :param shape:指定初始化张量的形状 :return:经过初始化后的张量 """ inital = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(inital)
def init_bias_variable(self, shape): """ 初始化偏置 :param shape:指定初始化张量的形状 :return:经过初始化后的张量 """ inital = tf.constant(1.0, shape=shape) return tf.Variable(inital)
def conv2d(self, x, w): """ 二维卷积方法 :param x:原始数据 :param w:卷积核 :return:返回卷积后的结果 """ return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding="SAME")
def max_pool_2x2(self, x): """ 池化函数 :param x:原始数据 :return:池化后的数据 """ return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
def create_conv_pool_layer(self, input, input_features, out_features): """ 卷积、激活、池化层 :param input:原始数据 :param input_features:输入特征数量 :param out_features:输出特征数量 :return:卷积、激活、池化层后的数据 """ filter = self.init_weight_variable([5, 5, input_features, out_features]) b_conv = self.init_bias_variable([out_features])
h_conv = tf.nn.relu(self.conv2d(input, filter) + b_conv) h_pool = self.max_pool_2x2(h_conv) return h_pool
def create_fc_layer(self, h_pool_flat, input_featrues, con_neurons): """ 创建全连接层 :param h_pool_flat:输入数据,经过拉伸后的一维张量 :param input_featrues:输入特征大小 :param con_neurons:神经元数量 :return:全连接 """ w_fc = self.init_weight_variable([input_featrues, con_neurons]) b_fc = self.init_bias_variable([con_neurons]) h_fc1 = tf.nn.relu(tf.matmul(h_pool_flat, w_fc) + b_fc) return h_fc1
def build(self): """ 组建CNN :return: """ self.x = tf.placeholder(tf.float32, shape=[None, 784]) x_image = tf.reshape(self.x, [-1, 28, 28, 1]) self.y_ = tf.placeholder(tf.float32, shape=[None, 10]) h_pool1 = self.create_conv_pool_layer(x_image, 1, self.out_featrues1) h_pool2 = self.create_conv_pool_layer(h_pool1, self.out_featrues1, self.out_featrues2) h_pool2_flat_features = 7 * 7 * self.out_featrues2 h_pool2_flat = tf.reshape(h_pool2, [-1, h_pool2_flat_features]) h_fc = self.create_fc_layer(h_pool2_flat, h_pool2_flat_features, self.con_neurons) self.keep_prob = tf.placeholder("float") h_fc1_drop = tf.nn.dropout(h_fc, self.keep_prob) w_fc = self.init_weight_variable([self.con_neurons, 10]) b_fc = self.init_bias_variable([10]) y_conv = tf.matmul(h_fc1_drop, w_fc) + b_fc
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(self.y_, 1)) self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
loss_func = tf.nn.softmax_cross_entropy_with_logits(labels=self.y_, logits=y_conv) cross_entropy = tf.reduce_mean(loss_func) optimizer = tf.train.AdamOptimizer(0.001) self.train_step = optimizer.minimize(cross_entropy)
def train(self): self.sess.run(tf.global_variables_initializer()) merged = tf.summary.merge_all()
batch_size = 100 print("beging training...")
for i in range(10): total_batch = int(self.data.train.num_examples / batch_size)
for j in range(total_batch): batch = self.data.train.next_batch(batch_size) params = {self.x: batch[0], self.y_:batch[1], self.keep_prob: 0.5}
t, acc = self.sess.run([self.train_step, self.accuracy], params) if j % 100 == 0: print("epoch: %d, pass: %d, acc: %f" % (i, j, acc)) def eval(self, x, y, keep_prob): params = {self.x: x, self.y_: y, self.keep_prob: keep_prob} test_acc = self.sess.run(self.accuracy, params) print('Test accuracy %f' % test_acc) return test_acc
def close(self): self.sess.close()
if __name__ == "__main__": mnist = FashionMnist('FASHION_MNIST_data/') mnist.build() mnist.train()
print('\n----- Test -----') xs, ys = mnist.data.test.next_batch(100) mnist.eval(xs, ys, 1.0) mnist.close()
|