MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   如何在MATLAB中实现频谱内核功能? (https://www.labfans.com/bbs/showthread.php?t=22739)

poster 2019-12-10 16:49

如何在MATLAB中实现频谱内核功能?
 
频谱内核函数通过对两个字符串之间的相同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 它使用函数[URL="http://www.mathworks.com/help/techdoc/ref/hankel.html"]HANKEL[/URL]首先创建索引矩阵,该矩阵将从给定的字符串中选择每组唯一的N长度子字符串。用此索引矩阵索引给定的字符串将创建一个字符数组,每行一个N长度的子字符串。然后,函数[URL="http://www.mathworks.com/help/techdoc/ref/cellstr.html"]CELLSTR[/URL]将字符数组的每一行放入单元格数组的单元格中。然后,函数[URL="http://www.mathworks.com/help/techdoc/ref/unique.html"]UNIQUE[/URL]删除重复的子字符串,并使用函数[URL="http://www.mathworks.com/help/techdoc/ref/accumarray.html"]ACCUMARRAY[/URL]计数每个唯一子字符串的出现次数(如果出于任何原因需要它们)。

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

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

[url=https://stackoverflow.com/questions/1190544]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 23:27

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.