clear all; n=0.2; w=[0,0,0]; P=[-9,1,-12,-4,0,5;... 15,-8,4,5,11,9]; d=[0,1,0,0,0,1]; P=[ones(1,6);P]; MAX=20; i=0; while 1 v=w*P; y=hardlim(v); e=(d-y); ee(i+1)=mae(e); if (ee(i+1)<0.001) disp('we have got it:'); disp(w); break; end w=w+n*(d-y)*P'; i=i+1; if (i>=MAX) disp('MAX times loop'); disp(w); disp(ee(i+1)); break; end end figure; subplot(2,1,1); plot([-9,-12,-4,0],[15,4,5,11],'o'); hold on; plot([1,5],[-8,9],'*'); axis([-13,6,-10,16]); legend('第一类','第二类'); title('6个坐标点的二分类'); x=-13:.2:6; y=x*(-w(2)/w(3)-w(1)/w(3)); plot(x,y); hold off; subplot(2,1,2); x=0:i; plot(x,ee,'o-'); s=sprintf('mae的值(迭代次数:%d)',i+1); title(s); 转变成python语言
时间: 2024-04-10 08:33:24 浏览: 148
在Python中,可以将上述MATLAB代码转换为以下代码:
```python
import numpy as np
import matplotlib.pyplot as plt
n = 0.2
w = np.zeros(3)
P = np.array([[-9, 1, -12, -4, 0, 5], [15, -8, 4, 5, 11, 9]])
d = np.array([0, 1, 0, 0, 0, 1])
P = np.vstack((np.ones(6), P))
MAX = 20
i = 0
ee = []
while True:
v = np.dot(w, P)
y = np.heaviside(v, 0)
e = d - y
ee.append(np.mean(np.abs(e)))
if ee[i] < 0.001:
print('we have got it:')
print(w)
break
w = w + n * np.dot((d - y), P.T)
i += 1
if i >= MAX:
print('MAX times loop')
print(w)
print(ee[i])
break
plt.figure()
plt.subplot(2, 1, 1)
plt.plot([-9, -12, -4, 0], [15, 4, 5, 11], 'o')
plt.hold(True)
plt.plot([1, 5], [-8, 9], '*')
plt.axis([-13, 6, -10, 16])
plt.legend(['Class 1', 'Class 2'])
plt.title('Binary Classification of 6 Coordinate Points')
x = np.arange(-13, 6, 0.2)
y = x * (-w[1] / w[2] - w[0] / w[2])
plt.plot(x, y)
plt.hold(False)
plt.subplot(2, 1, 2)
x = np.arange(0, i + 1)
plt.plot(x, ee, 'o-')
s = f'mae value (iterations: {i + 1})'
plt.title(s)
plt.show()
```
这是将MATLAB代码转换为Python代码的基本过程。请注意,在Python中,需要使用NumPy库进行矩阵运算,并使用Matplotlib库进行绘图。另外,一些函数和语法略有不同,因此可能需要进行适当的调整和修改。
阅读全文