result = []
long = math.pow(10, self.random_long)
for i in range(0, x, 1):
res = []
for j in range(0, y, 1):
num = round(random.randint(-1*long,long)/long, self.random_long)
res.insert(j, num)
result.insert(i, res)
return result
#初始阈值生成器
def __ini_threshold(self, n):
result = []
long = pow(10, self.random_long)
for i in range(0, n, 1):
num = round(random.randint(-1*long,long)/long, self.random_long)
result.insert(i, num)
return result
self.input = []
for value in data:
self.input.append(value)
if(expectation):
self.expectation = []
for value in expectation:
self.expectation.append(value)
#隐层计算
def count_hidden(self):
self.hidden = []
for h in range(0, self.hidden_num, 1):
Hval = 0
for i in range(len(self.input)):
Hval += self.input[i] * self.weight_ih[i][h]
Hval = self.excitation(Hval+self.threshold_h[h])
self.hidden.insert(h, Hval)
#输出层计算
def count_output(self):
self.output = []
for o in range(0, self.output_num, 1):
Oval = 0
for h in range(len(self.hidden)):
Oval += self.hidden[h] * self.weight_ho[h][o]
Oval += self.threshold_o[o]
Oval = round(Oval, self.num_long)
self.output.insert(o, Oval)
#误差计算
def count_error(self):
self.error = []
for key in range(len(self.output)):
self.error.insert(key, self.expectation[key] - self.output[key])
#连接权反馈训练 输入层->隐层
def train_weight_ih(self):
for i in range(len(self.weight_ih)):
for h in range(len(self.weight_ih[i])):
tmp = 0
for o in range(0, self.output_num, 1):
tmp += self.weight_ho[h][o] * self.error[o]
self.weight_ih[i][h] = self.weight_ih[i][h] + self.learn_rate * self.hidden[h] * (1 - self.hidden[h]) * self.input[i] * tmp
#连接权反馈训练 隐层->输出层
def train_weight_ho(self):
for h in range(len(self.weight_ho)):
for o in range(len(self.weight_ho[h])):
self.weight_ho[h][o] = self.weight_ho[h][o] + self.learn_rate * self.hidden[h] * self.error[o]
#阈值反馈训练 隐层
def train_threshold_h(self):
for h in range(len(self.threshold_h)):
tmp = 0
for o in range(0, self.output_num, 1):
tmp += self.weight_ho[h][o] * self.error[o]
self.threshold_h[h] = self.threshold_h[h] + self.learn_rate * self.hidden[h] * (1 - self.hidden[h]) * tmp
#阈值反馈训练 输出层
def train_threshold_o(self):
for o in range(len(self.threshold_o)):
self.threshold_o[o] = self.threshold_o[o] + self.error[o]
for i in range(len(data)):
#计算期望值
exp = testFunc(data)
#输入训练数据与期望
ann.input_param(dataNormal, exp)
#计算隐层
ann.count_hidden()
#计算输出层
ann.count_output()
#计算误差
ann.count_error()
#反馈训练
ann.train()
生成测试数据,随机生成20组
testdata = []
for i in range(0, 20, 1):
x = random.randint(0,1)
y = random.randint(0,1)
testdata.append([x,y])
进行测试,同时输出神经网络预测值与实际期望值
for i in range(len(testdata)):
exp = testFunc(testdata)
ann.input_param(testdata)
ann.count_hidden()
ann.count_output()
print("Ann:")
print(ann.output)
print("Exp:")
print(exp)
print("\r")