show,attend and tell(image caption论文复现总结)

小咪咪 2023-01-23 13:49 232阅读 0赞

论文中的核心思想

GitHub上的Image-Caption项目https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Image-Captioning

研究的问题—Image Caption

为图片自动生成caption的任务类似于场景理解,这是cv领域的一个核心问题。要想解决这个问题,不仅要求你的模型能够识别出图片中有什么物体,还得能够将图片中出现的场景与自然语言相联系。问题的核心是模仿人类将大量重要的视觉信息压缩成一句抽象的描述性语言。

解决问题的思路

2014年左右由于AlexNet,VGGNet等深度卷积神经网络的出现,使得Image Caption成为了一项研究的热点。一种新的解决问题的范式是,利用CNN当作提取图像特征向量的Encoder,RNN通过传递过来的特征向量decode出自然语言序列。本篇论文这种解决问题的思路之上增加了attention机制,对feature map每个像素点进行概率的估计,再进行加权求和。这种思想来自于,人们在观察图像中倾向于关注那些有用的信息,而忽略掉大量无用的信息。
至此我们确定复现该论文的基本思想是CNN + LSTM (RNN的变体)+ Attention.
在这里插入图片描述

本篇文章的主要贡献

  • 提出了两种基于attention的Image Caption生成器,本篇博文介绍的是能够利用BP算法训练的确定性的attention机制
  • 可视化了attention在每个time step上focus的点
  • 量化了加入attention机制以后网络在Flickr8k,Flickr30k,MS COCO的性能

模型细节

Encoder

使用CNN来提取出L个的特征向量 a \bold a a,每个向量都代表了一个feature map:
a = { a 1 , a 2 , . . . , a L } , a i ∈ R D \bold a = \{a_1,a_2,…,a_L\},a_i ∈R^D a={ a1​,a2​,…,aL​},ai​∈RD
这一部分很容易实现,我们可以利用VGGNet,Inception等已经在ImageNet上预训练好的CNN,将最后的flatten操作和全连接层去掉,直接得到一个feature map set。

Decoder

使用了LSTM来在每个time step上生成一个word,LSTM的输入是被上一个time step的hidden state和cell state以及当前的context向量,而LSTM的输出是这一时刻的hidden_state和cell_state。

Attention

attention在这个模型中的作用就是生成Decoder每一个time step的context向量。利用CNN提取出来的L个特征向量 a \bold a a以及LSTM输出的 h t − 1 \bold h_{t-1} ht−1​通过三个线性层以及一个softmax操作算出每一个像素点成为预测这个time step word的概率,再利用这个概率值对 a \bold a a加权求和输出。输出的向量与上一个time step的词向量进行拼接操作,作为这一时刻的context向量

模型代码的复现

Encoder的实现

这里的Encoder中使用的是预训练好的resnet101,去除了最后两层的flatten,fully_connected_network,最后得到了2048个特征图

  1. # models.py
  2. import torch
  3. from torch import nn
  4. import torchvision
  5. class Encoder(nn.Module):
  6. def __init__(self,img_size=14):
  7. #img_size决定了最后feature map的宽高是多少,这里默认是 14 * 14
  8. super().__init__()
  9. resnet = torchvision.models.resnet101(pretrained=True)#加载预训练的模型
  10. modules = list(resnet.children())[:-2] #children本身对应的是个generator,转换成list之后丢弃最后的两项
  11. self.resnet = nn.Sequential(*modules) #利用自带的序列容器将modules逐个装入
  12. self.adaptive_pool = nn.AdaptiveAvgPool2d((img_size,img_size))#因为不确定输入图片的大小,使用自适应的池化层将特征图转化成固定的大小
  13. def forward(self,images):
  14. #images:shape[batch_size,3,height,width]
  15. out = self.resnet(images)
  16. out = self.adaptive_pool(out) #[batch_size,2048,img_size,img_size]
  17. out = out.permute(0,2,3,1)#将轴的顺序做下调整,方便后面的计算#[batch_size,img_size,img_size,2048]
  18. return out

