修改下列代码使得在能输出图像的同时能在命令框中得到分界面方程 data=[1 0 1;1 1 1 ;0 2 1; 2 1 -1 ; 2 2 -1;1 3 -1 ]; X = data(:, [1, 2]); y = data(:, 3); m = size(X,1); plotData2(X,y); X = [ones(m,1) X]; error = 1; W=[1;1;1]; first = 1; tim=0; alph=0.1; hold on axis([-3 3 -3 3]); x1=-2:0.2:2; while error>0 error=0; for i = 1:m if ( ((W'*(X(i,:)'))*y(i) <= 0 )|| (first == 1) ) first=0; error=error+1; tim=tim+1; W = W + alph*(X(i,:))'*y(i); fprintf('%dn',tim); if W(3)~=0 && W(2)~=0 y1=-(W(1)/W(3)+W(2)*x1/W(3)); plot(x1,y1,'-b'); end; end; end; end; if W(3)~=0 && W(2)~=0 y1=-(W(1)/W(3)+W(2)*x1/W(3)); plot(x1,y1,'r'); end; hold off
时间: 2023-09-07 14:13:35 浏览: 104
下面是修改后的代码:
```
data=[1 0 1;1 1 1 ;0 2 1; 2 1 -1 ; 2 2 -1;1 3 -1 ];
X = data(:, [1, 2]);
y = data(:, 3);
m = size(X,1);
plotData2(X,y);
X = [ones(m,1) X];
error = 1;
W=[1;1;1];
first = 1;
tim=0;
alph=0.1;
hold on
axis([-3 3 -3 3]);
x1=-2:0.2:2;
while error>0
error=0;
for i = 1:m
if ( ((W'*(X(i,:)'))*y(i) <= 0 )|| (first == 1) )
first=0;
error=error+1;
tim=tim+1;
W = W + alph*(X(i,:))'*y(i);
fprintf('%dn',tim);
end;
end;
if W(3)~=0 && W(2)~=0
y1=-(W(1)/W(3)+W(2)*x1/W(3));
plot(x1,y1,'-b');
disp(['Current decision boundary: ', num2str(W(1)), ' + ', num2str(W(2)), 'x1 + ', num2str(W(3)), 'x2 = 0']);
end;
end;
if W(3)~=0 && W(2)~=0
y1=-(W(1)/W(3)+W(2)*x1/W(3));
plot(x1,y1,'r');
disp(['Final decision boundary: ', num2str(W(1)), ' + ', num2str(W(2)), 'x1 + ', num2str(W(3)), 'x2 = 0']);
end;
hold off
```
修改后的代码在每次更新权重时输出当前的决策边界方程,并在命令框中显示。
阅读全文