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

방구석퀀트

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

2017년 8월 29일 화요일

(TF 1.1 & Slim) 4 학습된 모델 사용하기( Caltech ) - 복수 이미지 분류하기(2/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. 학습된 모델 사용하기 - 복수 이미지 분류하기(2/2)

 지난 챕터에서는 datasets 폴더에 caltech256.py 로 정의해 놓은 데이터셋에서 복수의 이미지를 불러와 분류를 해보았습니다. 이 포스팅에서는 데이터셋과 상관없는 복수의 이미지를 이용한 분류를 해 보겠습니다.

아래 코드를 UserImages_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
from matplotlib import pyplot as plt

import numpy as np
import os
import tensorflow as tf

from nets import inception
from preprocessing import inception_preprocessing

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

slim = tf.contrib.slim

image_size = inception.inception_v1.default_image_size    

with tf.Graph().as_default():

    user_images = [] # 복수의 원본 이미지
    user_processed_images = [] # 복수의 전처리된 이미지

    image_files = os.listdir("./user_images") # 분류하고 싶은 이미지가 저장된 폴더

    for i in image_files:
        image_input = tf.read_file("./user_images" +'/'+ i)
        image = tf.image.decode_jpeg(image_input, channels=3)
        user_images.append(image)
        processed_image = inception_preprocessing.preprocess_image(image, image_size, image_size, is_training=False)
        user_processed_images.append(processed_image)
        
    processed_images  = tf.expand_dims(processed_image, 0)
    
    with slim.arg_scope(inception.inception_v1_arg_scope()):
        logits, _ = inception.inception_v1(user_processed_images, num_classes=257, is_training=False)
    probabilities = tf.nn.softmax(logits)

    init_fn = slim.assign_from_checkpoint_fn(
        os.path.join(checkpoints_dir, 'model.ckpt-500'),
        slim.get_model_variables('InceptionV1'))

    with tf.Session() as sess:
        init_fn(sess)
        np_images, probabilities = sess.run([user_images, probabilities])
    
    names = os.listdir("\\tmp\\caltech256\\caltech256_photos")
    

    for files in range(len(image_files)):
        probabilitie = probabilities[files, 0:]
        sorted_inds = [i[0] for i in sorted(enumerate(-probabilitie), key=lambda x:x[1])]

        plt.figure()
        plt.imshow(np_images[files].astype(np.uint8))
        plt.axis('off')
        plt.show()
        
        for p in range(5):
            index = sorted_inds[p]
            print('Probability %0.2f%% => [%s]' % (probabilitie[index], names[index]))

기존 한장 이미지 분류에 사용했던 코드(Image_Classification_Caltech256.py)에서 이미지들을 변수 하나에 쌓아서 모델에 넣는 코드를 추가 하였습니다.

구체적으로 18,19 라인에 복수의 이미지를 저장하는 변수가 선언 되어 있고요.
21라인에서 이미지 파일 이름을 불러와
23~28라인에서 이미지 여러장을 변수 하나에 넣었습니다.
34라인에 여러장 쌓인 변수(user_processed_images)를 모델에 그냥 넣으면 되고요
43라인에 원본 이미지도 여러장이 쌓인 변수(user_images)를 넣어주기만 하면 됩니다.

분류된 결과는 43라인의 np_images에는 이미지들이 배열로 저장되고, probabilities에는 해당 이미지의 분류 결과가 역시 배열로 저장되어 있습니다.

48~59라인에서 이미지 파일 갯수(인덱스)에 따라 순차적으로 그 결과를 표시하는 코드 입니다.

위 코드에서는 user_images 라는 폴더안에 분류하고 싶은 이미지들을 복사해두고 아래 명령어를 아나콘다에서 실행 하겠습니다.
python UserImage_Classification_Caltech256.py
결과는 아래와 같습니다.( Jupyter notebook 에서 실행한 결과입니다.)




 처음엔 TF-slim 에서 다 만들어 놓은 코드를 가져다 쓰기만 했는데 이렇게 사용 목적에 맞게 코드를 만들고 수정해 보니 더 재미가 느껴지는거 같습니다.

댓글 1개:

  1. 이 프로그램을 배치 단위로 반복문에서 돌아가게 짜려면 어떤 식으로 짜는게 좋을까요??

    답글삭제

가장 많이 본 글