在这里插入图片描述
这里随机生成了一个batch的数据,输出的数据的shape与一开始的推测是一致的

Attention的实现

  1. # models.py
  2. class Attention(nn.Module):
  3. def __init__(self,encode_dim,decode_dim,attention_dim):
  4. super().__init__()
  5. #对象属性的初始化
  6. self.encode_dim = encode_dim
  7. self.decode_dim = decode_dim
  8. self.attention_dim = attention_dim
  9. self.e_att = nn.Linear(encode_dim,attention_dim)#将cnn输出的feature转换成特定维度的线性层
  10. self.d_att = nn.Linear(decode_dim,attention_dim) #将decode输出的hidden_state转换成特定维度的线性层
  11. self.ful_att = nn.Linear(attention_dim,1)
  12. self.softmax = nn.Softmax(dim=1)
  13. self.relu = nn.ReLU()
  14. def forward(self,encoder_out,hidden_state):
  15. #encoder_out [batch_size,196,encoder_dim],196代表特征图上的196个像素点
  16. att1 = self.e_att(encoder_out) #[batch_size 196,attention_dim]
  17. att2 = self.d_att(hidden_state)#[batch_size,attention_dim]
  18. att = self.ful_att(self.relu(att1 + att2.unsqueeze(1)))#[batch_size,196,1]
  19. att = att.squeeze(2)
  20. alpha = self.softmax(att)#[batch_size,196] #每个像素的概率被计算出来了
  21. awe = (encoder_out * alpha.unsqueeze(2)).sum(dim=1)#每个像素点加权求和
  22. return awe,alpha

在这里插入图片描述
在这里插入图片描述

