본문 바로가기
💻 Programming 개발

[번역] How to Use Small Experiments to Develop a Caption Generation Model in Keras

by 킴디 kimdee 2020. 3. 29.
반응형

'20 JUN : 직접 번역하며 작업한 colab 노트북 링크를 유실해서 아직 진행중입니다. 

 

--- 

원 출처 : https://machinelearningmastery.com/develop-a-caption-generation-model-in-keras/

By Jason Brownlee on Nov 24, 2017 / Last updated on Aug 7, 2019

 

How to Use Small Experiments to Develop a Caption Generation Model in Keras

Caption generation is a challenging artificial intelligence problem where a textual description must be generated for a photograph. It requires both methods from computer vision to understand the content of the image and a language model from the field of

machinelearningmastery.com

* 아래 글은 제이슨 브라운리의 "Keras에서 캡션 생성 모델을 만드는 법"을 번역한 글입니다. 

 

캡션 생성은 사진에 대한 설명을 만들어내는, 어려운 인공지능 문제입니다. 이를 해결하기 위해서는 이미지의 콘텐트를 이해하는 컴퓨터 비전과 자연어처리 분야에서 이미지에 대해 이해한 내용을 올바른 순서의 단어로 치환하는 랭귀지 모델이 필요합니다. 최근 딥러닝으로 이 문제를 해결하는 최신의 결과물을 달성했습니다. 

 

직접 데이터를 가지고 캡션 생성 모델을 개발하는 것은 매우 어려울 수 있습니다. 주로 데이터셋과 모델이 너무 크기 때문에 트레인을 하는 데에 수일이 걸리기 때문입니다. 이에 대한 대안으로 fuller 데이터셋의 작은 샘플로 모델 configuration을 탐색하는 방법이 있습니다. 

 

이 튜토리얼에서는 표준 사진 캡션 데이터셋의 적은 샘플을 이용하여 다양한 딥모델 디자인을 탐색하는 방법을 알아볼 것입니다. 튜토리얼을 끝내면 어떤 것들을 알게될까요?

 

* 사진 캡션 생성 모델링을 위해 데이터를 준비하는 방법

* 모델의 스킬을 평가하고 확률적 특성을 제어하기 위한 베이스라인과 테스트 하네스를 설계하는 법

 * 모델의 스킬, 특징 추출 모델, 워드 임베딩 등 모델의 스킬을 향상시키기 위한 프로퍼티를 평가하는 방법

 

텍스트 분류, 번역, 사진 캡션 생성, 딥러닝 모델을 개발하는 많은 방법을 저의 새 책에서 만나보세요. 30가지의 단계별 튜토리얼과 소스코드도 포함되어 있습니다. 

https://machinelearningmastery.com/deep-learning-for-nlp/

 

Deep Learning For Natural Language Processing

Deep Learning for Natural Language Processing Develop Deep Learning Models for your Natural Language Problems Working with Text is… important, under-discussed, and HARD We are awash with text, from books, papers, blogs, tweets, news, and increasingly text

machinelearningmastery.com

 

사진출처: https://www.flickr.com/photos/perry-pics/5968641588/ 

튜토리얼 개요

이 튜토리얼은 총 6개의 부분으로 되어있습니다. 

1. 데이터 준비

2. 베이스 라인 캡션 생성 모델

3. 네트워크 사이즈 파라미터

4. 피쳐 추출 모델 Configuring

5. 워드 임베딩 모델

6. 결과 분석

 

파이썬 환경

Python3와 Scipy. Scikit-learn, Pandas, Numpy, Matplotlib 

Tensorflow와 Theano 백엔드, Keras(2.0이상) 설치되어있어야 합니다. 

 

환경설정에 대해 도움이 필요하다면 아래 튜토리얼을 참고하세요. 

 

아나콘다로 머신러닝과 딥러닝을 위한 파이썬 환경 설정하는 방법

https://machinelearningmastery.com/setup-python-environment-machine-learning-deep-learning-anaconda/

 

