tensorflow訓練本身的數據集實現CNN圖像分類2(保存模型&測試單張圖片)

  神經網絡訓練的時候,咱們須要將模型保存下來,方便後面繼續訓練或者用訓練好的模型進行測試。所以,咱們須要建立一個saver保存模型git

 

 1 def run_training():
 2     data_dir = 'C:/Users/wk/Desktop/bky/dataSet/'
 3     log_dir = 'C:/Users/wk/Desktop/bky/log/'
 4     image,label = inputData.get_files(data_dir)
 5     image_batches,label_batches = inputData.get_batches(image,label,32,32,16,20)
 6     print(image_batches.shape)
 7     p = model.mmodel(image_batches,16)
 8     cost = model.loss(p,label_batches)
 9     train_op = model.training(cost,0.001)
10     acc = model.get_accuracy(p,label_batches)
11     
12     sess = tf.Session()
13     init = tf.global_variables_initializer()
14     sess.run(init)
15     saver = tf.train.Saver()
16     coord = tf.train.Coordinator()
17     threads = tf.train.start_queue_runners(sess = sess,coord = coord)
18     
19     try:
20        for step in np.arange(1000):
21            print(step)
22            if coord.should_stop():
23                break
24            _,train_acc,train_loss = sess.run([train_op,acc,cost])
25            print("loss:{} accuracy:{}".format(train_loss,train_acc))
26            if step % 100 == 0:
27                check = os.path.join(log_dir,"model.ckpt")
28                saver.save(sess,check,global_step = step)
29     except tf.errors.OutOfRangeError:
30         print("Done!!!")
31     finally:
32         coord.request_stop()
33     coord.join(threads)
34     sess.close()

 

  訓練好的模型信息會記錄在checkpoint文件中,大體以下:網絡

 

model_checkpoint_path: "C:/Users/wk/Desktop/bky/log/model.ckpt-100"
all_model_checkpoint_paths: "C:/Users/wk/Desktop/bky/log/model.ckpt-0"
all_model_checkpoint_paths: "C:/Users/wk/Desktop/bky/log/model.ckpt-100"

 

  其他還會生成一些文件,分別記錄了模型參數等信息,後邊測試的時候程序會讀取checkpoint文件去加載這些真正的數據文件ide

 

  構建好神經網絡進行訓練完成後,若是用以前的代碼直接進行測試,會報shape不符合的錯誤,大體是卷積層的輸入與圖像的shape不一致,這是由於上篇的代碼,將weights和biases定義在了模型的外面,調用模型的時候,出現valueError的錯誤。函數

  所以,咱們須要將參數定義在模型裏面,加載訓練好的模型參數時,訓練好的參數纔可以真正初始化模型。重寫模型函數以下測試

 

 1 def mmodel(images,batch_size):
 2     with tf.variable_scope('conv1') as scope:
 3         weights = tf.get_variable('weights', 
 4                                   shape = [3,3,3, 16],
 5                                   dtype = tf.float32, 
 6                                   initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
 7         biases = tf.get_variable('biases', 
 8                                  shape=[16],
 9                                  dtype=tf.float32,
10                                  initializer=tf.constant_initializer(0.1))
11         conv = tf.nn.conv2d(images, weights, strides=[1,1,1,1], padding='SAME')
12         pre_activation = tf.nn.bias_add(conv, biases)
13         conv1 = tf.nn.relu(pre_activation, name= scope.name)
14     with tf.variable_scope('pooling1_lrn') as scope:
15         pool1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1],strides=[1,2,2,1],
16                                padding='SAME', name='pooling1')
17         norm1 = tf.nn.lrn(pool1, depth_radius=4, bias=1.0, alpha=0.001/9.0,
18                           beta=0.75,name='norm1')
19     with tf.variable_scope('conv2') as scope:
20         weights = tf.get_variable('weights',
21                                   shape=[3,3,16,128],
22                                   dtype=tf.float32,
23                                   initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
24         biases = tf.get_variable('biases',
25                                  shape=[128], 
26                                  dtype=tf.float32,
27                                  initializer=tf.constant_initializer(0.1))
28         conv = tf.nn.conv2d(norm1, weights, strides=[1,1,1,1],padding='SAME')
29         pre_activation = tf.nn.bias_add(conv, biases)
30         conv2 = tf.nn.relu(pre_activation, name='conv2')    
31     with tf.variable_scope('pooling2_lrn') as scope:
32         norm2 = tf.nn.lrn(conv2, depth_radius=4, bias=1.0, alpha=0.001/9.0,
33                           beta=0.75,name='norm2')
34         pool2 = tf.nn.max_pool(norm2, ksize=[1,2,2,1], strides=[1,1,1,1],
35                                padding='SAME',name='pooling2')
36     with tf.variable_scope('local3') as scope:
37         reshape = tf.reshape(pool2, shape=[batch_size, -1])
38         dim = reshape.get_shape()[1].value
39         weights = tf.get_variable('weights',
40                                   shape=[dim,4096],
41                                   dtype=tf.float32,
42                                   initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
43         biases = tf.get_variable('biases',
44                                  shape=[4096],
45                                  dtype=tf.float32, 
46                                  initializer=tf.constant_initializer(0.1))
47         local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name) 
48     with tf.variable_scope('softmax_linear') as scope:
49         weights = tf.get_variable('softmax_linear',
50                                   shape=[4096, 2],
51                                   dtype=tf.float32,
52                                   initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
53         biases = tf.get_variable('biases', 
54                                  shape=[2],
55                                  dtype=tf.float32, 
56                                  initializer=tf.constant_initializer(0.1))
57         softmax_linear = tf.add(tf.matmul(local3, weights), biases, name='softmax_linear')
58     return softmax_linear

 

 測試訓練好的模型

首先獲取一張測試圖像spa

1 def get_one_image(img_dir):
2     image = Image.open(img_dir)
3     plt.imshow(image)
4     image = image.resize([32, 32])
5     image_arr = np.array(image)
6     return image_arr

加載模型,計算測試結果rest

 1 def test(test_file):
 2     log_dir = 'C:/Users/wk/Desktop/bky/log/'
 3     image_arr = get_one_image(test_file)
 4     
 5     with tf.Graph().as_default():
 6         image = tf.cast(image_arr, tf.float32)
 7         image = tf.image.per_image_standardization(image)
 8         image = tf.reshape(image, [1,32, 32, 3])
 9         print(image.shape)
10         p = model.mmodel(image,1)
11         logits = tf.nn.softmax(p)
12         x = tf.placeholder(tf.float32,shape = [32,32,3])
13         saver = tf.train.Saver()
14         with tf.Session() as sess:
15             ckpt = tf.train.get_checkpoint_state(log_dir)
16             if ckpt and ckpt.model_checkpoint_path:
17                 global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
18                 saver.restore(sess, ckpt.model_checkpoint_path)
19                 print('Loading success)
20             else:
21                 print('No checkpoint')
22             prediction = sess.run(logits, feed_dict={x: image_arr})
23             max_index = np.argmax(prediction)
24             print(max_index)

前面主要是將測試圖片標準化爲網絡的輸入圖像,15-19是加載模型文件,而後將圖像輸入到模型裏便可code

相關文章
相關標籤/搜索