Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train_model.py 8.6 KB

You have to be logged in to leave a comment. Sign In
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. import tensorflow as tf
  4. import input_data
  5. from tensorflow.python.framework import graph_util
  6. def build_network(height,width):
  7. """
  8. Function:构建网络模型。
  9. Parameters
  10. ----------
  11. height: Mnist图像的宽。
  12. width: Mnist图像的宽。
  13. """
  14. x = tf.placeholder(tf.float32, [None, height, width], name='input')
  15. y_placeholder = tf.placeholder(tf.float32, shape=[None, 10],name='labels_placeholder')
  16. keep_prob_placeholder = tf.placeholder(tf.float32, name='keep_prob_placeholder')
  17. def weight_variable(shape):
  18. initial = tf.truncated_normal(shape, stddev=0.1)
  19. return tf.Variable(initial)
  20. def bias_variable(shape):
  21. initial = tf.constant(0.1, shape=shape)
  22. return tf.Variable(initial)
  23. def conv2d(x, W):
  24. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  25. def max_pool_2x2(x):
  26. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  27. x_image = tf.reshape(x, [-1,height, width,1])
  28. # First Convolutional Layer
  29. W_conv1 = weight_variable([5, 5, 1, 32])
  30. b_conv1 = bias_variable([32])
  31. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
  32. h_pool1 = max_pool_2x2(h_conv1)
  33. # Second Convolutional Layer
  34. W_conv2 = weight_variable([5, 5, 32, 64])
  35. b_conv2 = bias_variable([64])
  36. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
  37. h_pool2 = max_pool_2x2(h_conv2)
  38. # Densely Connected Layer
  39. W_fc1 = weight_variable([7 * 7 * 64, 1024])
  40. b_fc1 = bias_variable([1024])
  41. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
  42. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  43. # Dropout
  44. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob_placeholder)
  45. # Readout Layer
  46. W_fc2 = weight_variable([1024, 10])
  47. b_fc2 = bias_variable([10])
  48. logits = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  49. sofmax_out = tf.nn.softmax(logits,name="out_softmax")
  50. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y_placeholder))
  51. optimize = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost)
  52. prediction_labels = tf.argmax(sofmax_out, axis=1,name="output")
  53. real_labels= tf.argmax(y_placeholder, axis=1)
  54. correct_prediction = tf.equal(prediction_labels, real_labels)
  55. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  56. #一个Batch中预测正确的次数
  57. correct_times_in_batch = tf.reduce_sum(tf.cast(correct_prediction, tf.int32))
  58. return dict(
  59. keep_prob_placeholder = keep_prob_placeholder,
  60. x_placeholder= x,
  61. y_placeholder = y_placeholder,
  62. optimize = optimize,
  63. logits = logits,
  64. prediction_labels = prediction_labels,
  65. real_labels = real_labels,
  66. correct_prediction = correct_prediction,
  67. correct_times_in_batch = correct_times_in_batch,
  68. cost = cost,
  69. accuracy = accuracy,
  70. )
  71. def train_network(graph,
  72. dataset,
  73. batch_size,
  74. num_epochs,
  75. pb_file_path,):
  76. """
  77. Function:训练网络。
  78. Parameters
  79. ----------
  80. graph: 一个dict,build_network函数的返回值。
  81. dataset: 数据集
  82. batch_size:
  83. num_epochs: 训练轮数。
  84. pb_file_path:要生成的pb文件的存放路径。
  85. """
  86. with tf.Session() as sess:
  87. sess.run(tf.global_variables_initializer())
  88. print("batch size:",batch_size)
  89. #用于控制每epoch_delta轮在train set和test set上计算一下accuracy和cost
  90. epoch_delta = 2
  91. for epoch_index in range(num_epochs):
  92. #################################
  93. # 获取TRAIN set,开始训练网络
  94. #################################
  95. for (batch_xs,batch_ys) in dataset.train.mini_batches(batch_size):
  96. sess.run([graph['optimize']], feed_dict={
  97. graph['x_placeholder']: batch_xs,
  98. graph['y_placeholder']: batch_ys,
  99. graph['keep_prob_placeholder']:0.5,
  100. })
  101. #每epoch_delta轮在train set和test set上计算一下accuracy和cost
  102. if epoch_index % epoch_delta == 0:
  103. #################################
  104. # 开始在 train set上计算一下accuracy和cost
  105. #################################
  106. #记录训练集中有多少个batch
  107. total_batches_in_train_set = 0
  108. #记录在训练集中预测正确的次数
  109. total_correct_times_in_train_set = 0
  110. #记录在训练集中的总cost
  111. total_cost_in_train_set = 0.
  112. for (train_batch_xs,train_batch_ys) in dataset.train.mini_batches(batch_size):
  113. return_correct_times_in_batch = sess.run(graph['correct_times_in_batch'], feed_dict={
  114. graph['x_placeholder']: train_batch_xs,
  115. graph['y_placeholder']: train_batch_ys,
  116. graph['keep_prob_placeholder']:1.0,
  117. })
  118. mean_cost_in_batch = sess.run(graph['cost'], feed_dict={
  119. graph['x_placeholder']: train_batch_xs,
  120. graph['y_placeholder']: train_batch_ys,
  121. graph['keep_prob_placeholder']:1.0,
  122. })
  123. total_batches_in_train_set += 1
  124. total_correct_times_in_train_set += return_correct_times_in_batch
  125. total_cost_in_train_set += (mean_cost_in_batch*batch_size)
  126. #################################
  127. # 开始在 test set上计算一下accuracy和cost
  128. #################################
  129. #记录测试集中有多少个batch
  130. total_batches_in_test_set = 0
  131. #记录在测试集中预测正确的次数
  132. total_correct_times_in_test_set = 0
  133. #记录在测试集中的总cost
  134. total_cost_in_test_set = 0.
  135. for (test_batch_xs,test_batch_ys) in dataset.test.mini_batches(batch_size):
  136. return_correct_times_in_batch = sess.run(graph['correct_times_in_batch'], feed_dict={
  137. graph['x_placeholder']: test_batch_xs,
  138. graph['y_placeholder']: test_batch_ys,
  139. graph['keep_prob_placeholder']:1.0,
  140. })
  141. mean_cost_in_batch = sess.run(graph['cost'], feed_dict={
  142. graph['x_placeholder']: test_batch_xs,
  143. graph['y_placeholder']: test_batch_ys,
  144. graph['keep_prob_placeholder']:1.0,
  145. })
  146. total_batches_in_test_set += 1
  147. total_correct_times_in_test_set += return_correct_times_in_batch
  148. total_cost_in_test_set += (mean_cost_in_batch*batch_size)
  149. ### summary and print
  150. acy_on_test = total_correct_times_in_test_set / float(total_batches_in_test_set * batch_size)
  151. acy_on_train = total_correct_times_in_train_set / float(total_batches_in_train_set * batch_size)
  152. print('Epoch - {:2d} , acy_on_test:{:6.2f}%({}/{}),loss_on_test:{:6.2f}, acy_on_train:{:6.2f}%({}/{}),loss_on_train:{:6.2f}'.
  153. format(epoch_index, acy_on_test*100.0,total_correct_times_in_test_set,
  154. total_batches_in_test_set * batch_size,total_cost_in_test_set, acy_on_train*100.0,
  155. total_correct_times_in_train_set,total_batches_in_train_set * batch_size,total_cost_in_train_set))
  156. # 每轮训练完后就保存为pb文件
  157. constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, ["output"]) #out_softmax
  158. with tf.gfile.FastGFile(pb_file_path,mode='wb') as f:
  159. f.write(constant_graph.SerializeToString())
  160. def main():
  161. batch_size = 20
  162. num_epochs = 2
  163. #pb文件保存路径
  164. pb_file_path = "output/mnist-tf1.0.1.pb"
  165. g = build_network(height=28, width=28)
  166. dataset = input_data.read_data_sets()
  167. train_network(g, dataset, batch_size, num_epochs, pb_file_path)
  168. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...