How to Setup Your Python Environment for Machine Learning with Anaconda

It can be difficult to install a Python machine learning environment on some platforms. Python itself must be installed first and then there are many packages to install, and it can be confusing for beginners. In this tutorial, you will discover how to set

machinelearningmastery.com

 

GPU 환경에서 코드를 돌릴 것을 추천합니다. 아마존 웹서비스에서 저렴한 가격으로 GPU에 접속할 수 있습니다. 아래 튜토리얼을 참고하세요. 

 

아마존 웹서비스에서 케라스를 사용하여 대규모의 딥러닝모델을 평가하고 개발하는 방법

https://machinelearningmastery.com/develop-evaluate-large-deep-learning-models-keras-amazon-web-services/

 

How to Train Keras Deep Learning Models on AWS EC2 GPUs (step-by-step)

Keras is a Python deep learning library that provides easy and convenient access to the powerful numerical libraries like TensorFlow. Large deep learning models require a lot of compute time to run. You can run them on your CPU but it can take hours or day

machinelearningmastery.com

 

1. 데이터 준비

 

모델을 트레이닝 하기 위핸 데이터셋을 먼저 준비해야 합니다. 약 8,000장이 넘는 사진과 설명으로 구성된 Flickr8K 데이터셋을 사용해 볼 것입니다. 데이터셋은 아래에서 다운받을 수 있습니다. 

 

 * 데이터셋과 텍스트  (업데이트 : 공식 사이트에서 링크가 내려가서 저자의 깃허브 레포에서 바로 다운받을 수 있는 링크를 첨부합니다.)

https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_Dataset.zip

https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_text.zip

 

작업하고 있는 디렉토리에 사진과 설명 데이터의 압축을 풀고 각각  Flicker8k_Dataset,  Flickr8k_text 폴더에 저장합니다. 

 

데이터 준비에는 사진과 텍스트 각각 두가지 과정이 있습니다. 

 

1-1 텍스트 준비 (괜찮은 표현이 있다면 댓글로 부탁드립니다.) 

데이터셋에는 각 사진에 대한 여러 디스크립션이 포함되어 있습니다. 설명 텍스트에 약간의 정제과정을 거칠 것입니다. 먼저 디스크립션이 포함된 파일을 모두 불러올 것입니다.

# load doc into memory 문서를 메모리에 로드
def load_doc(filename):
	# open the file as read only 파일을 읽기전용으로 열기
	file = open(filename, 'r')
	# read all text 모든 텍스트를 읽기
	text = file.read()
	# close the file 파일 닫기
	file.close()
	return text

filename = 'Flickr8k_text/Flickr8k.token.txt'
# load descriptions 디스크립션 불러오기
doc = load_doc(filename)

 

각 사진에는 고유의 식별자가 있고, 사진 파일의 이름과 설명 텍스트 파일에서 사용됩니다. 다음으로 사진에 대한 설명  목록을 살펴보고, 각 사진에 대한 첫번째 설명을 저장합니다. 

 

아래에서는 load_descriptions() 라는 함수를 정의하여, 로드된 문서 텍스트가 주어질 때 디스크립션에, 사진 식별자를 딕셔너리 형태로 반환하는 과정을 거칠 것입니다. 

 

# extract descriptions for images
def load_descriptions(doc):
	mapping = dict()
	# process lines
	for line in doc.split('\n'):
		# split line by white space
		tokens = line.split()
		if len(line) < 2:
			continue
		# take the first token as the image id, the rest as the description
		image_id, image_desc = tokens[0], tokens[1:]
		# remove filename from image id
		image_id = image_id.split('.')[0]
		# convert description tokens back to string
		image_desc = ' '.join(image_desc)
		# store the first description for each image
		if image_id not in mapping:
			mapping[image_id] = image_desc
	return mapping

# parse descriptions
descriptions = load_descriptions(doc)
print('Loaded: %d ' % len(descriptions))

 

1-2 사진 준비 

 

반응형

댓글