我想比较不同的机器学习算法。作为其中的一部分,我需要能够执行 grid search for optimal hyperparameters .但是,我并不真正喜欢为每个固定算法及其超参数的固定子集编写单独的网格搜索实现的想法。相反,我希望它看起来更像 scikit-learn 中的样子。但可能没有那么多的功能(例如,我不需要多个网格)并且是用 MATLAB 编写的。
到目前为止,我正在尝试理解尚未编写的 grid_search.m
function model = grid_search(algo, data, labels, varargin)
p = inputParser;
% here comes the list of all possible hyperparameters for all algorithms
% I will just leave three for brevity
addOptional(p, 'kernel_function', {'linear'});
addOptional(p, 'rbf_sigma', {1});
addOptional(p, 'C', {1});
parse(p, algo, data, labels, varargin{:});
names = fieldnames(p.Results);
values = struct2cell(p.Results); % a cell array of cell arrays
argsize = 2 * length(names);
args = cell(1, argsize);
args(1 : 2 : argsize) = names;
% Now this is the stumbling point.
end
对 grid_search
函数的调用应该如下所示:
m = grid_search('svm', data, labels, 'kernel_function', {'rbf'}, 'C', {[0.1], [1], [10]}, 'rbf_sigma', {[1], [2], [3]})
m = grid_search('knn', data, labels, 'NumNeighbors', {[1], [10]}, 'Distance', {'euclidean', 'cosine'})
然后第一个调用将尝试 rbf 内核与约束和 Sigmas 的所有组合:
{'rbf', 0.1, 1}
{'rbf', 0.1, 2}
{'rbf', 0.1, 3}
{'rbf', 1, 1}
{'rbf', 1, 2}
{'rbf', 1, 3}
{'rbf', 10, 1}
{'rbf', 10, 2}
{'rbf', 10, 3}
args
变量背后的想法是它是一个格式为 {'name1', 'value1', 'name2', 'value2', ..., 'nameN', 'valueN'}
稍后将传递给相应的算法:algo(data, labels, args{:})
。 {'name1', 'name2', ..., 'nameN'}
部分很简单。问题是我无法理解如何在每个步骤中创建 {'value1', 'value2', ..., 'valueN'}
部分。
我知道机器学习术语并不是每个人都知道这就是为什么下面有一个独立的例子:
假设 TARDIS 的船员可能由以下几类生物组成:
tardis_crew = {{'doctor'}, {'amy', 'clara'}, {'dalek', 'cyberman', 'master'}}
由于 Timelord、Companion 和 Villain 总是只有一个位置,请告诉我如何生成以下元胞数组:
{'Timelord', 'doctor', 'Companion', 'amy', 'Villain', 'dalek'}
{'Timelord', 'doctor', 'Companion', 'amy', 'Villain', 'cyberman'}
{'Timelord', 'doctor', 'Companion', 'amy', 'Villain', 'master'}
{'Timelord', 'doctor', 'Companion', 'clara', 'Villain', 'dalek'}
{'Timelord', 'doctor', 'Companion', 'clara', 'Villain', 'cyberman'}
{'Timelord', 'doctor', 'Companion', 'clara', 'Villain', 'master'}
解决方案应该是通用的,即如果一个类中的生物数量发生变化或添加了更多生物类,它应该仍然有效。我也非常感谢分步描述而不是代码。
附注:non-stripped原始 grid_search.m
的 github 版本可能会让您更好地理解我的意思。
最佳答案
您似乎想要生成任意数量集合的笛卡尔积。我觉得这个ALLCOMB函数会为你做这件事,但如果你想要一个(迭代)算法的细节以便你可以自己实现它,请检查 this answer .
编辑:顺便感谢您为没有 ML 知识的人提供通用措辞。
关于MATLAB 中与算法无关的超参数网格搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20490971/