导出使用 MATLAB 以其他编程语言训练的神经网络
Posted
技术标签:
【中文标题】导出使用 MATLAB 以其他编程语言训练的神经网络【英文标题】:Export a neural network trained with MATLAB in other programming languages 【发布时间】:2013-03-09 16:46:19 【问题描述】:我使用 MATLAB 神经网络工具箱训练了一个神经网络,特别是使用命令 nprtool
,它提供了一个简单的 GUI 来使用工具箱功能,并导出一个包含有关 NN 信息的 net
对象生成。
通过这种方式,我创建了一个可工作的神经网络,我可以将其用作分类器,并且表示它的图表如下:
有 200 个输入,第一个隐藏层中有 20 个神经元,最后一层有 2 个神经元提供二维输出。
我想做的是用其他编程语言(C#、Java、...)来使用网络。
为了解决这个问题,我尝试在MATLAB中使用如下代码:
y1 = tansig(net.IW1 * input + net.b1);
Results = tansig(net.LW2 * y1 + net.b2);
假设 input
是一个包含 200 个元素的一维数组,如果 net.IW1
是一个 20x200 矩阵(20 个神经元,200 个权重),前面的代码就可以工作。
问题是我注意到size(net.IW1)
返回了意外的值:
>> size(net.IW1)
ans =
20 199
我在输入 10000 的网络上遇到了同样的问题。在这种情况下,结果不是 20x10000,而是类似于 20x9384(我不记得确切的值)。
那么,问题是:如何获得每个神经元的权重?在那之后,谁能解释我如何使用它们来产生相同的 MATLAB 输出?
【问题讨论】:
某些权重可能已设置为 0,因此从矩阵中删除。希望,如果我是正确的,有一个地方可以避免这种行为。 我看不到任何设置来更改此类选项...您能帮我找到它们吗? 【参考方案1】:我解决了上述问题,我认为分享我所学到的东西很有用。
场所
首先,我们需要一些定义。让我们考虑以下图片,取自 [1]:
上图中,IW代表初始权重:它们代表Layer 1上神经元的权重,每个都是与每个输入相连,如下图所示[1]:
所有其他权重,称为层权重(第一张图中的LW),它们也与前一层的每个输出相连。在我们的研究案例中,我们使用了一个只有两层的网络,因此我们将只使用一个 LW 阵列来解决我们的问题。
问题的解决方案
经过上面的介绍,我们可以将问题分为两步进行:
强制初始权重的数量与输入数组长度相匹配 使用权重来实现和使用刚刚用其他编程语言训练的神经网络A - 强制初始权重的数量与输入数组长度匹配
使用nprtool
,我们可以训练我们的网络,并且在过程结束时,我们还可以在工作区中导出有关整个训练过程的一些信息。特别是,我们需要导出:
此外,我们需要生成一个 M 文件,其中包含 MATLAB 用于创建神经网络的代码,因为我们需要修改它并更改一些训练选项。
下图显示了如何执行这些操作:
生成的 M 代码将类似于以下代码:
function net = create_pr_net(inputs,targets)
%CREATE_PR_NET Creates and trains a pattern recognition neural network.
%
% NET = CREATE_PR_NET(INPUTS,TARGETS) takes these arguments:
% INPUTS - RxQ matrix of Q R-element input samples
% TARGETS - SxQ matrix of Q S-element associated target samples, where
% each column contains a single 1, with all other elements set to 0.
% and returns these results:
% NET - The trained neural network
%
% For example, to solve the Iris dataset problem with this function:
%
% load iris_dataset
% net = create_pr_net(irisInputs,irisTargets);
% irisOutputs = sim(net,irisInputs);
%
% To reproduce the results you obtained in NPRTOOL:
%
% net = create_pr_net(trainingSetInput,trainingSetOutput);
% Create Network
numHiddenNeurons = 20; % Adjust as desired
net = newpr(inputs,targets,numHiddenNeurons);
net.divideParam.trainRatio = 75/100; % Adjust as desired
net.divideParam.valRatio = 15/100; % Adjust as desired
net.divideParam.testRatio = 10/100; % Adjust as desired
% Train and Apply Network
[net,tr] = train(net,inputs,targets);
outputs = sim(net,inputs);
% Plot
plotperf(tr)
plotconfusion(targets,outputs)
在开始训练过程之前,我们需要删除 MATLAB 对输入和输出执行的所有预处理和后处理函数。这可以通过在 % Train and Apply Network
行之前添加以下行来完成:
net.inputs1.processFcns = ;
net.outputs2.processFcns = ;
在对create_pr_net()
函数进行这些更改之后,我们可以简单地使用它来创建我们的最终神经网络:
net = create_pr_net(input, target);
其中input
和target
是我们通过nprtool
导出的值。
通过这种方式,我们确定权重的数量等于输入数组的长度。此外,此过程对于简化向其他编程语言的移植很有用。
B - 实现和使用刚刚用其他编程语言训练的神经网络
通过这些更改,我们可以定义如下函数:
function [ Results ] = classify( net, input )
y1 = tansig(net.IW1 * input + net.b1);
Results = tansig(net.LW2 * y1 + net.b2);
end
在这段代码中,我们使用了上面提到的 IW 和 LW 数组,还有 biases b,nprtool
在网络模式中使用。在这种情况下,我们不关心role of biases;简单地说,我们需要使用它们,因为nprtool
做到了。
现在,我们可以使用上面定义的classify()
函数,或者同样使用sim()
函数,得到同样的结果,如下例所示:
>> sim(net, input(:, 1))
ans =
0.9759
-0.1867
-0.1891
>> classify(net, input(:, 1))
ans =
0.9759
-0.1867
-0.1891
显然,classify()
函数可以被解释为伪代码,然后在任何可以定义 MATLAB tansig()
函数 [2] 和数组之间的基本操作的编程语言中实现。
参考文献
[1]Howard Demuth, Mark Beale, Martin Hagan: Neural Network Toolbox 6 - User Guide, MATLAB
[2]Mathworks, tansig - Hyperbolic tangent sigmoid transfer function, MATLAB Documentation center
补充说明
查看robott's answer 和Sangeun Chi's answer 了解更多详情。
【讨论】:
感谢您的回答。这对我帮助很大。但我需要processFcns。我在输入数据上只使用了[inputs,PSi] = mapminmax(inputs);
,并将其保存到 minmaxParams.mat save('minmaxParams','PSi')
。然后在我的分类功能中我添加了load minmaxParams.mat;input = mapminmax('apply',input, PSi);
我已经合并了所有 cmets,纠正了一些错别字,并给出了一个适用于单个隐藏层 ANN 的示例实现。它包括 Sangeun Chi 的改进和更正。【参考方案2】:
这是对伟大的 Vito Gentile 答案的一个小改进。
如果你想使用预处理和后处理 'mapminmax' 函数,你必须注意,因为 Matlab 中的 'mapminmax' 是按 ROW 而不是按列进行归一化的!
这是您需要添加到上层“分类”功能的内容,以保持前后处理的连贯性:
[m n] = size(input);
ymax = 1;
ymin = -1;
for i=1:m
xmax = max(input(i,:));
xmin = min(input(i,:));
for j=1:n
input(i,j) = (ymax-ymin)*(input(i,j)-xmin)/(xmax-xmin) + ymin;
end
end
这个在函数的最后:
ymax = 1;
ymin = 0;
xmax = 1;
xmin = -1;
Results = (ymax-ymin)*(Results-xmin)/(xmax-xmin) + ymin;
这是 Matlab 代码,但它可以作为伪代码轻松阅读。 希望这会有所帮助!
【讨论】:
【参考方案3】:感谢 VitoShadow 和 robott 的回答,我可以将 Matlab 神经网络值导出到其他应用程序。
我非常感谢他们,但我在他们的代码中发现了一些微不足道的错误,并想更正它们。
1) 在 VitoShadow 代码中,
Results = tansig(net.LW2 * y1 + net.b2);
-> Results = net.LW2 * y1 + net.b2;
2) 在机器人预处理代码中, 从净变量中提取 xmax 和 xmin 比计算它们更容易。
xmax = net.inputs1.processSettings1.xmax
xmin = net.inputs1.processSettings1.xmin
3) 在机器人后处理代码中,
xmax = net.outputs2.processSettings1.xmax
xmin = net.outputs2.processSettings1.xmin
Results = (ymax-ymin)*(Results-xmin)/(xmax-xmin) + ymin;
-> Results = (Results-ymin)*(xmax-xmin)/(ymax-ymin) + xmin;
您可以手动检查并确认以下值:
p2 = mapminmax('apply', net(:, 1), net.inputs1.processSettings1)
-> 预处理数据
y1 = purelin ( net.LW2 * tansig(net.iw1* p2 + net.b1) + net.b2)
-> 神经网络处理数据
y2 = mapminmax( 'reverse' , y1, net.outputs2.processSettings1)
-> 后处理数据
参考: http://www.mathworks.com/matlabcentral/answers/14517-processing-of-i-p-data
【讨论】:
【参考方案4】:我尝试使用 OpenCV 在 C++ 中实现一个简单的 2 层 NN,然后将权重导出到运行良好的 android。我写了一个小脚本,它生成一个带有学习权重的头文件,并在以下代码中使用。
// Map Minimum and Maximum Input Processing Function
Mat mapminmax_apply(Mat x, Mat settings_gain, Mat settings_xoffset, double settings_ymin)
Mat y;
subtract(x, settings_xoffset, y);
multiply(y, settings_gain, y);
add(y, settings_ymin, y);
return y;
/* MATLAB CODE
y = x - settings_xoffset;
y = y .* settings_gain;
y = y + settings_ymin;
*/
// Sigmoid Symmetric Transfer Function
Mat transig_apply(Mat n)
Mat tempexp;
exp(-2*n, tempexp);
Mat transig_apply_result = 2 /(1 + tempexp) - 1;
return transig_apply_result;
// Map Minimum and Maximum Output Reverse-Processing Function
Mat mapminmax_reverse(Mat y, Mat settings_gain, Mat settings_xoffset, double settings_ymin)
Mat x;
subtract(y, settings_ymin, x);
divide(x, settings_gain, x);
add(x, settings_xoffset, x);
return x;
/* MATLAB CODE
function x = mapminmax_reverse(y,settings_gain,settings_xoffset,settings_ymin)
x = y - settings_ymin;
x = x ./ settings_gain;
x = x + settings_xoffset;
end
*/
Mat getNNParameter (Mat x1)
// convert double array to MAT
// input 1
Mat x1_step1_xoffsetM = Mat(1, 48, CV_64FC1, x1_step1_xoffset).t();
Mat x1_step1_gainM = Mat(1, 48, CV_64FC1, x1_step1_gain).t();
double x1_step1_ymin = -1;
// Layer 1
Mat b1M = Mat(1, 25, CV_64FC1, b1).t();
Mat IW1_1M = Mat(48, 25, CV_64FC1, IW1_1).t();
// Layer 2
Mat b2M = Mat(1, 48, CV_64FC1, b2).t();
Mat LW2_1M = Mat(25, 48, CV_64FC1, LW2_1).t();
// input 1
Mat y1_step1_gainM = Mat(1, 48, CV_64FC1, y1_step1_gain).t();
Mat y1_step1_xoffsetM = Mat(1, 48, CV_64FC1, y1_step1_xoffset).t();
double y1_step1_ymin = -1;
// ===== SIMULATION ========
// Input 1
Mat xp1 = mapminmax_apply(x1, x1_step1_gainM, x1_step1_xoffsetM, x1_step1_ymin);
Mat temp = b1M + IW1_1M*xp1;
// Layer 1
Mat a1M = transig_apply(temp);
// Layer 2
Mat a2M = b2M + LW2_1M*a1M;
// Output 1
Mat y1M = mapminmax_reverse(a2M, y1_step1_gainM, y1_step1_xoffsetM, y1_step1_ymin);
return y1M;
标题中的偏差示例可能是这样的:
static double b2[1][48] =
-0.19879, 0.78254, -0.87674, -0.5827, -0.017464, 0.13143, -0.74361, 0.4645, 0.25262, 0.54249, -0.22292, -0.35605, -0.42747, 0.044744, -0.14827, -0.27354, 0.77793, -0.4511, 0.059346, 0.29589, -0.65137, -0.51788, 0.38366, -0.030243, -0.57632, 0.76785, -0.36374, 0.19446, 0.10383, -0.57989, -0.82931, 0.15301, -0.89212, -0.17296, -0.16356, 0.18946, -1.0032, 0.48846, -0.78148, 0.66608, 0.14946, 0.1972, -0.93501, 0.42523, -0.37773, -0.068266, -0.27003, 0.1196;
现在,Google 发布了 Tensorflow,这已经过时了。
【讨论】:
【参考方案5】:因此解决方案变为(纠正所有部分后)
这里我在 Matlab 中给出了一个解决方案,但是如果你有 tanh() 函数,你可以很容易地将它转换为任何编程语言。它仅用于显示网络对象中的字段和您需要的操作。
假设您有一个训练有素的 ann(网络对象)要导出 假设训练的ann的名字是trained_ann这是用于导出和测试的脚本。 测试脚本将原始网络结果与 my_ann_evaluation() 结果进行比较
% Export IT
exported_ann_structure = my_ann_exporter(trained_ann);
% Run and Compare
% Works only for single INPUT vector
% Please extend it to MATRIX version by yourself
input = [12 3 5 100];
res1 = trained_ann(input')';
res2 = my_ann_evaluation(exported_ann_structure, input')';
你需要以下两个函数的地方
第一个 my_ann_exporter:
function [ my_ann_structure ] = my_ann_exporter(trained_netw)
% Just for extracting as Structure object
my_ann_structure.input_ymax = trained_netw.inputs1.processSettings1.ymax;
my_ann_structure.input_ymin = trained_netw.inputs1.processSettings1.ymin;
my_ann_structure.input_xmax = trained_netw.inputs1.processSettings1.xmax;
my_ann_structure.input_xmin = trained_netw.inputs1.processSettings1.xmin;
my_ann_structure.IW = trained_netw.IW1;
my_ann_structure.b1 = trained_netw.b1;
my_ann_structure.LW = trained_netw.LW2;
my_ann_structure.b2 = trained_netw.b2;
my_ann_structure.output_ymax = trained_netw.outputs2.processSettings1.ymax;
my_ann_structure.output_ymin = trained_netw.outputs2.processSettings1.ymin;
my_ann_structure.output_xmax = trained_netw.outputs2.processSettings1.xmax;
my_ann_structure.output_xmin = trained_netw.outputs2.processSettings1.xmin;
end
第二次 my_ann_evaluation:
function [ res ] = my_ann_evaluation(my_ann_structure, input)
% Works with only single INPUT vector
% Matrix version can be implemented
ymax = my_ann_structure.input_ymax;
ymin = my_ann_structure.input_ymin;
xmax = my_ann_structure.input_xmax;
xmin = my_ann_structure.input_xmin;
input_preprocessed = (ymax-ymin) * (input-xmin) ./ (xmax-xmin) + ymin;
% Pass it through the ANN matrix multiplication
y1 = tanh(my_ann_structure.IW * input_preprocessed + my_ann_structure.b1);
y2 = my_ann_structure.LW * y1 + my_ann_structure.b2;
ymax = my_ann_structure.output_ymax;
ymin = my_ann_structure.output_ymin;
xmax = my_ann_structure.output_xmax;
xmin = my_ann_structure.output_xmin;
res = (y2-ymin) .* (xmax-xmin) /(ymax-ymin) + xmin;
end
【讨论】:
这个导出函数是为一个简单的情况设计的:仅适用于具有 1 个输入、1 个输出和 1 个隐藏层的 ANN。可以轻松地将其扩展到更多分层的人工神经网络以上是关于导出使用 MATLAB 以其他编程语言训练的神经网络的主要内容,如果未能解决你的问题,请参考以下文章