피곤핑
코딩일탈
피곤핑
전체 방문자
오늘
어제
  • 분류 전체보기
    • Kotlin & Java
    • Spring
      • Spring Security
      • Spring
    • 네트워크
    • JavaScript & Node js
    • Docker
    • Python3
    • Unity
    • 딥러닝
    • 객체지향프로그래밍
    • Error 보고서
    • 나의 이야기 & 회고
    • HTML & CSS
    • Archive
    • 독서

블로그 메뉴

  • 홈
  • 방명록

공지사항

인기 글

태그

  • 오블완
  • Client
  • 코딩테스트준비
  • JavaScript
  • 항해99
  • nodejs
  • 99클럽
  • 개발자취업
  • 티스토리챌린지
  • TiL

최근 댓글

hELLO · Designed By 정상우.
피곤핑

코딩일탈

0807 사전훈련된컨브넷사용하기 - VGG16합성곱
딥러닝

0807 사전훈련된컨브넷사용하기 - VGG16합성곱

2019. 8. 7. 13:06

 - VGG 네트워크 다운받기

from keras.applications import VGG16

conv_base = VGG16(weights = 'imagenet', ## 모델을 초기화할 가중치 체크포인트 지정
                 include_top = False, ## 최상위 완전 연결 분류기를 포함할지 안할지
                 input_shape = (150, 150, 3)) ## 이미지 텐서의 크기

 - 합성곱 구조 보기

conv_base.summary()

 - ImageDataGenerator를 사용하여 이미지와 레이블을 넘파이 배열로 추출

 - conv_base모델의 predict 메서드를 호출하여 이 이미지에서 특성을 추출

import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator

base_dir = './datasets/cats_and_dogs_small'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
test_dir = os.path.join(base_dir, 'test')

datagen = ImageDataGenerator(rescale=1./255)
batch_size = 20

 

 - 특성 추출 함수

def extract_features(directory, sample_count) :
    features = np.zeros(shape=(sample_count, 4, 4, 512))
    labels = np.zeros(shape=(sample_count))
    generator = datagen.flow_from_directory(
    directory,
    target_size = (150,150),
    batch_size = batch_size,
    class_mode = 'binary')
    
    i=0
    for inputs_batch ,labels_batch in generator:
        features_batch = conv_base.predict(inputs_batch)
        features[i * batch_size : (i+1) * batch_size] = features_batch
        labels[i * batch_size : (i+1) * batch_size] = labels_batch
        i+=1
        if i * batch_size >= sample_count :
            break ## 제너레이터는 루프 안에서 무한하게 데이터를 만들어내므로
                  ## 모든 이미지를 한 번씩 처리하고 나면 중지해야함
    return features, labels
train_features, train_labels = extract_features(train_dir, 2000)
validation_features, validation_labels = extract_features(validation_dir, 1000)
test_features, test_labels = extract_features(test_dir, 1000)

 

-  완전연결분류기에 주입하기전에 Flatten() 해주는 코드

 model의 layer같은 경우에는 model.add하는 과정에서 Flatten() 을 해주었는데 이런 array 같은경우에는 직접

reshape를 해주어야함.

train_features = np.reshape(train_features, (2000, 4 * 4 * 512))
validation_features = np.reshape(validation_features, (1000, 4* 4* 512))
test_features = np.reshape(test_features, (1000, 4*4*512))

 

 - 정의하고 훈련하기

from keras import models
from keras import layers
from keras import optimizers

model = models.Sequential()
model.add(layers.Dense(256, activation='relu', input_dim= 4*4*512))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(1, activation='sigmoid'))

model.compile(optimizer = optimizers.RMSprop(lr=2e-5),
             loss='binary_crossentropy',
             metrics=['acc'])

history = model.fit(train_features, train_labels,
                   epochs=30,
                   batch_size=20,
                   validation_data = (validation_features, validation_labels))

 

 

- 그래프로 표현하기

import matplotlib.pyplot as plt

acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs, acc, 'bo', label = 'Training acc')
plt.plot(epochs, val_acc, 'b', label = 'Validation acc')
plt.title('Training and validation accuracy')
plt.legend()

plt.figure()

plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()

'딥러닝' 카테고리의 다른 글

0807 6장 텍스트 데이터 다루기 [Embedding층에 사용할 IMDB 데이터 로드하기]  (0) 2019.08.07
0807 미세조정 fine-tuning  (0) 2019.08.07
0806 kaggle 자료 이용해서 컨브넷 훈련하기 - 소규모데이터  (0) 2019.08.06
0806 합성곱 신경망  (0) 2019.08.06
0806 +) 가중치규제, 드롭아웃  (0) 2019.08.06
    '딥러닝' 카테고리의 다른 글
    • 0807 6장 텍스트 데이터 다루기 [Embedding층에 사용할 IMDB 데이터 로드하기]
    • 0807 미세조정 fine-tuning
    • 0806 kaggle 자료 이용해서 컨브넷 훈련하기 - 소규모데이터
    • 0806 합성곱 신경망
    피곤핑
    피곤핑

    티스토리툴바