1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
|
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 4 14:24:53 2016 @author: kuangmeng """ import time import os import math class model: def __init__(self): self.a = [] self.b = 0.0 class DATA: def __init__(self): self.samples = [] # 样本数据 self.tests = [] # 测试数据 self.models = [] # 训练的模型 self.forecasterror = [] # 预测知与真实y之差Ei self.modelnum = 0 # 当前正使用或训练的模型 self.cache= [] # 缓存kernel函数的计算结果 self.sigma = 10 # sigma def init_models(self): for i in range(0, 10): m = model() for j in range(len(self.samples)): m.a.append(0) self.models.append(m) def init_cache(self): i = 0 for x in self.samples: print ("正在计算第",i+1,"个样本的RBF核") self.cache.append([]) j = 0 for z in self.samples: if i > j: self.cache[i].append(self.cache[j][i]) else: self.cache[i].append(RBF(x,z)) j += 1 i += 1 class image: def __init__(self): self.data = [] self.num = 0 self.label = [] self.filename = "" gv = DATA() # RBF核函数 def RBF(j, i): if j == i: return math.exp(0) sigma = gv.sigma ret = 0.0 for m in range(len(j.data)): for n in range(len(j.data[m])): ret += math.pow(int(j.data[m][n]) - int(i.data[m][n]), 2) ret = math.exp(-ret/sigma) return ret #加载测试与训练数据 def loaddata(dirpath, name): files = os.listdir(dirpath) for file in files: img = image() img.data = images(dirpath + file) img.num = int(file[0]) img.filename = file name.append(img) #图片分列 def images(path): img = [] file = open(path, "r") for line in file: line = line[:-2] img.append(line) return img #更新样本标签,正在训练啥就将啥的标签定为1,其他的定为-1 def update_samples_label(num): for img in gv.samples: if img.num == num: img.label.append(1) else: img.label.append(-1) #初始化DATA.forecasterror def init_forecasterror(): gv.forecasterror = [] for i in range(len(gv.samples)): diff = 0.0 for j in range(len(gv.samples)): if gv.models[gv.modelnum].a[j] != 0: diff += gv.models[gv.modelnum].a[j] * gv.samples[j].label[gv.modelnum] * gv.cache[j][i] diff += gv.models[gv.modelnum].b diff -= gv.samples[i].label[gv.modelnum] gv.forecasterror.append(diff) #更新DATA.forecasterror def update_forecasterror(i, new_ai, j, new_bj, new_b): for idx in range(len(gv.samples)): diff = (new_ai - gv.models[gv.modelnum].a[i])* gv.samples[i].label[gv.modelnum] * gv.cache[i][idx] diff += (new_bj - gv.models[gv.modelnum].a[j])* gv.samples[j].label[gv.modelnum] * gv.cache[j][idx] diff += new_b - gv.models[gv.modelnum].b diff += gv.forecasterror[idx] gv.forecasterror[idx] = diff # g(x) def predict(m): pred = 0.0 for j in range(len(gv.samples)): if gv.models[gv.modelnum].a[j] != 0: pred += gv.models[gv.modelnum].a[j] * gv.samples[j].label[gv.modelnum] * RBF(gv.samples[j],m) pred += gv.models[gv.modelnum].b return pred def save_models(): for i in range(10): fn = open("models/" + str(i) + "_a.model", "w") for ai in gv.models[i].a: fn.write(str(ai)) fn.write('\n') fn.close() fn = open("models/" + str(i) + "_b.model", "w") fn.write(str(gv.models[i].b)) fn.close() def load_models(): for i in range(10): fn = open("models/" + str(i) + "_a.model", "r") j = 0 for line in fn: gv.models[i].a[j] = float(line) j += 1 fn.close() fn = open("models/" + str(i) + "_b.model", "r") gv.models[i].b = float(fn.readline()) fn.close() ### # T: tolerance 误差容忍度(精度) # times: 迭代次数 # 优化方法:SMO # C: 惩罚系数 # modelnum: 模型序号0到9 # step: aj移动的最小步长 ### def train(T, times, C, modelnum, step): time = 0 gv.modelnum = modelnum update_samples_label(modelnum) init_forecasterror() updated = True while time < times and updated: updated = False time += 1 for i in range(len(gv.samples)): ai = gv.models[gv.modelnum].a[i] Ei = gv.forecasterror[i] #计算违背KKT的点 if (gv.samples[i].label[gv.modelnum] * Ei < -T and ai < C) or (gv.samples[i].label[gv.modelnum] * Ei > T and ai > 0): for j in range(len(gv.samples)): if j == i: continue kii = gv.cache[i][i] kjj = gv.cache[j][j] kji = kij = gv.cache[i][j] eta = kii + kjj - 2 * kij if eta <= 0: continue new_aj = gv.models[gv.modelnum].a[j] + gv.samples[j].label[gv.modelnum] * (gv.forecasterror[i] - gv.forecasterror[j]) / eta # f 7.106 L = 0.0 H = 0.0 a1_old = gv.models[gv.modelnum].a[i] a2_old = gv.models[gv.modelnum].a[j] if gv.samples[i].label[gv.modelnum] == gv.samples[j].label[gv.modelnum]: L = max(0, a2_old + a1_old - C) H = min(C, a2_old + a1_old) else: L = max(0, a2_old - a1_old) H = min(C, C + a2_old - a1_old) if new_aj > H: new_aj = H if new_aj < L: new_aj = L if abs(a2_old - new_aj) < step: # print ("j = %d, is not moving enough" % j) continue new_ai = a1_old + gv.samples[i].label[gv.modelnum] * gv.samples[j].label[gv.modelnum] * (a2_old - new_aj) # f 7.109 new_b1 = gv.models[gv.modelnum].b - gv.forecasterror[i] - gv.samples[i].label[gv.modelnum] * kii * (new_ai - a1_old) - gv.samples[j].label[gv.modelnum] * kji * (new_aj - a2_old) # f7.115 new_b2 = gv.models[gv.modelnum].b - gv.forecasterror[j] - gv.samples[i].label[gv.modelnum]*kji*(new_ai - a1_old) - gv.samples[j].label[gv.modelnum]*kjj*(new_aj-a2_old) # f7.116 if new_ai > 0 and new_ai < C: new_b = new_b1 elif new_aj > 0 and new_aj < C: new_b = new_b2 else: new_b = (new_b1 + new_b2) / 2.0 update_forecasterror(i, new_ai, j, new_aj, new_b) gv.models[gv.modelnum].a[i] = new_ai gv.models[gv.modelnum].a[j] = new_aj gv.models[gv.modelnum].b = new_b updated = True print ("迭代次数: %d, 修改组合: i: %d 与 j:%d" %(time, i, j)) break # 测试数据 def test(): record = 0 record_correct = 0 for img in gv.tests: print ("正在测试:", img.filename) for modelnum in range(10): gv.modelnum = modelnum if predict(img) > 0: print ("测试结果:",modelnum) record += 1 if modelnum == int(img.filename[0]): record_correct += 1 break print ("相关记录数量:", record) print ("正确识别数量:", record_correct) print ("正确识别比例:", record_correct/record) print ("测试数据总量:", len(gv.tests)) if __name__ == "__main__": print ("开始时间:",time.strftime('%Y-%m-%d %H:%M:%S')) training = True loaddata("train/", gv.samples) loaddata("test/", gv.tests) print ("训练数据个数:",len(gv.samples)) print ("测试数据个数:",len(gv.tests)) if training == True: gv.init_cache() gv.init_models() print ("模型初始化成功!") print ("当前时间:",time.strftime('%Y-%m-%d %H:%M:%S')) T = 0.0001 C = 10 step = 0.001 gv.sigma = 1 if training == True: for i in range(10): print ("正在训练模型:", i) train(T, 10, C, i, step) save_models() else: load_models() for i in range(10): update_samples_label(i) print ("训练完成时间:",time.strftime('%Y-%m-%d %H:%M:%S')) test() print ("测试完成时间:",time.strftime('%Y-%m-%d %H:%M:%S'))
|