感知机算法的对偶形式

image image image image


 class PerceptionPair:
        #初始化一些参数学习率,gram矩阵等等
  7     def __init__(self, dataSet, target, learningrate=1):
  8         self.lr = learningrate
  9         self.a = np.zeros(len(dataSet), np.float)
 10         self.b = 0.0
 11         self.gram = np.matmul(np.array(dataSet), np.array(dataSet).T)
 12         self.target = target

 13     #计算判断是否误分类的值
 14     def calc(self,i):
 15         res = np.dot(self.a*self.target, self.gram[i])
 16         res = (res+self.b)*target[i]
 17         return res
 18
 19     def train(self, inputs, target):
 20         flag = False
 21         m = len(inputs)
 22         res = 0.0
 23         for i in range(m):
                # 进行权值更新
 24             if self.calc(i) <= 0:
 25                 self.a[i] += self.lr
 26                 self.b += target[i]
 27                 print(self.a, self.b)

image image


完整代码

Ref:
1.统计学习方法-李航