在 MATLAB 中绘制除法 MLP 线和图表

Draw divisory MLP line together with chart in MATLAB

我需要绘制分界线和下图:

我用来训练 MLP 神经网络的代码在这里:

circles = [1 1; 2 1; 2 2; 2 3; 2 4; 3 2; 3 3; 4 1; 4 2; 4 3];
crosses = [1 2; 1 3; 1 4; 2 5; 3 4; 3 5; 4 4; 5 1; 5 2; 5 3];

net = feedforwardnet(3);
net = train(net, circles, crosses);

plot(circles(:, 1), circles(:, 2), 'ro');
hold on
plot(crosses(:, 1), crosses(:, 2), 'b+');
hold off;

但我也想在图表中显示分隔各组的线。我该如何进行?提前致谢。

首先,您没有正确训练您的神经网络。您必须同时使用 circlescrosses 作为神经网络的输入样本,并且输出必须是双神经元输出,其中 [1 0] 作为输出表示圆圈class 是 class 化应该是什么,[0 1] 是交叉 class 化会是什么。

此外,每个 是一个输入样本,而每一行都是一个特征。因此,您必须转置这两个并制作更大的输入矩阵。您还需要按照我们刚才所说的制作输出标签:

X = [circles.' crosses.'];
Y = [[ones(1, size(circles,1)); zeros(1, size(circles,1))] ...
     [zeros(1, size(crosses,1)); ones(1, size(crosses,1))]];

现在训练你的网络:

net = feedforwardnet(3);
net = train(net, X, Y);

现在,如果你想弄清楚每个点属于哪个 class,你只需获取最大的神经元输出,无论哪个给你最大,就是它所属的 class。


现在,要回答您的实际问题,如果您使用 MATLAB 工具箱,则没有直接的方法来显示 "lines" 与神经网络的分离。但是,您可以显示 区域 的分离,并可能添加一些透明度,以便您可以将其覆盖在图的顶部。

为此,定义一个二维坐标网格,跨越两个 classes 但具有更细的粒度……比如……0.01。 运行这个通过神经网络,看看最大输出神经元是多少,然后在你的图上做相应的标记。

我想到了这样的事情:

%// Generate test data
[ptX,ptY] = meshgrid(1:0.01:5, 1:0.01:5);
Xtest = [ptX(:).'; ptY(:).'];

%// See what the output labels are
out = sim(net, Xtest);
[~,classes] = max(out,[],1);

%// Now plot the regions
figure;
hold on;
%// Plot the first class region
plot(Xtest(1, classes == 1), Xtest(2, classes == 1), 'y.');
%// Add transparency
alpha(0.1);

%// Plot the second class region
plot(Xtest(1, classes == 2), Xtest(2, classes == 2), 'g.');
%// Add transparency
alpha(0.1);

%// Now add the points
plot(circles(:, 1), circles(:, 2), 'ro');
plot(crosses(:, 1), crosses(:, 2), 'b+');

前两行代码生成一堆测试 (x,y) 点并确保它们位于 2 行输入矩阵中,因为这是网络输入所需要的。我使用 meshgrid for generating these points. Next, we use sim to simulate or put in inputs into the neural network. Once we do this, we will have two output neuron neural network responses per input point where we take a look at which output neuron gave us the largest response. If the first output gave us the largest response, we consider the input as belonging to the first class. If not, then it's the second class. This is facilitated by using max 并独立查看每一列 - 每个输入样本一列并查看哪个位置给了我们最大值。

完成此操作后,我们创建一个新图形并绘制属于 class 1 的点,即黄色的圆圈和第二个 class,即十字,绿色。我加入了一些透明度以确保我们可以看到带有点的区域。之后,我使用您的代码正常绘制点。


通过上面的代码,我得到了这个数字:


如您所见,您的模型有一些 class化不准确。具体来说,有三个十字会被误class误认为是圆圈。您将不得不尝试使用隐藏层中的神经元数量以及可能使用不同的激活函数,但这肯定足以让您入门。

祝你好运!