Decoder的实现

  1. # models.py
  2. class Decoder(nn.Module):
  3. def __init__(self,encode_dim,decode_dim,attention_dim,embed_dim,vocab_size,dropout):
  4. super().__init__()
  5. self.encode_dim = encode_dim #feature map的个数
  6. self.decode_dim = decode_dim #decoder的向量维数
  7. self.attention_dim = attention_dim #设计的神经网络神经元的个数
  8. self.vocab_size = vocab_size #词典的大小
  9. self.embed_dim = embed_dim #每个词向量的维度大小
  10. self.attention = Attention(encode_dim,decode_dim,attention_dim)
  11. self.embeddings = nn.Embedding(vocab_size,embed_dim)
  12. self.dropout = nn.Dropout(p=dropout)
  13. self.sigmoid = nn.Sigmoid()
  14. self.fc = nn.Linear(decode_dim,vocab_size)
  15. self.f_beta = nn.Linear(decode_dim,encode_dim)
  16. self.init_h = nn.Linear(encode_dim,decode_dim)
  17. self.init_c = nn.Linear(encode_dim,decode_dim)
  18. self.lstm = nn.LSTMCell((encode_dim + embed_dim),decode_dim)
  19. self.init_weight() #对一些参数进行初始化
  20. pass
  21. def init_weight(self):
  22. self.embeddings.weight.data.uniform_(-0.1, 0.1)
  23. self.fc.bias.data.fill_(0)
  24. self.fc.weight.data.uniform_(-0.1, 0.1)
  25. def init_hidden(self,encoder_out):
  26. #encoder_out[batch_size,num_pixels,encode_dim]
  27. mean_encoder_out = encoder_out.sum(dim=1)#shape [batch_size,encode_dim]
  28. h = self.init_h(mean_encoder_out)
  29. c = self.init_c(mean_encoder_out)
  30. return h, c
  31. def forward(self,encoder_out,encode_captions,caplens):
  32. """ encoder_out:shape[batch_size,img_size,img_size,encoder_dim] encoder_captions是被序列化的caption[batch_size,max_len] max_len表示所有caption被填充到统一长度 caplens [batch_size,1]每个caption对应的长度 """
  33. #将高和宽的轴展开,看作height * width个像素点
  34. batch_size = encoder_out.size(0)
  35. encoder_out = encoder_out.reshape(batch_size,-1,self.encode_dim) #[batch_size,num_pixels,encoder_dim]
  36. num_pixels = encoder_out.size(1)
  37. #将输入数据进行降序排序,这里排序的目的是为了后面在每个时间步进行decode时方便,具体作用在后面代码解释
  38. caplens,sort_ind = caplens.view(-1).sort(dim = 0,descending=True)
  39. encoder_out = encoder_out[sort_ind]
  40. encode_captions = encode_captions[sort_ind]
  41. embeddings = self.embeddings(encode_captions)#shape[batch_size,max_len,embed_dim]
  42. #hidden_state和cell_state的初始状态由encoder_out通过两个全连接神经网络来获得
  43. h,c = self.init_hidden(encoder_out)
  44. #这里经过编码的caption是 《start》 + 原先序列长度 + 《end》,而我们decode的时候start不需要,所以需要的时间步减1
  45. decode_length = (caplens - 1).tolist()
  46. predictions = torch.ones(batch_size,max(decode_length),self.vocab_size)
  47. alphas = torch.ones(batch_size,max(decode_length),num_pixels)
  48. for t in range(max(decode_length)):
  49. """ 这里说明一下前面进行降序排列的原因,因为每个caption的实际长度不一样(caplens中进行了记录),所以decode的长度也不一样, 显然,caption越长,decode的长度就越长,下面的batch_size_t就是统计本次时间步还有多少需要decode,而需要decode都在序列的 前面 """
  50. batch_size_t = sum([l > t for l in decode_length])#统计本次时间步前多少需要decode
  51. awe,alpha = self.attention(encoder_out[:batch_size_t],h[:batch_size_t])
  52. gate = self.sigmoid(self.f_beta(h[:batch_size_t]))#[batch_size,encode_dim] 门单元,决定awe那些像素点本次被需要
  53. awe = awe * gate
  54. context = torch.cat([awe,embeddings[:batch_size_t,t,:]],dim=1)#[batch_size,encode_dim + embed_dim]
  55. h,c = self.lstm(
  56. context,(h[:batch_size_t],c[:batch_size_t])
  57. )
  58. preds = self.fc(self.dropout(h)) #[batch_size,vocab_size]本次预测的结果,词表中的每一个单词都有一个对应的概率
  59. predictions[:batch_size_t,t,:] = preds
  60. alphas[:batch_size_t,t,:] = alpha
  61. return predictions,encode_captions,decode_length,alphas,sort_ind
  62. pass

在这里插入图片描述
在这里插入图片描述

所用数据集的介绍

论文中提到了三个标准数据集Flickr8k,Flickr30k,MS COCO,为了方便起见,我使用的是较小的Flickr8k数据集
Flickr8k的图片文件名和所对应的caption用一个json文件保存了起来,json文件大概格式如下

  1. ”“”
  2. json文件中除了images以外的字段这个项目用不到就没有列出,imagessentencessplit以及filename字段比较重要
  3. split表示的是数据集划分{ 'train','val','test'}
  4. {
  5. "images":[
  6. {
  7. "sentids":[0,1,2,3,4],
  8. "imgid":0,
  9. "sentences":[
  10. {
  11. "tokens":["a","black","dog"],
  12. "raw":...,
  13. "imgid":0,
  14. "sentid":0
  15. }
  16. ],
  17. "split":"train",
  18. "filename":"...."
  19. },
  20. ],
  21. }
  22. “”“

