def train(self, dataSet, C, toler, kernel = kernel_func): '''用smo算法求拉格朗日乘算子''' Kernel.clearCache()#清空缓存 smo = SMOAlgorithm(dataSet, C, toler, kernel) self.alphas = smo.run() self.kernel = smo.kernel self.dataSet = dataSet #计算b的值 b_array = [] for j in range(len(self.alphas)): alphaj = self.alphas[j] assert 0 <= alphaj and alphaj <= C #先则0 < alpha < c的正分量 if alphaj == 0 or alphaj == C: continue yj = dataSet.getLabel(j) b = 0.0 for i in range(len(self.alphas)): alphai = self.alphas[i] yi = dataSet.getLabel(i) kij = self.kernel.compute(i, j) b += alphai * yi * kij b = yj - b b_array.append(b) self.b = numpy.array(b_array).mean() return self.alphas, self.b
def test_clear(self): Kernel.clearCache() print(Kernel.cacheMatrix)