网站规划和建设方案,如何设计个人网页,做网站整理信息的表格,开发龙岗网站建设✨✨ 欢迎大家来访Srlua的博文#xff08;づ#xffe3;3#xffe3;#xff09;づ╭❤#xff5e;✨✨ #x1f31f;#x1f31f; 欢迎各位亲爱的读者#xff0c;感谢你们抽出宝贵的时间来阅读我的文章。 我是Srlua小谢#xff0c;在这里我会分享我的知识和经验。づ3づ╭❤✨✨ 欢迎各位亲爱的读者感谢你们抽出宝贵的时间来阅读我的文章。 我是Srlua小谢在这里我会分享我的知识和经验。 希望在这里我们能一起探索IT世界的奥妙提升我们的技能。 记得先点赞后阅读哦~ 所属专栏传知代码论文复现 欢迎访问我的主页Srlua小谢 获取更多信息和资源。✨✨
目录
概述
算法原理
核心逻辑
效果演示
使用方式
参考文献 本文所有资源均可在该地址处获取。
概述
本文基于论文 Multi-Label Classification using Deep Convolutional Neural Network[1] 实现图像自动标注程序。
计算机技术的进步和互联网产业的不断发展导致了网络图像数量的爆炸式增长如何管理种类繁多的海量图像成为了一个重要问题。自动图像标注Automatic Image Tagging作为一项重要的图像管理技术可以利用计算机自动为每张图像打上与其内容有关的标签从而帮助用户更好地搜索和访问图像。 图1图像自动标注任务
近年来随着深度学习技术的发展深度神经网络能够捕捉到更多且更加复杂的图像特征这使得图像标注算法的性能也随之受益。图像标注与图像多标签分类有着天然的紧密连系后者会根据内容将一张图像归纳到多个类别中。综上本文基于目前先进的深度神经网络 VGG-Net[2] 和大规模图像多标签分类数据集 MS-COCO-2017[3] 训练自动图像标注模型。
算法原理
VGG-Net 是一种经典的卷积神经网络 (Convolutional Neural Network) 架构其核心思想是通过更深的网络结构以及使用较小的卷积核来提取更丰富的图像特征。VGG-Net 通过堆叠多个卷积层来加深网络且卷积层全部采用大小为 3×33×3 的小卷积核步长为 11填充为 11。这种设计通过堆叠多个小卷积核来增加网络的非线性表达能力且相比使用较大的卷积核能减少参数数量。在若干卷积层后VGG-Net 使用 2×22×2 的最大池化层步长为 22。池化层用于减少特征图的尺寸并保留主要的特征。在最后的卷积层之后VGG-Net 通过三个全连接层对特征进行进一步处理最后输出分类结果。在每个卷积层和全连接层之后VGG-Net 使用 ReLU (Rectified Linear Unit) 激活函数以增加网络的非线性。 图2模型结构
本文使用一个线性层和 Sigmoid 函数构建模型的分类器并利用二元交叉熵损失Binary Cross-Entropy, BCE进行训练。
Sigmoid(x)11e−xSigmoid(x)1e−x1
BCE(y,y^)−1N∑i1N[yilog(y^i)(1−yi)log(1−y^i)]BCE(y,y^)−N1i1∑N[yilog(y^i)(1−yi)log(1−y^i)] 图3训练过程精准度、召回率、F1-score
核心逻辑
程序的核心代码如下所示 # transformtransform v2.Compose([v2.Resize(256),v2.CenterCrop(224),v2.RandomHorizontalFlip(),v2.ColorJitter(brightness0.2, contrast0.2, saturation0.2),v2.ToImage(),v2.ToDtype(torch.float32, scaleTrue),v2.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225]),])# devicedevice torch.device(cuda if torch.cuda.is_available() else cpu)# datasettrain_dataset COCO_Dataset(configs[train_annotations_path], configs[train_images_dir], transform)train_dataloader DataLoader(train_dataset, batch_size configs[batch_size], shuffle True, num_workers8, pin_memoryTrue)test_dataset COCO_Dataset(configs[test_annotations_path], configs[test_images_dir], transform)test_dataloader DataLoader(test_dataset, batch_size configs[batch_size], shuffle False, num_workers8, pin_memoryTrue)# modelmodel ImageTaggingModel().to(device)optimizer optim.Adam(model.parameters(), lrconfigs[learning_rate], weight_decayconfigs[weight_decay])lr_scheduler optim.lr_scheduler.StepLR(optimizer, step_sizeconfigs[lr_decay_step], gammaconfigs[lr_decay_rate])# logloss_epoch []precise_epoch []recall_epoch []f1_epoch []# train testfor epoch_id in range(configs[epochs]):current_loss 0# trainmodel.train()for batch in tqdm(train_dataloader, descTraining(Epoch %d) % epoch_id, ascii 123456789#):optimizer.zero_grad()images batch[images].to(device)labels batch[labels].to(device)logits model(images)loss F.binary_cross_entropy_with_logits(logits, labels)current_loss loss.item()loss.backward()optimizer.step()lr_scheduler.step()current_loss / len(train_dataloader)print(Current Average Loss:, current_loss)loss_epoch.append(current_loss)plt.plot(loss_epoch)plt.xlabel(Epoch)plt.ylabel(Loss)plt.title(Loss-Epoch)plt.savefig(os.path.join(configs[logs_dir], Loss.png), dpi300)plt.clf()# testmodel.eval()TT_num 0FT_num 0FF_num 0with torch.no_grad():for batch in tqdm(test_dataloader, descTesting(Epoch %d) % epoch_id, ascii 123456789#):images batch[images].to(device)labels batch[labels].to(device)logits model(images)probs F.sigmoid(logits)predictions (probs configs[threshold]).to(labels.dtype)TT_num torch.sum(predictions * labels).item()FT_num torch.sum(predictions * (1 - labels)).item()FF_num torch.sum((1 - predictions) * labels).item()precise TT_num / (TT_num FT_num)recall TT_num / (TT_num FF_num)f1_score 2 * precise * recall / (precise recall)precise_epoch.append(precise)recall_epoch.append(recall)f1_epoch.append(f1_score)print(Precise %.2f, Recall %.2f, F1-score %.2f % (precise, recall, f1_score))plt.plot(precise_epoch, labelPrecise)plt.plot(recall_epoch, labelRecall)plt.plot(f1_epoch, labelF1-score)plt.xlabel(Epoch)plt.ylabel(Value)plt.title(Result)plt.legend()plt.savefig(os.path.join(configs[logs_dir], Result.png), dpi300)plt.clf()# save modeltorch.save(model.state_dict(), configs[checkpoint])以上代码仅作展示更详细的代码文件请参见附件。
效果演示
配置环境并运行 main.py脚本效果如图4所示。 图5程序运行结果
此外网站还提供了在线体验功能。用户只需要输入一张大小不超过 1MB 的 JPG 图像网站就会自动为图像打上标记并展示词云如图5所示。 图6在线体验结果
使用方式
解压附件压缩包并进入工作目录。如果是Linux系统请使用如下命令
unzip ImageCaptioning.zip
cd ImageCaptioning代码的运行环境可通过如下命令进行配置
pip install -r requirements.txt如果在本地测试自动图像标注程序请运行如下命令
python main.py如果希望在线部署请运行如下命令
python main-flask.py参考文献
[1] Lydia A A, Francis F S. Multi-label classification using deep convolutional neural network[C]//2020 international conference on innovative trends in information technology (ICITIIT). IEEE, 2020: 1-6.
[2] Simonyan K, Zisserman A. Very deep convolutional networks for large-scale image recognition[J]. arXiv preprint arXiv:1409.1556, 2014.
[3] Lin T Y, Maire M, Belongie S, et al. Microsoft coco: Common objects in context[C]//Computer Vision–ECCV 2014: 13th European Conference, Zurich, Switzerland, September 6-12, 2014, Proceedings, Part V 13. Springer International Publishing, 2014: 740-755.