接下来我们处理文件需要完成下面几个目标:
1.将所有图片通过文件名读入并保存成一个hdf5文件,这么做的原因是从磁盘中读入一个整体的文件效率更高,而一张张从文件夹中读取图片效率太低了。
2.遍历每张图片对应的sentences数组,其中的token是已经做了分词的caption,如果caption的长度小于最大长度(如我们不能让caption的长度超过100),我们将其保存到该图片对应的caption数组中。最后保证每个image都有对应的5个caption,如果不够就随机重复,如果超过就sample来随机抽取5个。
3.在读入caption构建一个词频表,最后将词频低于最小阈值的单词删除,并建立一张word_map的字典
4.将caption数组,word_map,caplens用json格式进行保存

  1. # utils.py
  2. from imageio import imread
  3. from PIL import Image
  4. def create_input_file(image_folder,json_path,out_folder,cap_per_image = 5,min_word_freq = 5,max_len = 48):
  5. """ image_folder:image文件夹所在的路径 json_path json文件的完整路径 out_folder输出的文件保存在哪儿 cap_per_image 每张图片应该有多少caption min_word_freq最小词频 max_len caption中token最多数 """
  6. #把所需要的json格式文件加载进来
  7. with open(json_path,'r') as j:
  8. data = json.load(j)
  9. images = data['images']
  10. train_images_list = []
  11. train_captions_list = []
  12. val_images_list = []
  13. val_captions_list = []
  14. test_images_list = []
  15. test_captions_list = []
  16. word_freq = Counter() #counter是一个字典,不过有个方便更新词频的方法update
  17. for img in images:
  18. captions = [] #用于保存每个对应image的caption
  19. for sentence in img['sentences']:
  20. word_freq.update(sentence['tokens'])
  21. if len(sentence['tokens'])<= max_len:
  22. captions.append(sentence['tokens'])#如果这个caption比最大长度短就增加
  23. if len(captions) == 0:continue
  24. if len(captions) < cap_per_image:
  25. captions = captions + [choice(captions) for _ in range(cap_per_image - len(captions))] #choice是从caption中随机取一个元素
  26. elif len(captions) > cap_per_image:
  27. captions = sample(captions,k=cap_per_image) #超过了就进行随机取样
  28. assert len(captions) == cap_per_image
  29. if img['split'] in { 'train','restval'}:
  30. train_images_list.append(img['filename'])
  31. train_captions_list.append(captions)
  32. elif img['split'] == 'val':
  33. val_images_list.append(img['filename'])
  34. val_captions_list.append(captions)
  35. elif img['split'] == 'test':
  36. test_images_list.append(img['filename'])
  37. test_captions_list.append(captions)
  38. assert len(train_images_list) == len(train_captions_list)
  39. assert len(val_images_list) == len(val_captions_list)
  40. assert len(test_images_list) == len(test_captions_list)
  41. word = [w for w in word_freq if word_freq[w] > min_word_freq] #根据词频来筛掉单词
  42. #构建一个word_map出来
  43. word_map = { w:i+1 for i,w in enumerate(word)}
  44. word_map['<start>'] = len(word_map) + 1
  45. word_map['<end>'] = len(word_map) + 1
  46. word_map['<unk>'] = len(word_map) + 1
  47. word_map['<pad>'] = 0
  48. base_name = str(cap_per_image) + '_cap_per_image_' + str(min_word_freq) + '_min_word_freq' #这里的base文件名可以自己随便定义
  49. seed(223)
  50. #下面开始保存image,captions和caplens
  51. for img_paths,img_caps,split in [
  52. (test_images_list,test_captions_list,'TEST'),
  53. (val_images_list,val_captions_list,'VAL'),
  54. (train_images_list,train_captions_list,'TRAIN')
  55. ]:
  56. with h5py.File(os.path.join(out_folder,split + '_IMAGES_' + base_name + '.hdf5'),'a') as h:
  57. h.attrs['captions_per_image'] = cap_per_image
  58. images = h.create_dataset('images',(len(img_paths),3,256,256),dtype='uint8')
  59. enc_captions = list()
  60. caplens = list()
  61. print("start to store {0} images..." .format(split))
  62. for i,path in enumerate(tqdm(img_paths)):
  63. captions = img_caps[i] #注意这里要把第i个图片对应的caption取出来
  64. path = os.path.join(image_folder,path)
  65. img = imread(path) #拿到了第i个图片的数据,下面进行一些变形
  66. img = numpy.array(Image.fromarray(img).resize((256,256)))
  67. if len(img.shape) == 2:
  68. img = img[:,:,numpy.newaxis]
  69. img = numpy.concatenate([img,img,img],dim=2)
  70. img = img.transpose(2,0,1)#这几步的目的是将img转换成(3,256,256)
  71. images[i] = img #保存第i个图片
  72. for j,caption in enumerate(captions):
  73. en_cap = [word_map['<start>']] + [word_map.get(w,word_map['<unk>']) for w in caption]\
  74. + [word_map['<end>']] + [word_map['<pad>']] * (max_len - len(caption))
  75. enc_captions.append(en_cap)
  76. caplens.append(len(caption) + 2)
  77. assert images.shape[0] * cap_per_image == len(enc_captions) == len(caplens)
  78. with open(os.path.join(out_folder,split + '_CAPTIONS_' + base_name + '.json'),'w') as j:
  79. json.dump(enc_captions,j)
  80. with open(os.path.join(out_folder,split + '_CAPLENS_' + base_name + '.json'),'w') as j:
  81. json.dump(caplens,j)
  82. with open(os.path.join(out_folder,'WORDMAP_' + base_name +'.json'),'w') as j:
  83. json.dump(word_map,j)

