[{"data":1,"prerenderedAt":625},["ShallowReactive",2],{"content-query-kMBr4VYyam":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"category":13,"body":14,"_type":619,"_id":620,"_source":621,"_file":622,"_stem":623,"_extension":624},"/technology-blogs/zh/1994","zh",false,"","基于昇思MindSpore，实现使用胶囊网络的图像描述生成算法","图像描述生成任务的目的就是教会计算机如何描述所看到的内容，其中涉及到了对视觉信息的处理以及如何生成符合人类语言习惯的语句，这两方面也分别对应的人工智能的两大领域——计算机视觉和自然语言处理。","2022-12-09","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/12/09/fb2ce3d281a64981b678555ed6c3f26b.png","technology-blogs","大V博文",{"type":15,"children":16,"toc":610},"root",[17,25,35,40,48,59,67,75,80,88,93,101,106,114,119,124,129,137,142,150,155,160,165,170,175,180,185,190,195,200,205,210,215,220,228,233,238,243,248,253,258,262,267,272,277,282,287,291,296,300,305,310,315,319,324,329,333,338,343,347,352,356,361,366,370,375,380,384,388,393,398,402,407,412,417,422,427,432,437,442,447,452,457,462,467,472,477,482,487,492,497,502,507,512,517,522,527,532,537,545,550,555,560,565,570,575,580,585,590,595,600,605],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"基于昇思mindspore实现使用胶囊网络的图像描述生成算法",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":29},"h2",{"id":28},"项目名称",[30],{"type":18,"tag":31,"props":32,"children":33},"strong",{},[34],{"type":24,"value":28},{"type":18,"tag":36,"props":37,"children":38},"p",{},[39],{"type":24,"value":8},{"type":18,"tag":26,"props":41,"children":43},{"id":42},"项目链接",[44],{"type":18,"tag":31,"props":45,"children":46},{},[47],{"type":24,"value":42},{"type":18,"tag":36,"props":49,"children":50},{},[51],{"type":18,"tag":52,"props":53,"children":57},"a",{"href":54,"rel":55},"https://github.com/Liu-Yuanqiu/acn_mindspore",[56],"nofollow",[58],{"type":24,"value":54},{"type":18,"tag":26,"props":60,"children":62},{"id":61},"项目描述",[63],{"type":18,"tag":31,"props":64,"children":65},{},[66],{"type":24,"value":61},{"type":18,"tag":36,"props":68,"children":69},{},[70],{"type":18,"tag":31,"props":71,"children":72},{},[73],{"type":24,"value":74},"图像描述生成算法",{"type":18,"tag":36,"props":76,"children":77},{},[78],{"type":24,"value":79},"人类可以轻易的使用语言来描述所看到的场景，但是计算机却很难做到，图像描述生成任务的目的就是教会计算机如何描述所看到的内容，其中涉及到了对视觉信息的处理以及如何生成符合人类语言习惯的语句，这两方面也分别对应的人工智能的两大领域——计算机视觉和自然语言处理。图像描述生成任务不仅仅在算法研究上具有重要的意义，同时在盲人助理、图文转换等实际应用场景也有广泛的应用。",{"type":18,"tag":36,"props":81,"children":82},{},[83],{"type":18,"tag":31,"props":84,"children":85},{},[86],{"type":24,"value":87},"胶囊网络",{"type":18,"tag":36,"props":89,"children":90},{},[91],{"type":24,"value":92},"因为卷积是局部连接和参数共享的，并没有考虑到特征之间的相互关联和相互位置关系，即没有学习到特征之间的位姿信息；胶囊网络同时将空间信息和物体存在概率编码到胶囊向量中，通过动态路由决定当前胶囊输入到哪个更加高级的胶囊，并通过非线性激活函数在归一化的同时保持方向不变，从而使胶囊网络学习到有用的特征以及它们之间的关系。",{"type":18,"tag":26,"props":94,"children":96},{"id":95},"网络结构",[97],{"type":18,"tag":31,"props":98,"children":99},{},[100],{"type":24,"value":95},{"type":18,"tag":36,"props":102,"children":103},{},[104],{"type":24,"value":105},"具体来说，图像描述生成算法通常使用编码器-解码器结构，如图1所示，其中编码器部分提取图片的视觉特征，通过多种注意力机制捕获视觉特征之间的关系并生成输出，其中包括了双线性池化模块和注意力胶囊模块，双线性池化模块通过对特征进行挤压-奖励操作获取特征之间的二阶交互，注意力胶囊模块将每一个视觉特征看作一个胶囊，从而捕获特征之间的相对位置关系；解码器部分根据视觉特征通过循环神经网络生成对应单词，解码器使用自回归方式解码，以上一时刻单词作为输入，逐个生成单词组成最终的描述语句。",{"type":18,"tag":36,"props":107,"children":108},{},[109],{"type":18,"tag":110,"props":111,"children":113},"img",{"alt":7,"src":112},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/12/09/8fb2cff8aeba466580776533a7ff2d18.png",[],{"type":18,"tag":36,"props":115,"children":116},{},[117],{"type":24,"value":118},"图1 使用胶囊网络的图像描述生成算法框架",{"type":18,"tag":36,"props":120,"children":121},{},[122],{"type":24,"value":123},"算法使用交叉熵损失监督训练，损失函数表示为：",{"type":18,"tag":36,"props":125,"children":126},{},[127],{"type":24,"value":128},"其中表示前i-1步生成的单词，表示图像特征，表示在两者基础上生成本时刻单词的概率。",{"type":18,"tag":26,"props":130,"children":132},{"id":131},"开发流程",[133],{"type":18,"tag":31,"props":134,"children":135},{},[136],{"type":24,"value":131},{"type":18,"tag":36,"props":138,"children":139},{},[140],{"type":24,"value":141},"在具体实现过程中，我们先进行数据集适配，然后对网络模型进行开发，之后编写了训练代码。MindSpore拥有良好的基础算子支持和简洁的API接口，不管是底层的矩阵运算还是高层的网络模型封装都可以完美的支持，极大的方便了开发和调试的过程。",{"type":18,"tag":36,"props":143,"children":144},{},[145],{"type":18,"tag":31,"props":146,"children":147},{},[148],{"type":24,"value":149},"数据集适配",{"type":18,"tag":36,"props":151,"children":152},{},[153],{"type":24,"value":154},"因为图像描述生成任务涉及到对图片和文本的处理，因此训练数据的格式也具有多种类型，其中图像特征是使用Faster RCNN预处理好的矩阵，词表以txt文件存储，描述语句使用数组进行存储，因此我们使用自定义数据集来生成训练批次，首先定义一个数据类，类中实现__getitem__作为可迭代对象返回数据，使用GeneratorDataset组装数据类，从而进行混洗和抽取批次。",{"type":18,"tag":36,"props":156,"children":157},{},[158],{"type":24,"value":159},"coco_train_set = CocoDataset(",{"type":18,"tag":36,"props":161,"children":162},{},[163],{"type":24,"value":164},"image_ids_path = os.path.join(args.dataset_path, 'txt', 'coco_train_image_id.txt'),",{"type":18,"tag":36,"props":166,"children":167},{},[168],{"type":24,"value":169},"input_seq = os.path.join(args.dataset_path, 'sent', 'coco_train_input.pkl'),",{"type":18,"tag":36,"props":171,"children":172},{},[173],{"type":24,"value":174},"target_seq = os.path.join(args.dataset_path, 'sent', 'coco_train_target.pkl'),",{"type":18,"tag":36,"props":176,"children":177},{},[178],{"type":24,"value":179},"att_feats_folder = os.path.join(args.dataset_path, 'feature', 'up_down_36'),",{"type":18,"tag":36,"props":181,"children":182},{},[183],{"type":24,"value":184},"seq_per_img = args.seq_per_img,",{"type":18,"tag":36,"props":186,"children":187},{},[188],{"type":24,"value":189},"max_feat_num = -1)",{"type":18,"tag":36,"props":191,"children":192},{},[193],{"type":24,"value":194},"dataset_train = ds.GeneratorDataset(coco_train_set,",{"type":18,"tag":36,"props":196,"children":197},{},[198],{"type":24,"value":199},"column_names=[\"indices\", \"input_seq\", \"target_seq\", \"att_feats\"],",{"type":18,"tag":36,"props":201,"children":202},{},[203],{"type":24,"value":204},"shuffle=True,",{"type":18,"tag":36,"props":206,"children":207},{},[208],{"type":24,"value":209},"python_multiprocessing=True,",{"type":18,"tag":36,"props":211,"children":212},{},[213],{"type":24,"value":214},"num_parallel_workers=args.works)",{"type":18,"tag":36,"props":216,"children":217},{},[218],{"type":24,"value":219},"dataset_train = dataset_train.batch(args.batch_size, drop_remainder=True)",{"type":18,"tag":36,"props":221,"children":222},{},[223],{"type":18,"tag":31,"props":224,"children":225},{},[226],{"type":24,"value":227},"网络模型开发",{"type":18,"tag":36,"props":229,"children":230},{},[231],{"type":24,"value":232},"网络模型均使用nn.Cell作为基类进行开发，根据网络中模型的不同功能实现了模型整体类CapsuleXlan、编码器Encoder和解码器Decoder等等，其中涉及到线性层、激活层、矩阵操作、张量操作等等，具体网络结构定义如下。",{"type":18,"tag":36,"props":234,"children":235},{},[236],{"type":24,"value":237},"class CapsuleXlan(nn.Cell):",{"type":18,"tag":36,"props":239,"children":240},{},[241],{"type":24,"value":242},"def __init__():",{"type":18,"tag":36,"props":244,"children":245},{},[246],{"type":24,"value":247},"self.encoder = Encoder()",{"type":18,"tag":36,"props":249,"children":250},{},[251],{"type":24,"value":252},"self.decoder = Decoder()",{"type":18,"tag":36,"props":254,"children":255},{},[256],{"type":24,"value":257},"class Encoder(nn.Cell):",{"type":18,"tag":36,"props":259,"children":260},{},[261],{"type":24,"value":242},{"type":18,"tag":36,"props":263,"children":264},{},[265],{"type":24,"value":266},"self.encoder = nn.CellList([])",{"type":18,"tag":36,"props":268,"children":269},{},[270],{"type":24,"value":271},"for _ in range(layer_num):",{"type":18,"tag":36,"props":273,"children":274},{},[275],{"type":24,"value":276},"sublayer = CapsuleLowRankLayer()",{"type":18,"tag":36,"props":278,"children":279},{},[280],{"type":24,"value":281},"self.encoder.append(sublayer)",{"type":18,"tag":36,"props":283,"children":284},{},[285],{"type":24,"value":286},"class Decoder(nn.Cell):",{"type":18,"tag":36,"props":288,"children":289},{},[290],{"type":24,"value":242},{"type":18,"tag":36,"props":292,"children":293},{},[294],{"type":24,"value":295},"self.decoder = nn.CellList([])",{"type":18,"tag":36,"props":297,"children":298},{},[299],{"type":24,"value":271},{"type":18,"tag":36,"props":301,"children":302},{},[303],{"type":24,"value":304},"sublayer = LowRankLayer()",{"type":18,"tag":36,"props":306,"children":307},{},[308],{"type":24,"value":309},"self.decoder.append(sublayer)",{"type":18,"tag":36,"props":311,"children":312},{},[313],{"type":24,"value":314},"class CapsuleLowRankLayer(nn.Cell):",{"type":18,"tag":36,"props":316,"children":317},{},[318],{"type":24,"value":242},{"type":18,"tag":36,"props":320,"children":321},{},[322],{"type":24,"value":323},"self.attn_net = Capsule()",{"type":18,"tag":36,"props":325,"children":326},{},[327],{"type":24,"value":328},"class LowRankLayer(nn.Cell):",{"type":18,"tag":36,"props":330,"children":331},{},[332],{"type":24,"value":242},{"type":18,"tag":36,"props":334,"children":335},{},[336],{"type":24,"value":337},"self.attn_net = SCAtt()",{"type":18,"tag":36,"props":339,"children":340},{},[341],{"type":24,"value":342},"class SCAtt(nn.Cell):",{"type":18,"tag":36,"props":344,"children":345},{},[346],{"type":24,"value":242},{"type":18,"tag":36,"props":348,"children":349},{},[350],{"type":24,"value":351},"class Capsule(nn.Cell):",{"type":18,"tag":36,"props":353,"children":354},{},[355],{"type":24,"value":242},{"type":18,"tag":36,"props":357,"children":358},{},[359],{"type":24,"value":360},"其中CapsuleXlan中包含了Encoder和Decoder，通过Encoder编码视觉信息，通过Decoder生成描述语句；Encoder中包含多层CapsuleLowRankLayer，每一层CapsuleLowRankLayer对特征进行处理后输入Capsule进行计算，结果处理后返回上一层；对于Decoder来说同理。",{"type":18,"tag":36,"props":362,"children":363},{},[364],{"type":24,"value":365},"对于具体的运算，以Decoder为例，首先我们定义子层和对应的线性层，提前需要使用的算子操作，然后在construct中使用预先定义的各个层对输入进行处理，计算结果经过线性层和层归一化后返回。",{"type":18,"tag":36,"props":367,"children":368},{},[369],{"type":24,"value":286},{"type":18,"tag":36,"props":371,"children":372},{},[373],{"type":24,"value":374},"def __init__(self, layer_num, embed_dim, att_heads, att_mid_dim, att_mid_drop):",{"type":18,"tag":36,"props":376,"children":377},{},[378],{"type":24,"value":379},"super(Decoder, self).__init__()",{"type":18,"tag":36,"props":381,"children":382},{},[383],{"type":24,"value":295},{"type":18,"tag":36,"props":385,"children":386},{},[387],{"type":24,"value":271},{"type":18,"tag":36,"props":389,"children":390},{},[391],{"type":24,"value":392},"sublayer = LowRankLayer(embed_dim=embed_dim, att_heads=8,",{"type":18,"tag":36,"props":394,"children":395},{},[396],{"type":24,"value":397},"att_mid_dim=[128, 64, 128], att_mid_drop=0.9)",{"type":18,"tag":36,"props":399,"children":400},{},[401],{"type":24,"value":309},{"type":18,"tag":36,"props":403,"children":404},{},[405],{"type":24,"value":406},"self.proj = nn.Dense(embed_dim * (layer_num + 1), embed_dim)",{"type":18,"tag":36,"props":408,"children":409},{},[410],{"type":24,"value":411},"self.layer_norm = nn.LayerNorm([embed_dim])",{"type":18,"tag":36,"props":413,"children":414},{},[415],{"type":24,"value":416},"self.concat_last = ops.Concat(-1)",{"type":18,"tag":36,"props":418,"children":419},{},[420],{"type":24,"value":421},"def construct(self, gv_feat, att_feats, att_mask):",{"type":18,"tag":36,"props":423,"children":424},{},[425],{"type":24,"value":426},"batch_size = att_feats.shape[0]",{"type":18,"tag":36,"props":428,"children":429},{},[430],{"type":24,"value":431},"feat_arr = [gv_feat]",{"type":18,"tag":36,"props":433,"children":434},{},[435],{"type":24,"value":436},"for i, decoder_layer in enumerate(self.decoder):",{"type":18,"tag":36,"props":438,"children":439},{},[440],{"type":24,"value":441},"gv_feat = decoder_layer(gv_feat, att_feats, att_mask, gv_feat, att_feats)",{"type":18,"tag":36,"props":443,"children":444},{},[445],{"type":24,"value":446},"feat_arr.append(gv_feat)",{"type":18,"tag":36,"props":448,"children":449},{},[450],{"type":24,"value":451},"gv_feat = self.concat_last(feat_arr)",{"type":18,"tag":36,"props":453,"children":454},{},[455],{"type":24,"value":456},"gv_feat = self.proj(gv_feat)",{"type":18,"tag":36,"props":458,"children":459},{},[460],{"type":24,"value":461},"gv_feat = self.layer_norm(gv_feat)",{"type":18,"tag":36,"props":463,"children":464},{},[465],{"type":24,"value":466},"return gv_feat, att_feats",{"type":18,"tag":36,"props":468,"children":469},{},[470],{"type":24,"value":471},"同时，对交叉熵损失进行实现并将其和网络模型组装到一个类中：",{"type":18,"tag":36,"props":473,"children":474},{},[475],{"type":24,"value":476},"class CapsuleXlanWithLoss(nn.Cell):",{"type":18,"tag":36,"props":478,"children":479},{},[480],{"type":24,"value":481},"def __init__(self, model):",{"type":18,"tag":36,"props":483,"children":484},{},[485],{"type":24,"value":486},"super(CapsuleXlanWithLoss, self).__init__()",{"type":18,"tag":36,"props":488,"children":489},{},[490],{"type":24,"value":491},"self.model = model",{"type":18,"tag":36,"props":493,"children":494},{},[495],{"type":24,"value":496},"self.ce = nn.SoftmaxCrossEntropyWithLogits(sparse=True)",{"type":18,"tag":36,"props":498,"children":499},{},[500],{"type":24,"value":501},"def construct(self, indices, input_seq, target_seq, att_feats):",{"type":18,"tag":36,"props":503,"children":504},{},[505],{"type":24,"value":506},"logit = self.model(input_seq, att_feats)",{"type":18,"tag":36,"props":508,"children":509},{},[510],{"type":24,"value":511},"logit = logit.view((-1, logit.shape[-1]))",{"type":18,"tag":36,"props":513,"children":514},{},[515],{"type":24,"value":516},"target_seq = target_seq.view((-1))",{"type":18,"tag":36,"props":518,"children":519},{},[520],{"type":24,"value":521},"mask = (target_seq > -1).astype(\"float32\")",{"type":18,"tag":36,"props":523,"children":524},{},[525],{"type":24,"value":526},"loss = self.ce(logit, target_seq)",{"type":18,"tag":36,"props":528,"children":529},{},[530],{"type":24,"value":531},"loss = ops.ReduceSum(False)(loss * mask) / mask.sum()",{"type":18,"tag":36,"props":533,"children":534},{},[535],{"type":24,"value":536},"return loss",{"type":18,"tag":36,"props":538,"children":539},{},[540],{"type":18,"tag":31,"props":541,"children":542},{},[543],{"type":24,"value":544},"训练",{"type":18,"tag":36,"props":546,"children":547},{},[548],{"type":24,"value":549},"数据集和网络模型都已经准备完毕，在训练过程中只需要将模型、优化器、数据集、回调函数装配起来即可，在这里我们首先定义优化器，使用Adam优化器进行优化，然后定义回调函数，使用LossMonitor、TimeMonitor、ModelCheckpoint和SummaryCollector分别监听损失函数、计算每一步所用时间、保存模型以及保存可视化数据。最终使用nn.Model将四部分装配在一起进行训练，并可以通过MindInsight观察训练损失和参数的变化。",{"type":18,"tag":36,"props":551,"children":552},{},[553],{"type":24,"value":554},"net = CapsuleXlan()",{"type":18,"tag":36,"props":556,"children":557},{},[558],{"type":24,"value":559},"net = CapsuleXlanWithLoss(net)",{"type":18,"tag":36,"props":561,"children":562},{},[563],{"type":24,"value":564},"warmup_lr = nn.WarmUpLR(args.lr, args.warmup)",{"type":18,"tag":36,"props":566,"children":567},{},[568],{"type":24,"value":569},"optim = nn.Adam(params=net.trainable_params(), learning_rate=warmup_lr, beta1=0.9, beta2=0.98, eps=1.0e-9)",{"type":18,"tag":36,"props":571,"children":572},{},[573],{"type":24,"value":574},"model = ms.Model(network=net, optimizer=optim)",{"type":18,"tag":36,"props":576,"children":577},{},[578],{"type":24,"value":579},"loss_cb = LossMonitor(per_print_times=1)",{"type":18,"tag":36,"props":581,"children":582},{},[583],{"type":24,"value":584},"time_cb = TimeMonitor(data_size=step_per_epoch)",{"type":18,"tag":36,"props":586,"children":587},{},[588],{"type":24,"value":589},"ckpoint_cb = ModelCheckpoint(prefix='ACN',",{"type":18,"tag":36,"props":591,"children":592},{},[593],{"type":24,"value":594},"directory=os.path.join(args.result_folder, 'checkpoints'))",{"type":18,"tag":36,"props":596,"children":597},{},[598],{"type":24,"value":599},"summary_cb = SummaryCollector(summary_dir=os.path.join(args.result_folder, 'summarys'))",{"type":18,"tag":36,"props":601,"children":602},{},[603],{"type":24,"value":604},"cbs = [loss_cb, time_cb, ckpoint_cb, summary_cb]",{"type":18,"tag":36,"props":606,"children":607},{},[608],{"type":24,"value":609},"model.train(epoch=args.epochs, train_dataset=dataset_train, callbacks=cbs)",{"title":7,"searchDepth":611,"depth":611,"links":612},4,[613,615,616,617,618],{"id":28,"depth":614,"text":28},2,{"id":42,"depth":614,"text":42},{"id":61,"depth":614,"text":61},{"id":95,"depth":614,"text":95},{"id":131,"depth":614,"text":131},"markdown","content:technology-blogs:zh:1994.md","content","technology-blogs/zh/1994.md","technology-blogs/zh/1994","md",1776506117504]