Skip to content

Commit 3ac1e9c

Browse files
committed
image captionig added
1 parent c5f3dd3 commit 3ac1e9c

File tree

4 files changed

+266
-0
lines changed

4 files changed

+266
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import torch
2+
import torchvision.transforms as transforms
3+
import torch.utils.data as data
4+
import os
5+
import pickle
6+
import numpy as np
7+
import nltk
8+
from PIL import Image
9+
from vocab import Vocabulary
10+
from pycocotools.coco import COCO
11+
12+
13+
class CocoDataset(data.Dataset):
14+
"""COCO Custom Dataset compatible with torch.utils.data.DataLoader."""
15+
def __init__(self, root, json, vocab, transform=None):
16+
"""
17+
Args:
18+
root: image directory.
19+
json: coco annotation file path.
20+
vocab: vocabulary wrapper.
21+
transform: transformer for image.
22+
"""
23+
self.root = root
24+
self.coco = COCO(json)
25+
self.ids = list(self.coco.anns.keys())
26+
self.vocab = vocab
27+
self.transform = transform
28+
29+
def __getitem__(self, index):
30+
"""This function should return one data pair(image and caption)."""
31+
coco = self.coco
32+
vocab = self.vocab
33+
ann_id = self.ids[index]
34+
caption = coco.anns[ann_id]['caption']
35+
img_id = coco.anns[ann_id]['image_id']
36+
path = coco.loadImgs(img_id)[0]['file_name']
37+
38+
image = Image.open(os.path.join(self.root, path)).convert('RGB')
39+
if self.transform is not None:
40+
image = self.transform(image)
41+
42+
# Convert caption (string) to word ids.
43+
tokens = nltk.tokenize.word_tokenize(str(caption).lower())
44+
caption = []
45+
caption.append(vocab('<start>'))
46+
caption.extend([vocab(token) for token in tokens])
47+
caption.append(vocab('<end>'))
48+
target = torch.Tensor(caption)
49+
return image, target
50+
51+
def __len__(self):
52+
return len(self.ids)
53+
54+
55+
def collate_fn(data):
56+
"""Build mini-batch tensors from a list of (image, caption) tuples.
57+
Args:
58+
data: list of (image, caption) tuple.
59+
- image: torch tensor of shape (3, 256, 256).
60+
- caption: torch tensor of shape (?); variable length.
61+
62+
Returns:
63+
images: torch tensor of shape (batch_size, 3, 256, 256).
64+
targets: torch tensor of shape (batch_size, padded_length).
65+
lengths: list; valid length for each padded caption.
66+
"""
67+
# Sort a data list by caption length
68+
data.sort(key=lambda x: len(x[1]), reverse=True)
69+
images, captions = zip(*data)
70+
71+
# Merge images (convert tuple of 3D tensor to 4D tensor)
72+
images = torch.stack(images, 0)
73+
74+
# Merget captions (convert tuple of 1D tensor to 2D tensor)
75+
lengths = [len(cap) for cap in captions]
76+
targets = torch.zeros(len(captions), max(lengths)).long()
77+
for i, cap in enumerate(captions):
78+
end = lengths[i]
79+
targets[i, :end] = cap[:end]
80+
return images, targets, lengths
81+
82+
83+
def get_loader(root, json, vocab, transform, batch_size=100, shuffle=True, num_workers=2):
84+
"""Returns torch.utils.data.DataLoader for custom coco dataset."""
85+
# COCO custom dataset
86+
coco = CocoDataset(root=root,
87+
json=json,
88+
vocab = vocab,
89+
transform=transform)
90+
91+
# Data loader
92+
data_loader = torch.utils.data.DataLoader(dataset=coco,
93+
batch_size=batch_size,
94+
shuffle=True,
95+
num_workers=num_workers,
96+
collate_fn=collate_fn)
97+
return data_loader
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from PIL import Image
2+
import os
3+
4+
5+
def resize_image(image, size):
6+
"""Resizes an image to the given size."""
7+
return image.resize(size, Image.ANTIALIAS)
8+
9+
def resize_images(image_dir, output_dir, size):
10+
"""Resizes the images in the image_dir and save into the output_dir."""
11+
if not os.path.exists(output_dir):
12+
os.makedirs(output_dir)
13+
14+
images = os.listdir(image_dir)
15+
num_images = len(images)
16+
for i, image in enumerate(images):
17+
with open(os.path.join(image_dir, image), 'r+b') as f:
18+
with Image.open(f) as img:
19+
img = resize_image(img, size)
20+
img.save(
21+
os.path.join(output_dir, image), img.format)
22+
if i % 100 == 0:
23+
print ('[%d/%d] Resized the images and saved into %s.'
24+
%(i, num_images, output_dir))
25+
26+
def main():
27+
splits = ['train', 'val']
28+
for split in splits:
29+
image_dir = './data/%s2014/' %split
30+
output_dir = './data/%s2014resized' %split
31+
resize_images(image_dir, output_dir, (256, 256))
32+
33+
34+
if __name__ == '__main__':
35+
main()
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
from data import get_loader
2+
from vocab import Vocabulary
3+
from models import EncoderCNN, DecoderRNN
4+
from torch.autograd import Variable
5+
from torch.nn.utils.rnn import pack_padded_sequence
6+
import torch
7+
import torch.nn as nn
8+
import numpy as np
9+
import torchvision.transforms as T
10+
import pickle
11+
12+
# Hyper Parameters
13+
num_epochs = 5
14+
batch_size = 100
15+
embed_size = 128
16+
hidden_size = 512
17+
num_layers = 1
18+
learning_rate = 0.001
19+
train_image_path = './data/train2014resized/'
20+
train_json_path = './data/annotations/captions_train2014.json'
21+
22+
# Image Preprocessing
23+
transform = T.Compose([
24+
T.RandomHorizontalFlip(),
25+
T.ToTensor(),
26+
T.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))])
27+
28+
# Load Vocabulary Wrapper
29+
with open('./data/vocab.pkl', 'rb') as f:
30+
vocab = pickle.load(f)
31+
32+
# Build Dataset Loader
33+
train_loader = get_loader(train_image_path, train_json_path, vocab, transform,
34+
batch_size=batch_size, shuffle=True, num_workers=2)
35+
total_step = len(train_loader)
36+
37+
# Build Models
38+
encoder = EncoderCNN(embed_size)
39+
decoder = DecoderRNN(embed_size, hidden_size, len(vocab), num_layers)
40+
encoder.cuda()
41+
decoder.cuda()
42+
43+
# Loss and Optimizer
44+
criterion = nn.CrossEntropyLoss()
45+
optimizer = torch.optim.Adam(decoder.parameters(), lr=learning_rate)
46+
47+
# Train the Decoder
48+
for epoch in range(num_epochs):
49+
for i, (images, captions, lengths) in enumerate(train_loader):
50+
# Set mini-batch dataset
51+
images = Variable(images).cuda()
52+
captions = Variable(captions).cuda()
53+
targets = pack_padded_sequence(captions, lengths, batch_first=True)[0]
54+
55+
# Forward, Backward and Optimize
56+
decoder.zero_grad()
57+
features = encoder(images)
58+
outputs = decoder(features, captions, lengths)
59+
loss = criterion(outputs, targets)
60+
loss.backward()
61+
optimizer.step()
62+
63+
if i % 100 == 0:
64+
print('Epoch [%d/%d], Step [%d/%d], Loss: %.4f, Perplexity: %5.4f'
65+
%(epoch, num_epochs, i, total_step, loss.data[0], np.exp(loss.data[0])))
66+
67+
# Save the Model
68+
torch.save(decoder, 'decoder.pkl')
69+
torch.save(encoder, 'encoder.pkl')
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Create a vocabulary wrapper
2+
import nltk
3+
import pickle
4+
from collections import Counter
5+
from pycocotools.coco import COCO
6+
7+
8+
class Vocabulary(object):
9+
"""Simple vocabulary wrapper."""
10+
def __init__(self):
11+
self.word2idx = {}
12+
self.idx2word = {}
13+
self.idx = 0
14+
15+
def add_word(self, word):
16+
if not word in self.word2idx:
17+
self.word2idx[word] = self.idx
18+
self.idx2word[self.idx] = word
19+
self.idx += 1
20+
21+
def __call__(self, word):
22+
if not word in self.word2idx:
23+
return self.word2idx['<unk>']
24+
return self.word2idx[word]
25+
26+
def __len__(self):
27+
return len(self.word2idx)
28+
29+
def build_vocab(json, threshold):
30+
"""Build a simple vocabulary wrapper."""
31+
coco = COCO(json)
32+
counter = Counter()
33+
ids = coco.anns.keys()
34+
for i, id in enumerate(ids):
35+
caption = str(coco.anns[id]['caption'])
36+
tokens = nltk.tokenize.word_tokenize(caption.lower())
37+
counter.update(tokens)
38+
39+
if i % 1000 == 0:
40+
print("[%d/%d] tokenized the captions." %(i, len(ids)))
41+
42+
# Discard if the occurrence of the word is less than min_word_cnt.
43+
words = [word for word, cnt in counter.items() if cnt >= threshold]
44+
45+
# Create a vocab wrapper and add some special tokens.
46+
vocab = Vocabulary()
47+
vocab.add_word('<pad>')
48+
vocab.add_word('<start>')
49+
vocab.add_word('<end>')
50+
vocab.add_word('<unk>')
51+
52+
# Add words to the vocabulary.
53+
for i, word in enumerate(words):
54+
vocab.add_word(word)
55+
return vocab
56+
57+
def main():
58+
vocab = create_vocab(json='./data/annotations/captions_train2014.json',
59+
threshold=4)
60+
with open('./data/vocab.pkl', 'wb') as f:
61+
pickle.dump(vocab, f, pickle.HIGHEST_PROTOCOL)
62+
print("Saved vocabulary file to ", './data/vocab.pkl')
63+
64+
if __name__ == '__main__':
65+
main()

0 commit comments

Comments
 (0)