登录论坛

查看完整版本 : 如何在MATLAB中实现频谱内核功能?


poster
2019-12-10, 16:49
频谱内核函数通过对两个字符串之间的相同n-gram进行计数来对字符串进行操作。例如,“ tool”具有三个2克(“ to”,“ oo”和“ ol”),并且“ tool”和“ fool”之间的相似度为2。(常见的“ oo”和“ ol” )。

如何编写可以计算该指标的MATLAB函数?


回答:
第一步是创建一个可以为给定字符串生成n元语法的函数。以矢量化方式执行此操作的一种方法是使用一些巧妙的索引。

function [subStrings, counts] = n_gram(fullString, N) if (N == 1) [subStrings, ~, index] = unique(cellstr(fullString.')); %.'# Simple case else nString = numel(fullString); index = hankel(1:(nString-N+1), (nString-N+1):nString); [subStrings, ~, index] = unique(cellstr(fullString(index))); end counts = accumarray(index, 1); end 它使用函数HANKEL (http://www.mathworks.com/help/techdoc/ref/hankel.html)首先创建索引矩阵,该矩阵将从给定的字符串中选择每组唯一的N长度子字符串。用此索引矩阵索引给定的字符串将创建一个字符数组,每行一个N长度的子字符串。然后,函数CELLSTR (http://www.mathworks.com/help/techdoc/ref/cellstr.html)将字符数组的每一行放入单元格数组的单元格中。然后,函数UNIQUE (http://www.mathworks.com/help/techdoc/ref/unique.html)删除重复的子字符串,并使用函数ACCUMARRAY (http://www.mathworks.com/help/techdoc/ref/accumarray.html)计数每个唯一子字符串的出现次数(如果出于任何原因需要它们)。

使用上面的函数,您可以使用INTERSECT (http://www.mathworks.com/help/techdoc/ref/intersect.html)函数轻松计算两个字符串之间共享的n-gram数:

subStrings1 = n_gram('tool',2); subStrings2 = n_gram('fool',2); sharedStrings = intersect(subStrings1,subStrings2); nShared = numel(sharedStrings);

更多&回答... (https://stackoverflow.com/questions/1190544)