这个难到是不难,主要是熟悉python和文件IO
第一次写python,模块化做的不是很好,代码写的也比较乱。
也没有使用numpy,这代码就算python的第一次练手了
#!/usr/bin/python3.5 import os import math def Read_W_and_b(m): if not os.path.exists('W_and_b.txt'): os.mknod('W_and_b.txt') f_W_and_b = open('W_and_b.txt','a') W_and_b = [] for i in range(m): f_W_and_b.write('0.0') f_W_and_b.write(' ') W_and_b.append(0) W_and_b.append(0) f_W_and_b.write('0') f_W_and_b.write(' ') f_W_and_b.close() return W_and_b else: f_W_and_b = open('W_and_b.txt') line = f_W_and_b.readline() result = line.split() W_and_b = [] for i in result: W_and_b.append(float(str(i))) f_W_and_b.close() return W_and_b def getTrainSet(): if not os.path.exists('train.txt'): return -1,-1 fTrainSet = open('train.txt') example = [[],[]] ans = [] while 1: line = fTrainSet.readline() if not line: break pass result = line.split() example[0].append(float(str(result[0]))) example[1].append(float(str(result[1]))) ans.append(float(str(result[2]))) return example,ans def sigmoid(z): if z<=-100: return 1 return 1/(1+math.exp(-z)) def L(a, y): return -(y*math.log(a)+(1-y)*math.log(1-a)) def Z(x1, x2, w1, w2,b): return x1*w1+x2*w2+b def cal_d(W_and_b, X1_X2, Y): Derivative = [0,0,0] Len = len(X1_X2)-1 for k in range(0,Len): z = Z(X1_X2[0][k],X1_X2[1][k],W_and_b[0],W_and_b[1],W_and_b[2]) a = sigmoid(z) Derivative[0] = Derivative[0] - (a-Y[k])*X1_X2[0][k] Derivative[1] = Derivative[1] - (a-Y[k])*X1_X2[1][k] Derivative[2] = Derivative[2] - (a-Y[k]) Derivative[0] = Derivative[0]/(Len+1) Derivative[1] = Derivative[1]/(Len+1) Derivative[2] = Derivative[2]/(Len+1) return Derivative def cal_add(Derivative,alaph): Derivative[0] = Derivative[0] * alaph Derivative[1] = Derivative[1] * alaph Derivative[2] = Derivative[2] * alaph return Derivative def Write_W_and_b(W_and_b): f_W_and_b = open('W_and_b.txt','w') f_W_and_b.write(str(W_and_b[0])) f_W_and_b.write(' ') f_W_and_b.write(str(W_and_b[1])) f_W_and_b.write(' ') f_W_and_b.write(str(W_and_b[2])) f_W_and_b.write(' ') f_W_and_b.close() return def train(m):#m表示数据为长度为m的行向量 W_and_b = Read_W_and_b(m) X1_X2, Y = getTrainSet() if X1_X2 == -1 and Y == -1: print('无法找到训练集') return Derivative = cal_d(W_and_b, X1_X2, Y) add = cal_add(Derivative,1) W_and_b[0] = W_and_b[0] + add[0] W_and_b[1] = W_and_b[1] + add[1] W_and_b[2] = W_and_b[2] + add[2] print(W_and_b) Write_W_and_b(W_and_b) print("训练完成") return def calPrep(x,y,W_and_b): save = x*W_and_b[0]+y*W_and_b[1]+W_and_b[2] if save >= 0: return 1 else: return 0 def test(m): W_and_b = Read_W_and_b(m) while 1: x, y = map(int,input("输入x,y:").strip().split()) if x==-1 and y==-1: break else: print(calPrep(x,y,W_and_b)) return print("开始训练: 1") op = int(input("开始使用: 2 ")) if op==1: train(2) else: test(2)