介绍
本次项目使用深度学习自动生成图像字幕。如上图,模型自动生成“The person is riding a surfboard in the ocean”字幕。我们具体该如何实现呢?
如图所示,我们需要分别使用CNN和RNN模型来实现。
CNN模型:
利用卷积网络对图像特征提取的强大能力,来提取特征信息。我们的CNN模型需要有强大的识别能力,因此该模型需要使用过大量,多类别的训练集进行训练,并且识别准确率较高。本次,我们利用迁移学习使用Inception模型实现此功能。
通过迁移学习实现OCT图像识别 文章中有迁移学习的相关介绍。
RNN模型:
对于文本序列数据,目前我们最好的选择依然是RNN模型。为了提升模型预测能力,我们使用注意力机制实现文本预测。
注意力机制实现机器翻译 文章中有注意力机制的相关介绍。
对模型的细节要求我们将在对应代码实现里进行介绍。
数据集介绍
我们使用MS-COCO数据集进行训练,为方便理解,简单介绍下数据格式。COCO数据有5种类型,分别是: object detection, keypoint detection, stuff segmentation, panoptic segmentation,image captioning。基础数据结构如下图所示:
具体样例(部分):
本次项目使用的是Image Captioning其中,每张照片不少于5个字幕:
数据下载处理
import tensorflow as tf
# 开启eager模式
tf.enable_eager_execution()
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import re
import numpy as np
import os
import time
import json
from glob import glob
from PIL import Image
import pickle
annotation_zip=tf.keras.utils.get_file(
# cache_dir(默认值): `~/.keras`
# cache_subdir: `datasets`,
# ~/.keras/datasets/captions.zip
fname='captions.zip',
cache_subdir=os.path.abspath('.'),
origin='http://images.cocodataset.org/annotations/annotations_trainval2014.zip',
# 解压
extract=True
)
# 返回文件夹名,实现:split(file)[0]
annotation_file = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json'
name_of_zip='train2014.zip'
if not os.path.exists(os.path.abspath('.')+"/"+name_of_zip):
image_zip=tf.keras.utils.get_file(
fname=name_of_zip,
cache_subdir=os.path.abspath('.'),
origin='http://images.cocodataset.org/zips/train2014.zip',
extract=True
)
PATH=os.path.dirname(image_zip)+'train2014/'
else:
PATH=os.path.abspath('.')+'/train2014/'
读取字幕和图片:
# 读取注释json文件
with open(annotation_file,'r') as f:
annotations=json.load(f)
# 保存全部字幕
all_captions=[]
# 保存全部图片
all_img_name_vecotr=[]
# json格式参考COCO数据集官网
for annot in annotations['annotations']:
# 添加开始和结束标记
caption='<start>'+annot['caption']+'<end>'
# 获取图片名字
image_