函数
[words,attentionScores] = beamSearch(X,beamIndex,parametersEncoder,parametersDecoder,
...
enc, maxNumWords)
%模型尺寸
numFeatures = size(X,1);
numHiddenUnits = size(parametersDecoder.attention.Weights1,1);
提取特征
features = modelEncoder(X,parametersEncoder);
初始化状态
State = struct;
state.gru.HiddenState = dlarray(0 ([numHiddenUnits 1],
“喜欢”
, X));
初始化候选
候选人= struct;
候选人。状态=状态;
候选人。话说=
“<开始>”
;
候选人。得分= 0;
候选人。注意分数= dlarray(零([numFeatures maxNumWords],
“喜欢”
, X));
候选人。StopFlag= false;
T = 0;
%循环单词
而
t < maxNumWords
T = T + 1;
candidatesNew = [];
%遍历候选人
为
I = 1:数字(候选人)
当预测到停止令牌时停止生成
如果
候选人(i)。StopFlag
继续
结束
%候选人详细信息
状态=候选人(i).状态;
words =考生(i).Words;
分数=考生(i).分数;
注意分数=考生(i).注意分数;
%预测下一个令牌
decoderInput = word2ind(enc,words(end));
[YPred,state,attentionScores(:,t)] = modelDecoder(decoderInput,parametersDecoder,features,state);
YPred = softmax(YPred,DataFormat=
“CB”
);
[scoresTop,idxTop] = maxk(extractdata(YPred),beamIndex);
idxTop = gather(idxTop);
循环顶部的预测
为
j = 1:beamIndex
Candidate = struct;
candidateWord = ind2word(enc,idxTop(j));
candidateScore = scoresTop(j);
如果
candidateWord = =
“<停止>”
候选人。StopFlag= true;
attentionScores(:,t+1:end) = [];
其他的
候选人。StopFlag= false;
结束
候选人。状态=状态;
候选人。话说=[words candidateWord];
候选人。分数=分数+日志(candidateScore);
候选人。注意力分数=注意力分数;
candidatesNew = [candidatesNew候选人];
变量' candidatennew '似乎在每次循环迭代中都改变了大小。考虑为速度进行预分配。”
结束
结束
%寻找最佳候选人
[~,idx] = maxk([candidatesNew.Score],beamIndex);
候选人=候选人新(idx);
当所有候选对象都有停止令牌时停止预测
如果
([candidates.StopFlag])
返回
结束
结束
%找到最佳候选人
words = candidate (1).Words(2:end-1);
脚本中的函数定义必须出现在文件的末尾。将语句移动到函数定义之前
attentionScores =考生(1).AttentionScores;
结束