在这里插入图片描述

创建我们实验所需要的dataset类

我们已经把所有图片文件保存在hdf5文件中,captions和caplens,word_map都保存在了对应json文件中,值得注意的一点是按照上面的代码逻辑,captions和caplens的长度是image数量的caption_per_image倍。
创建数据集的目标:

  • 将所需要的三个文件加载进来
  • 训练模式下每个getitem需要返回一张图片,一个caption和相对应的caplens
  • validate模式下需要将图像对应的所有caption全部返回

    dataset.py

    from torch.utils.data import Dataset
    class CaptionDataset(Dataset):

    1. def __init__(self,data_folder,base_name,split,transform=None):
    2. self.split = split
    3. self.transform = transform
    4. h = h5py.File(os.path.join(data_folder,split+ '_IMAGES_' + base_name + '.hdf5'),'r')
    5. self.images = h['images']
    6. self.cpi = h.attrs['captions_per_image']
    7. with open(os.path.join(data_folder,split + '_CAPLENS_' + base_name + '.json'),'r') as j:
    8. self.caplens = json.load(j)
    9. with open(os.path.join(data_folder,split + '_CAPTIONS_' + base_name + '.json'),'r') as j:
    10. self.captions = json.load(j)
    11. def __getitem__(self,i):
    12. img = torch.tensor(self.images[i // self.cpi]/255.)
    13. if self.transform:
    14. img = self.transform(img)
    15. caplen = torch.tensor([self.caplens[i]])
    16. caption = torch.tensor(self.captions[i])
    17. if self.split == 'TRAIN':
    18. return img,caption,caplen
    19. else:
    20. all_captions = torch.tensor(self.captions[(i // self.cpi) * self.cpi: (i // self.cpi) * self.cpi + self.cpi])
    21. return img,caption,caplen,all_captions
    22. def __len__(self):
    23. return len(self.captions)

在这里插入图片描述
在这里插入图片描述

开始训练模型

截至目前为止,我们已经实现了需要的模型,将我们需要的数据集处理成了训练所需要的Dataset类型,在每个单元都进行了测试,保证在模型训练过程中不会发生意料之外的错误,下面开始设计训练评估模型所需要的一些函数.

  1. #utils.py
  2. #为了记录一些评价指标的变化而创建的类
  3. class AverageMetric(object):
  4. def __init__(self):
  5. self.reset()
  6. pass
  7. def reset(self):
  8. self.val = 0
  9. self.count = 0
  10. self.avg = 0
  11. self.sum = 0
  12. def update(self,val,n = 1):
  13. self.val = val
  14. self.sum += val * n
  15. self.count += n
  16. self.avg = self.sum / self.count
  17. # utils.py
  18. #为了计算top5的准确率
  19. def accuracy(predict,targets,k):
  20. #predict:[num_words,vocab_size] 注意经过pack_padded_sequence处理后batch轴消失了,而是把decode的长度做了累和
  21. #targets:[num_words]
  22. num_words = predict.size(0)#看看一共需要比较多少个单词
  23. targets = targets.view(-1,1) #[num_words,1]
  24. _,ind = predict.topk(k,1,True,True) #这里的index就是对应word的索引 #[num_words,k]
  25. targets = targets.expand_as(ind) #[num_words,k]
  26. correct = targets.eq(ind).sum().item()
  27. return correct / num_words * 100.0

在这里插入图片描述
这里模拟了两个word的情况,第一个word中前5概率的索引是[1,6,3,5,4]包含了1,所以这个word被判定正确,第二个word中5概率的索引是
[4,2,0,1,3] 不包括7,所以被判定错误,最后的正确率是50%

  1. from time import time
  2. def train(train_loader,encoder,decoder,encoder_optimizer,decoder_optimizer,criterion,epoch):
  3. ''' train_loader:在训练模式下,train_loader在每一次迭代过程中返回给我们的数据是: img:[batch_size,3,256,256] caption:[batch_size,max_len + 2]这里之所以加2是因为包含了<start>和<end> caplen:[batch_size,1] '''
  4. encoder.train()
  5. decoder.train()
  6. batch_time = AverageMetric() #为了记录一个batch的时间
  7. data_load = AverageMetric() #记录加载一次数据所用的时间
  8. losses = AverageMetric() #loss值
  9. top5acc = AverageMetric() #top5准确度,就是每次预测概率最高的五个词与正确答案比对,有一个对了就算正确
  10. start = time()
  11. for i, (img,caption,caplen) in enumerate(train_loader):
  12. data_load.updata(time() - start)
  13. img = img.to(device)
  14. caption = caption.to(device)
  15. caplen = caplen.to(device)
  16. encoder_out = encoder(img)
  17. predict,encode_captions,decode_length,alphas,sort_ind = decoder(encoder_out,caption,caplen)
  18. #predict [batch_size,max(decode_length),vocab_size]
  19. #encode_captions:[batch_size,max_len + 2]
  20. predict_copy = predict.clone() #后面用来计算top5accuracy的使用
  21. predict = predict.argmax(dim=2) #拿到每个序列每个位置概率最大的那个单词,用于后面做cross_entropy
  22. targets = encode_captions[:,1:] #每个caption的第一个<start>需要被去掉因为他不是被decode出来的
  23. predict = pack_padded_sequence(predict,decode_length,batch_first=True).data.to(device)
  24. targets = pack_padded_sequence(targets,decode_length,batch_first=True).data.to(device)
  25. loss = criterion(predict,targets)
  26. encoder_optimizer.zero_grad()
  27. decoder_optimizer.zero_grad()
  28. loss.backward()
  29. encoder_optimizer.step()
  30. decoder_optimizer.step()
  31. top5 = accuracy(predict_clone,targets)
  32. losses.update(loss.item(),sum(decode_length))
  33. top5acc.update(top5,sum(decode_length))
  34. batch_time.update(time() - start)
  35. start = time()
  36. if i % print_freq == 0 and i != 0:
  37. print('Epoch: [{0}][{1}/{2}]\t'
  38. 'Batch Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
  39. 'Data Load Time {data_load.val:.3f} ({data_time.avg:.3f})\t'
  40. 'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
  41. 'Top-5 Accuracy {top5.val:.3f} ({top5.avg:.3f})'.format(epoch, i, len(train_loader),
  42. batch_time=batch_time,
  43. data_load=data_load, loss=losses,
  44. top5=top5acc))
  45. """ 这里谈一下pack_padded_sequence的效果,对于rnn任务而言,一个batch中不同的序列,它们的实际长度可能并不相同,而是在序列的最后用<pad>(0) 将它们补齐到了一样的长度,而在decode的过程中我们利用了batch_size_t的小trick避免了补齐的0被拿去decode的情况。 现在的predict是我们的预测结果,targets是原始的标签,很显然它们的长度不一样,都存在着补0的情况,所以我们传入了一个decode_length,来表达 一个batch中每个序列的实际编码长度,这样就可以使得二者长度对齐了。 """
  46. def validate(val_loader,encoder,decoder,criterion):
  47. encoder.eval()
  48. decoder.eval()
  49. #进入评估模式以后dropout会失效
  50. #定义了3个标准量
  51. batch_time = AverageMeter()
  52. losses = AverageMeter()
  53. top5accs = AverageMeter()
  54. start = time.time()
  55. #references里面是正确的caption,一般一张图片有五个正确的caption,hypotheses是模型做出的推断
  56. references = list()
  57. hypotheses = list()
  58. with torch.no_grad():
  59. for i,(imgs,caps,caplens,allcaps) in enumerate(val_loader):
  60. imgs = imgs.to(device)
  61. caps = caps.to(device)
  62. caplens = caplens.to(device)
  63. imgs = encoder(imgs)
  64. scores, caps_sorted,decode_lengths, alphas,sort_ind = decoder(imgs,caps,caplens)
  65. scores_copy = scores.clone()
  66. targets = caps_sorted[:,1:]
  67. scores = pack_padded_sequence(scores,decode_lengths,batch_first=True).data.to(device)
  68. targets = pack_padded_sequence(targets,decode_lengths,batch_first=True).data.to(device)
  69. loss = criterion(scores,targets)
  70. losses.update(loss.item(),sum(decode_lengths))
  71. top5 = accuracy(scores,targets,5)
  72. top5accs.update(top5,sum(decode_lengths))
  73. batch_time.update(time.time() - start)
  74. start = time.time()
  75. if i % print_freq == 0:
  76. print('Validation: [{0}/{1}]\t'
  77. 'Batch Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
  78. 'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
  79. 'Top-5 Accuracy {top5.val:.3f} ({top5.avg:.3f})\t'.format(i, len(val_loader),batch_time=batch_time,loss=losses, top5=top5accs))
  80. allcaps = allcaps[sort_ind]
  81. #这一部分是为了将start和pad去掉
  82. for j in range(allcaps.shape[0]):
  83. img_caps = allcaps[j].tolist()
  84. img_captions = list(
  85. map(lambda c:[w for w in c if w not in { word_map['<start>'],word_map['<pad>']}],img_caps)
  86. )
  87. references.append(img_captions)
  88. #这一部分拿到了一个batch所有推断出的句子
  89. _,preds = torch.max(scores_copy,dim=2)
  90. preds = preds.tolist()
  91. temp_preds = list()
  92. for j,p in enumerate(preds):
  93. temp = preds[j][:decode_lengths[j]]
  94. temp_preds.append(temp)
  95. preds = temp_preds
  96. hypotheses.extend(preds)
  97. assert len(references) == len(hypotheses)
  98. #计算bleu-4的分数
  99. bleu4 = corpus_bleu(references,hypotheses)
  100. print(
  101. '\n * LOSS - {loss.avg:.3f}, TOP-5 ACCURACY - {top5.avg:.3f}, BLEU-4 - {bleu}\n'.format(
  102. loss=losses,
  103. top5=top5accs,
  104. bleu=bleu4))
  105. return bleu4

开始模型的训练

这一部分我做了简洁化处理,主要是为了帮助理解训练过程,数据从loss采用的cross_entropy,看作一个多分类问题。每次训练一个epoch后,用validate函数计算一些bleu4的分数,最后得出最好的分数。

  1. import time
  2. import torch.backends.cudnn as cudnn
  3. import torch.optim
  4. import torch.utils.data
  5. import torchvision.transforms as transforms
  6. from torch import nn
  7. from torch.nn.utils.rnn import pack_padded_sequence
  8. from models import Encoder,Decoder
  9. from datasets import *
  10. from utils import *
  11. from nltk.translate.bleu_score import corpus_bleu
  12. data_folder = '/mnt/hdd3/std2021/xiejun/datasets/flickr8k'
  13. base_name = '5_cap_per_img_5_min_word_freq'
  14. emb_dim = 512
  15. attention_dim = 512
  16. decode_dim = 512
  17. dropout = 0.5
  18. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  19. cudnn.benchmark = True
  20. start_epoch = 0
  21. epochs = 10
  22. epochs_since_improvement = 0
  23. batch_size = 32
  24. encoder_lr = 1e-4
  25. decoder_lr = 4e-4
  26. alpha_c = 1.
  27. best_bleu4 = 0.
  28. print_freq = 100
  29. checkpoint = None
  30. def main():
  31. global best_bleu4,checkpoint,start_epoch,base_name,word_map,epoch,epochs_since_improvement,reversed_map
  32. with open(os.path.join(data_folder,'WORDMAP_' + base_name + '.json')) as j:
  33. word_map = json.load(j)
  34. decoder = Decoder(attention_dim=attention_dim,
  35. decode_dim=decode_dim,
  36. embed_dim=emb_dim,
  37. vocab_size=len(word_map),
  38. dropout=dropout,
  39. encode_dim= 2048
  40. )
  41. decoder_optimizer = torch.optim.Adam(decoder.parameters(),lr=decoder_lr)
  42. encoder = Encoder()
  43. encoder_optimizer = torch.optim.Adam(params=encoder.parameters(),lr=encoder_lr)
  44. decoder = decoder.to(device)
  45. encoder = encoder.to(device)
  46. criterion = nn.CrossEntropyLoss().to(device)
  47. normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
  48. std=[0.229, 0.224, 0.225])
  49. train_loader = torch.utils.data.DataLoader(
  50. CaptionDataset(data_folder,base_name,'TRAIN',transform=transforms.Compose([normalize])),
  51. batch_size=batch_size,shuffle=True,pin_memory=True
  52. )
  53. val_loader = torch.utils.data.DataLoader(
  54. CaptionDataset(data_folder,base_name,'VAL',transform=transforms.Compose([normalize])),
  55. batch_size=batch_size,shuffle=True,pin_memory=True
  56. )
  57. for epoch in range(start_epoch,epochs):
  58. train(train_loader=train_loader,
  59. decoder=decoder,
  60. criterion=criterion,
  61. encoder=encoder,
  62. encoder_optimizer=encoder_optimizer,
  63. decoder_optimizer=decoder_optimizer,
  64. epoch=epoch)
  65. recent_bleu4 = validate(val_loader=val_loader,
  66. encoder=encoder,
  67. decoder=decoder,
  68. criterion=criterion,
  69. )
  70. is_best = recent_bleu4 > best_bleu4
  71. best_bleu4 = max(recent_bleu4,best_bleu4)

发表评论

表情:
评论列表 (有 0 条评论,232人围观)

还没有评论,来说两句吧...

相关阅读

    相关 论文梳理(image caption

    论文四遍法: 第一遍: 只 标题,摘要(讲什么),图表 第二遍:看 主要思想(前言,结语,图表),不看(相关研究) 第三遍:看(纵览论文主体,整体脉络框架),不看(