|
| 1 | +# 为了 Python2 玩家们 |
| 2 | +from __future__ import print_function, division |
| 3 | + |
| 4 | +# 第三方 |
| 5 | +import tensorflow as tf |
| 6 | +from sklearn.metrics import confusion_matrix |
| 7 | +import numpy as np |
| 8 | + |
| 9 | +# 我们自己 |
| 10 | +import load |
| 11 | + |
| 12 | +train_samples, train_labels = load._train_samples, load._train_labels |
| 13 | +test_samples, test_labels = load._test_samples, load._test_labels |
| 14 | + |
| 15 | +print('Training set', train_samples.shape, train_labels.shape) |
| 16 | +print(' Test set', test_samples.shape, test_labels.shape) |
| 17 | + |
| 18 | +image_size = load.image_size |
| 19 | +num_labels = load.num_labels |
| 20 | +num_channels = load.num_channels |
| 21 | + |
| 22 | + |
| 23 | +def get_chunk(samples, labels, chunkSize): |
| 24 | + """ |
| 25 | + Iterator/Generator: get a batch of data |
| 26 | + 这个函数是一个迭代器/生成器,用于每一次只得到 chunkSize 这么多的数据 |
| 27 | + 用于 for loop, just like range() function |
| 28 | + """ |
| 29 | + if len(samples) != len(labels): |
| 30 | + raise Exception('Length of samples and labels must equal') |
| 31 | + stepStart = 0 # initial step |
| 32 | + i = 0 |
| 33 | + while stepStart < len(samples): |
| 34 | + stepEnd = stepStart + chunkSize |
| 35 | + if stepEnd < len(samples): |
| 36 | + yield i, samples[stepStart:stepEnd], labels[stepStart:stepEnd] |
| 37 | + i += 1 |
| 38 | + stepStart = stepEnd |
| 39 | + |
| 40 | + |
| 41 | +class Network(): |
| 42 | + def __init__(self, num_hidden, batch_size): |
| 43 | + """ |
| 44 | + @num_hidden: 隐藏层的节点数量 |
| 45 | + @batch_size:因为我们要节省内存,所以分批处理数据。每一批的数据量。 |
| 46 | + """ |
| 47 | + self.batch_size = batch_size |
| 48 | + self.test_batch_size = 500 |
| 49 | + |
| 50 | + # Hyper Parameters |
| 51 | + self.num_hidden = num_hidden |
| 52 | + |
| 53 | + # Graph Related |
| 54 | + self.graph = tf.Graph() |
| 55 | + self.tf_train_samples = None |
| 56 | + self.tf_train_labels = None |
| 57 | + self.tf_test_samples = None |
| 58 | + self.tf_test_labels = None |
| 59 | + self.tf_test_prediction = None |
| 60 | + |
| 61 | + # 统计 |
| 62 | + self.merged = None |
| 63 | + |
| 64 | + # 初始化 |
| 65 | + self.define_graph() |
| 66 | + self.session = tf.Session(graph=self.graph) |
| 67 | + self.writer = tf.summary.FileWriter('./board', self.graph) |
| 68 | + |
| 69 | + def define_graph(self): |
| 70 | + """ |
| 71 | + 定义我的的计算图谱 |
| 72 | + """ |
| 73 | + with self.graph.as_default(): |
| 74 | + # 这里只是定义图谱中的各种变量 |
| 75 | + with tf.name_scope('inputs'): |
| 76 | + self.tf_train_samples = tf.placeholder( |
| 77 | + tf.float32, shape=(self.batch_size, image_size, image_size, num_channels), name='tf_train_samples' |
| 78 | + ) |
| 79 | + self.tf_train_labels = tf.placeholder( |
| 80 | + tf.float32, shape=(self.batch_size, num_labels), name='tf_train_labels' |
| 81 | + ) |
| 82 | + self.tf_test_samples = tf.placeholder( |
| 83 | + tf.float32, shape=(self.test_batch_size, image_size, image_size, num_channels), |
| 84 | + name='tf_test_samples' |
| 85 | + ) |
| 86 | + |
| 87 | + # fully connected layer 1, fully connected |
| 88 | + with tf.name_scope('fc1'): |
| 89 | + fc1_weights = tf.Variable( |
| 90 | + tf.truncated_normal([image_size * image_size, self.num_hidden], stddev=0.1), name='fc1_weights' |
| 91 | + ) |
| 92 | + fc1_biases = tf.Variable(tf.constant(0.1, shape=[self.num_hidden]), name='fc1_biases') |
| 93 | + tf.summary.histogram('fc1_weights', fc1_weights) |
| 94 | + tf.summary.histogram('fc1_biases', fc1_biases) |
| 95 | + |
| 96 | + # fully connected layer 2 --> output layer |
| 97 | + with tf.name_scope('fc2'): |
| 98 | + fc2_weights = tf.Variable( |
| 99 | + tf.truncated_normal([self.num_hidden, num_labels], stddev=0.1), name='fc2_weights' |
| 100 | + ) |
| 101 | + fc2_biases = tf.Variable(tf.constant(0.1, shape=[num_labels]), name='fc2_biases') |
| 102 | + tf.summary.histogram('fc2_weights', fc2_weights) |
| 103 | + tf.summary.histogram('fc2_biases', fc2_biases) |
| 104 | + |
| 105 | + # 想在来定义图谱的运算 |
| 106 | + def model(data): |
| 107 | + # fully connected layer 1 |
| 108 | + shape = data.get_shape().as_list() |
| 109 | + reshape = tf.reshape(data, [shape[0], shape[1] * shape[2] * shape[3]]) |
| 110 | + |
| 111 | + with tf.name_scope('fc1_model'): |
| 112 | + fc1_model = tf.matmul(reshape, fc1_weights) + fc1_biases |
| 113 | + hidden = tf.nn.relu(fc1_model) |
| 114 | + |
| 115 | + # fully connected layer 2 |
| 116 | + with tf.name_scope('fc2_model'): |
| 117 | + return tf.matmul(hidden, fc2_weights) + fc2_biases |
| 118 | + |
| 119 | + # Training computation. |
| 120 | + logits = model(self.tf_train_samples) |
| 121 | + with tf.name_scope('loss'): |
| 122 | + self.loss = tf.reduce_mean( |
| 123 | + tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=self.tf_train_labels) |
| 124 | + ) |
| 125 | + tf.summary.scalar('Loss', self.loss) |
| 126 | + |
| 127 | + # Optimizer. |
| 128 | + with tf.name_scope('optimizer'): |
| 129 | + self.optimizer = tf.train.GradientDescentOptimizer(0.0001).minimize(self.loss) |
| 130 | + |
| 131 | + # Predictions for the training, validation, and test data. |
| 132 | + with tf.name_scope('predictions'): |
| 133 | + self.train_prediction = tf.nn.softmax(logits, name='train_prediction') |
| 134 | + self.test_prediction = tf.nn.softmax(model(self.tf_test_samples), name='test_prediction') |
| 135 | + |
| 136 | + self.merged = tf.summary.merge_all() |
| 137 | + |
| 138 | + def run(self): |
| 139 | + """ |
| 140 | + 用到Session |
| 141 | + """ |
| 142 | + |
| 143 | + # private function |
| 144 | + def print_confusion_matrix(confusionMatrix): |
| 145 | + print('Confusion Matrix:') |
| 146 | + for i, line in enumerate(confusionMatrix): |
| 147 | + print(line, line[i] / np.sum(line)) |
| 148 | + a = 0 |
| 149 | + for i, column in enumerate(np.transpose(confusionMatrix, (1, 0))): |
| 150 | + a += (column[i] / np.sum(column)) * (np.sum(column) / 26000) |
| 151 | + print(column[i] / np.sum(column), ) |
| 152 | + print('\n', np.sum(confusionMatrix), a) |
| 153 | + |
| 154 | + with self.session as session: |
| 155 | + tf.initialize_all_variables().run() |
| 156 | + |
| 157 | + # 训练 |
| 158 | + print('Start Training') |
| 159 | + # batch 1000 |
| 160 | + for i, samples, labels in get_chunk(train_samples, train_labels, chunkSize=self.batch_size): |
| 161 | + _, l, predictions, summary = session.run( |
| 162 | + [self.optimizer, self.loss, self.train_prediction, self.merged], |
| 163 | + feed_dict={self.tf_train_samples: samples, self.tf_train_labels: labels} |
| 164 | + ) |
| 165 | + self.writer.add_summary(summary, i) |
| 166 | + # labels is True Labels |
| 167 | + accuracy, _ = self.accuracy(predictions, labels) |
| 168 | + if i % 50 == 0: |
| 169 | + print('Minibatch loss at step %d: %f' % (i, l)) |
| 170 | + print('Minibatch accuracy: %.1f%%' % accuracy) |
| 171 | + # |
| 172 | + |
| 173 | + # 测试 |
| 174 | + accuracies = [] |
| 175 | + confusionMatrices = [] |
| 176 | + for i, samples, labels in get_chunk(test_samples, test_labels, chunkSize=self.test_batch_size): |
| 177 | + result = self.test_prediction.eval(feed_dict={self.tf_test_samples: samples}) |
| 178 | + accuracy, cm = self.accuracy(result, labels, need_confusion_matrix=True) |
| 179 | + accuracies.append(accuracy) |
| 180 | + confusionMatrices.append(cm) |
| 181 | + print('Test Accuracy: %.1f%%' % accuracy) |
| 182 | + print(' Average Accuracy:', np.average(accuracies)) |
| 183 | + print('Standard Deviation:', np.std(accuracies)) |
| 184 | + print_confusion_matrix(np.add.reduce(confusionMatrices)) |
| 185 | + # |
| 186 | + |
| 187 | + def accuracy(self, predictions, labels, need_confusion_matrix=False): |
| 188 | + """ |
| 189 | + 计算预测的正确率与召回率 |
| 190 | + @return: accuracy and confusionMatrix as a tuple |
| 191 | + """ |
| 192 | + _predictions = np.argmax(predictions, 1) |
| 193 | + _labels = np.argmax(labels, 1) |
| 194 | + cm = confusion_matrix(_labels, _predictions) if need_confusion_matrix else None |
| 195 | + # == is overloaded for numpy array |
| 196 | + accuracy = (100.0 * np.sum(_predictions == _labels) / predictions.shape[0]) |
| 197 | + return accuracy, cm |
| 198 | + |
| 199 | + |
| 200 | +if __name__ == '__main__': |
| 201 | + net = Network(num_hidden=128, batch_size=100) |
| 202 | + net.run() |
0 commit comments