개미들을 위한 퀀트 자동 매매 프로그램 개발자 블로그입니다. 프로그래밍과 퀀트 투자를 합니다.

방구석퀀트

네이버카페 : 방구석 퀀트 놀러오세요^^ https://cafe.naver.com/conerquant 가입해 주세요.

2017년 8월 25일 금요일

(TF 1.1 & Slim) 4 학습된 모델 사용하기( Caltech ) - 복수 이미지 분류하기(1/2)

*Tensorflow 1.9 버전 튜토리얼
1. 윈도우에 Tensorflow GPU 버전 설치하기
2 딥러닝 slim 라이브러리 설치, 학습, 평가하기
3. 내 이미지로 학습 하기 ( caltech 이미지 사용 )
4. 학습된 모델 사용하기

1. 윈도우에 Tensorflow GPU 버전 설치하기
2.1 딥러닝 slim 라이브러리 설치 및 이미지 셋 다운로드
2.2 딥러닝 모델 학습하기
2.3 딥러닝 모델 평가하기
3. 내 이미지로 학습 하기 ( caltech 이미지 사용 )
4. 학습된 모델 사용하기 - 복수 이미지 분류하기(1/2)

 지난 챕터에서 이미지 한장을 분류하는 코드를 실습해 보았습니다. 실제 실무에서는 이미지 한장이 아니라 수백, 수천, 수만장의 이미지를 한번에 분류 시켜야 할 필요가 더 많을거 같더군요. 그래서 어떻게 하면 복수의 이미지를 한번에 분류시키게 할 수 있을까...  사실 Tensorflow 문법도 모르고, Python 문법도 잘 모르는 상태라 삽질을 많이 했습니다. 근데 알고 봤더니 slim 폴더에 보면 slim_walkthrough.ipynb notebook 파일이 있는데.. 이 곳에 다 예제가 있었더군요... 그것도 모르고... 삽질만..

아래와 같이 한 파일로 만들었습니다. 아래 코드를 Images_Classification_Caltech256.py 저장 하겠습니다.


 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
from matplotlib import pyplot as plt

import numpy as np
import os
import tensorflow as tf

from nets import inception
from datasets import caltech256
from preprocessing import inception_preprocessing

checkpoints_dir = '\\tmp\\train_inception_v1_caltech256_FineTune_logs\\all'

slim = tf.contrib.slim
batch_size = 10
images_dir = '/tmp/caltech256'
image_size = inception.inception_v1.default_image_size    

def load_batch(dataset, batch_size=32, height=299, width=299, is_training=False):
    """Loads a single batch of data.
    
    Args:
      dataset: The dataset to load.
      batch_size: The number of images in the batch.
      height: The size of each image after preprocessing.
      width: The size of each image after preprocessing.
      is_training: Whether or not we're currently training or evaluating.
    
    Returns:
      images: A Tensor of size [batch_size, height, width, 3], image samples that have been preprocessed.
      images_raw: A Tensor of size [batch_size, height, width, 3], image samples that can be used for visualization.
      labels: A Tensor of size [batch_size], whose values range between 0 and dataset.num_classes.
    """
    data_provider = slim.dataset_data_provider.DatasetDataProvider(
        dataset, common_queue_capacity=32,
        common_queue_min=8)
    image_raw, label = data_provider.get(['image', 'label'])
    
    # Preprocess image for usage by Inception.
    image = inception_preprocessing.preprocess_image(image_raw, height, width, is_training=is_training)
    
    # Preprocess the image for display purposes.
    image_raw = tf.expand_dims(image_raw, 0)
    image_raw = tf.image.resize_images(image_raw, [height, width])
    image_raw = tf.squeeze(image_raw)

    # Batch it up.
    images, images_raw, labels = tf.train.batch(
          [image, image_raw, label],
          batch_size=batch_size,
          num_threads=1,
          capacity=2 * batch_size)
    
    return images, images_raw, labels

with tf.Graph().as_default():
    tf.logging.set_verbosity(tf.logging.INFO)
    
    dataset = caltech256.get_split('validation', images_dir)
    images, images_raw, labels = load_batch(dataset, height=image_size, width=image_size)
    
    # Create the model, use the default arg scope to configure the batch norm parameters.
    with slim.arg_scope(inception.inception_v1_arg_scope()):
        logits, _ = inception.inception_v1(images, num_classes=dataset.num_classes, is_training=True)

    probabilities = tf.nn.softmax(logits)
    
    checkpoint_path = tf.train.latest_checkpoint(checkpoints_dir)
    init_fn = slim.assign_from_checkpoint_fn(
      checkpoint_path,
      slim.get_variables_to_restore())
    
    with tf.Session() as sess:
        with slim.queues.QueueRunners(sess):
            sess.run(tf.initialize_local_variables())
            init_fn(sess)
            np_probabilities, np_images_raw, np_labels = sess.run([probabilities, images_raw, labels])
    
            for i in range(batch_size): 
                image = np_images_raw[i, :, :, :]
                true_label = np_labels[i]
                predicted_label = np.argmax(np_probabilities[i, :])
                predicted_name = dataset.labels_to_names[predicted_label]
                true_name = dataset.labels_to_names[true_label]
                
                plt.figure()
                plt.imshow(image.astype(np.uint8))
                plt.title('Ground Truth: [%s], Prediction [%s]' % (true_name, predicted_name))
                plt.axis('off')
                plt.show()

python Image_Classification_Caltech256.py

위와 같이 실행 시켜보면 10장에 대해서 이미지의 정답(Ground Truth)과 예측된 답(Prediction)을 순차적으로 볼 수 있습니다.

위 예제는 학습과 평가에 사용한 Caltech257 Dataset에서 이미지를 가져와 분류를 한번에 시켜보는 예제였습니다.

그렇다면... Dataset에 정의 되지 않은 이미지들을 한 폴더에 모아놓고 한번에 분류를 시키려면 코드를 어떻게 수정해야 할까요???(아시는 분 가르쳐 주세요~~)

아직은 잘 모르지만 삽질 좀 하다가... 다음 포스팅으로 돌아오겠습니다!

댓글 없음:

댓글 쓰기

가장 많이 본 글