Image Captioning Model
模型简介
模型特点
模型能力
使用案例
🚀 图解基于Transformer模型的图像描述生成
本项目利用视觉Transformer实现图像描述生成,结合计算机视觉与Transformer技术,在图像理解和描述生成方面取得了不错的效果,为图像描述任务提供了新的解决方案。
🚀 快速开始
本项目旨在利用Vision Transformers实现图像描述生成。以下是快速开始的步骤:
- 安装必要的依赖和环境。
- 准备数据集。
- 运行代码进行训练和推理。
✨ 主要特性
- 先进技术融合:采用Vision Transformers、注意力机制、语言建模、迁移学习等先进技术。
- 多评估指标:使用BLEU、METEOR、CIDEr等评估指标对图像描述进行评估。
- 用户友好界面:通过Gradio平台部署到Hugging Face Spaces,提供直观的Web界面。
📦 安装指南
安装COCO API
- 克隆仓库:
git clone https://github.com/cocodataset/cocoapi.git
- 配置COCO API:
cd cocoapi/PythonAPI
make
cd ..
- 下载特定数据:从官网下载以下数据:
- 注释数据:
- 2017 Train/Val注释 [241MB]:提取
captions_train2017.json
和captions_val2017.json
,分别放置在cocoapi/annotations/captions_train2017.json
和cocoapi/annotations/captions_val2017.json
。 - 2017测试图像信息 [1MB]:提取
image_info_test2017.json
,放置在cocoapi/annotations/image_info_test2017.json
。
- 2017 Train/Val注释 [241MB]:提取
- 图像数据:
- 2017训练图像 [83K/13GB]:提取
train2017
文件夹,放置在cocoapi/images/train2017/
。 - 2017验证图像 [41K/6GB]:提取
val2017
文件夹,放置在cocoapi/images/val2017/
。 - 2017测试图像 [41K/6GB]:提取
test2017
文件夹,放置在cocoapi/images/test2017/
。
- 2017训练图像 [83K/13GB]:提取
- 注释数据:
环境准备
注意:本项目在Mac上开发,在Windows和Linux上稍作修改也可运行。
- 克隆仓库并进入目录:
git clone https://github.com/CapstoneProjectimagecaptioning/image_captioning_transformer.git
cd image_captioning_transformer
- 创建并激活新环境:
conda create -n captioning_env python=3.7
source activate captioning_env
- 安装依赖:
pip install -r requirements.txt
- 返回仓库目录:
cd image_captioning
- 打开Jupyter Notebook:
jupyter notebook
- 打开项目Notebook后,确保选择正确的环境:点击
Kernel > Change Kernel > captioning_env
。
💻 使用示例
基础用法
# 代码示例保持不变
# 这里可以根据实际情况补充基础用法的代码示例
高级用法
# 高级场景说明
# 这里可以根据实际情况补充高级用法的代码示例
📚 详细文档
代码解释步骤
1. 数据加载与预处理
- 加载注释:从COCO 2017数据集中加载图像-描述对,使用JSON文件(
captions_train2017.json
)。 - 图像与描述配对:创建列表
img_cap_pairs
,将图像文件名与对应的描述配对。 - 描述数据框:使用pandas DataFrame组织数据,方便操作,包括创建图像文件路径。
- 数据采样:随机采样70,000个图像-描述对,使数据集更易于管理。
2. 文本预处理
对描述进行预处理,包括小写化、去除标点符号、替换多个空格为单个空格,并添加[start]
和[end]
标记。
3. 分词
- 词汇表设置:创建分词器(
TextVectorization
),词汇表大小为15,000个单词,最大标记长度为40。将描述分词,转换为整数序列。 - 保存词汇表:将词汇表保存到文件,以便后续重用。
- 单词与索引映射:创建
word2idx
和idx2word
映射,实现单词与索引的相互转换。
4. 数据集准备
- 图像-描述映射:使用字典将每个图像映射到其描述列表,然后打乱图像顺序,进行训练-验证分割(80%训练,20%验证)。
- 创建TensorFlow数据集:使用
load_data
函数,调整图像大小、预处理图像,并将描述分词为张量。将张量分批进行训练和验证,提高内存效率和并行处理能力。
5. 数据增强
对训练图像应用基本的图像增强(随机翻转、随机旋转和随机对比度),帮助模型更好地泛化。
6. 模型架构
- CNN编码器:使用在ImageNet上预训练的InceptionV3模型处理图像并提取特征,作为Transformer的输入。
- Transformer编码器层:使用多头自注意力和归一化层的
TransformerEncoderLayer
学习图像特征之间的关系。 - 嵌入层:添加位置嵌入,使模型能够捕捉描述中单词的顺序。
- Transformer解码器层:
TransformerDecoderLayer
生成描述,包括多头注意力、前馈神经网络和Dropout,防止过拟合。使用掩码确保在预测下一个单词时,标记不会“看到”未来的标记。
7. 图像描述模型类
ImageCaptioningModel
类将编码器、解码器和CNN编码器封装为一个统一的模型,用于训练和推理。自定义函数计算损失和准确率,跟踪模型性能。
8. 训练
- 损失函数:使用稀疏分类交叉熵计算预测标记和实际标记之间的差异,排除填充标记。
- 早停策略:监控验证损失,若验证集性能在一定时期内没有改善,则停止训练。
- 模型编译与训练:编译模型,进行优化,并在多个时期进行训练,同时应用早停策略。
9. 评估与描述生成
使用generate_caption
函数为新图像生成描述,通过迭代预测标记,直到生成[end]
标记或达到最大长度限制。
10. 保存模型
将模型权重保存到文件(Image_Captioning_Model
),以便后续重用,无需重新训练。
模型训练
训练和验证阶段的损失和BLEU-4分数表明,模型在第8个时期左右开始过拟合,第20个时期后BLEU-4分数和损失值不再改善。过拟合的原因可能包括:
- 训练数据不足:CPTR的编码器使用预训练的ViT模型初始化,但本项目中模型权重随机初始化,且训练图像少于18,500张。
- 特征处理不当:将Resnet101学习的图像特征分割成N个大小为
P x P
的块,可能不是最佳设计,将特征扁平化可能更好。 - 网络调优问题:预训练的Resnet101从一开始就进行调优,而词嵌入层在训练初期可能会扭曲图像特征。
- 超参数不合适:模型的超参数可能需要调整。
推理输出
生成描述的长度分布表明,模型倾向于生成较短的描述。训练描述长度的分布呈正偏态,模型生成的最大描述长度(21个标记)占训练集长度的98.66%。
🔧 技术细节
模型和技术使用
方法和技术
- 视觉Transformer(ViTs)
- 注意力机制
- 语言建模
- 迁移学习
- 图像描述评估指标(如BLEU、METEOR、CIDEr)
库使用
- PyTorch
- Transformers
- TorchVision
- NumPy
- NLTK
- Matplotlib
模型架构
CPTR由图像补丁器、Transformer编码器和解码器组成。图像补丁器将图像转换为补丁序列,添加位置嵌入后输入到12层相同的Transformer编码器。最后一层编码器的输出输入到4层相同的Transformer解码器。解码器还接收带有正弦位置嵌入的单词。
训练
使用交叉熵损失和双重随机注意力正则化训练模型。使用Adam优化器,批量大小为32。训练100个时期,若跟踪的评估指标(BLEU-4)连续20个时期没有改善,则停止训练;若连续10个时期没有改善,则将学习率降低0.25%。每2个时期对模型进行验证评估。
推理
使用大小为5的束搜索为测试集中的图像生成描述。生成从输入图像和“句子开始”特殊标记开始,每次迭代选择得分最高的5个标记,直到生成“句子结束”标记或达到最大长度限制。
评估指标
属性 | 详情 |
---|---|
模型类型 | 基于Transformer的图像描述生成模型 |
训练数据 | MS COCO 2017数据集 |
测试数据集上的性能指标均值和标准差如下:
bleu1 | bleu2 | bleu3 | bleu4 | gleu | meteor | |
---|---|---|---|---|---|---|
mean ± std | 0.7180 ± 0.17 | 0.5116 ± 0.226 | 0.3791 ± 0.227 | 0.2918 ± 0.215 | 0.2814 ± 0.174 | 0.4975 ± 0.193 |
注意力可视化
检查Transformer编码器-解码器注意力的最后一层,对注意力权重进行平均。从测试集中随机选择14个样本,将注意力权重叠加到样本图像上,输出保存为GIF或PNG格式,保存到images/tests
文件夹。
📄 许可证
本项目使用Apache 2.0许可证。
8. 参考文献
[1] Liu, W., Chen, S., Guo, L., Zhu, X., & Liu, J. (2021). CPTR: Full transformer network for image captioning. arXiv preprint arXiv:2101.10804. [2] Lin, T. Y., Maire, M., Belongie, S., Hays, J., Perona, P., Ramanan, D., ... & Zitnick, C. L. (2014, September). Microsoft coco: Common objects in context. In European conference on computer vision (pp. 740-755). Springer, Cham. [3] A. Vaswani et al., 'Attention is all you need', Advances in neural information processing systems, vol. 30, 2017. [4] M. Z. Hossain, F. Sohel, M. F. Shiratuddin, and H. Laga, 'A Comprehensive Survey of Deep Learning for Image Captioning', arXiv:1810.04020 [cs, stat], Oct. 2018, Accessed: Mar. 03, 2022. [Online]. Available: http://arxiv.org/abs/1810.04020. [5] S. Hochreiter and J. Schmidhuber, ‘Long short-term memory’, Neural computation, vol. 9, no. 8, pp. 1735–1780, 1997. [6] A. Dosovitskiy et al., 'An image is worth 16x16 words: Transformers for image recognition at scale', arXiv preprint arXiv:2010.11929, 2020. [7] K. He, X. Zhang, S. Ren, and J. Sun, 'Deep Residual Learning for Image Recognition', arXiv:1512.03385 [cs], Oct. 2015, Accessed: Mar. 06, 2022. [Online]. Available: http://arxiv.org/abs/1512.03385. [8] K. Xu et al., 'Show, Attend and Tell: Neural Image Caption Generation with Visual Attention', arXiv:1502.03044 [cs], Apr. 2016, Accessed: Mar. 07, 2022. [Online]. Available: http://arxiv.org/abs/1502.03044. [9] K. Papineni, S. Roukos, T. Ward, and W.-J. Zhu, 'Bleu: a method for automatic evaluation of machine translation', in Proceedings of the 40th annual meeting of the Association for Computational Linguistics, 2002, pp. 311–318. [10] S. Banerjee and A. Lavie, 'METEOR: An automatic metric for MT evaluation with improved correlation with human judgments', in Proceedings of the acl workshop on intrinsic and extrinsic evaluation measures for machine translation and/or summarization, 2005, pp. 65–72. [11] A. Mutton, M. Dras, S. Wan, and R. Dale, 'GLEU: Automatic evaluation of sentence-level fluency', in Proceedings of the 45th Annual Meeting of the Association of Computational Linguistics, 2007, pp. 344–351. [12] J. Pennington, R. Socher, and C. D. Manning, 'Glove: Global vectors for word representation', in Proceedings of the 2014 conference on empirical methods in natural language processing (EMNLP), 2014, pp. 1532–1543. [13] A. Karpathy and L. Fei-Fei, 'Deep visual-semantic alignments for generating image descriptions', in Proceedings of the IEEE conference on computer vision and pattern recognition, 2015, pp. 3128–3137. [14] Oriol Vinyals, Alexander Toshev, Samy Bengio, Dumitru Erhan; Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2015, pp. 3156-3164. [15] Hugging Face Spaces Forum about image captioning model. https://huggingface.co/docs/transformers/main/en/tasks/image_captioning [16] QuickStart Guide to GitHub pages https://docs.github.com/en/pages/quickstart [17] Microsoft COCO: Common Objects in Context (cs.CV). arXiv:1405.0312 [cs.CV] https://doi.org/10.48550/arXiv.1405.0312 [18] Show, Attend and Tell: Neural Image Caption Generation with Visual Attention arXiv:1502.03044v3 [cs.LG] 19 Apr 2016 https://doi.org/10.48550/arXiv.1502.03044 [19] Deep Residual Learning for Image Recognition arXiv:1512.03385v1 [cs.CV] 10 Dec 2015 [20] Gradio Quickstart Guide https://www.gradio.app/guides/quickstart








