def fuzDistAC(dataF, outF, nCuts=11, disp=False): #=use McCulloch, Wagner, Aickelin - Measuring the Directional Distance Between Fuzzy Sets - 2013 #A = data, B = output acuts = np.arange(0.05, 1.0, 1.0/(nCuts)) dataCuts = [] outCuts = [] #get all the alpha cuts for i in range(len(acuts)): dataCuts.append(fuzzyOps.alpha_cut(acuts[i], dataF)) outCuts.append(fuzzyOps.alpha_cut(acuts[i], outF)) #check for no alpha cuts and return None if all([x == None for x in dataCuts]) or \ all([x == None for x in outCuts]): return None #get the Hausdorff metrics to get numerator sumCuts = 0.0 hVals = [] for i in range(len(acuts)): if dataCuts[i] <> None and outCuts[i] <> None: #use ammended hausdorff measure for directional distance if abs(outCuts[i][0] - dataCuts[i][0]) > abs(outCuts[i][1] - dataCuts[i][1]): h = outCuts[i][0] - dataCuts[i][0] else: h = outCuts[i][1] - dataCuts[i][1] hVals.append(h) else: hVals.append(None) #add max instead of empty sets for i in range(len(hVals)): if hVals[i] == None: hVals[i] = max(hVals) if disp: print "ERROR:" for i in range(len(acuts)): print " ==> a =", acuts[i], "dCut =", dataCuts[i], "oCut =", outCuts[i], "hVal =", hVals[i] dAB = sum([hVals[i]*acuts[i] for i in range(len(acuts))]) / sum(acuts) return dAB
def test1(): test_name = 'SYS: In:7-2 Out:9-2 DATA: In:3 Out:3' print "*************************************" print "TESTING: ", test_name inMFs = input_7gaussMFs #system in outMFs = output_9gaussMFs defuzz = None outForm = 'tri' inDataForm = 'tri' outDataForm = 'tri' errType = 'fuzzy' input_arrays, output_arrays = generate_MFs(inMFs, outMFs) inputMFs = { ('VL_SYS_UNION', 'phi'): copy.deepcopy(input_arrays['phi']),('FWD_SYS_UNION', 'phi'): copy.deepcopy(input_arrays['phi']), ('WING_SYS_TYPE', 'phi'): copy.deepcopy(input_arrays['phi']),('ENG_SYS_TYPE', 'phi'): copy.deepcopy(input_arrays['phi']), ('VL_SYS_UNION', 'w'): copy.deepcopy(input_arrays['w']),('VL_SYS_TYPE', 'TP'): copy.deepcopy(input_arrays['TP']),('WING_SYS_TYPE', 'WS'): copy.deepcopy(input_arrays['WS']),('VL_SYS_PROP', 'sigma'): copy.deepcopy(input_arrays['sigma']), ('VL_SYS_TYPE', 'e_d'): copy.deepcopy(input_arrays['e_d']),('VL_SYS_DRV', 'eta_d'): copy.deepcopy(input_arrays['eta_d']),('FWD_SYS_DRV', 'eta_d'): copy.deepcopy(input_arrays['eta_d']),('FWD_SYS_PROP', 'eta_p'): copy.deepcopy(input_arrays['eta_p']), } inputPARAMs = { ('VL_SYS_UNION', 'phi'): copy.deepcopy(inMFs['phi']), ('FWD_SYS_UNION', 'phi'): copy.deepcopy(inMFs['phi']),('WING_SYS_TYPE', 'phi'): copy.deepcopy(inMFs['phi']),('ENG_SYS_TYPE', 'phi'): copy.deepcopy(inMFs['phi']), ('VL_SYS_UNION', 'w'): copy.deepcopy(inMFs['w']), ('VL_SYS_TYPE', 'TP'): copy.deepcopy(inMFs['TP']),('WING_SYS_TYPE', 'WS'): copy.deepcopy(inMFs['WS']), ('VL_SYS_PROP', 'sigma'): copy.deepcopy(inMFs['sigma']), ('VL_SYS_TYPE', 'e_d'): copy.deepcopy(inMFs['e_d']),('VL_SYS_DRV', 'eta_d'): copy.deepcopy(inMFs['eta_d']),('FWD_SYS_DRV', 'eta_d'): copy.deepcopy(inMFs['eta_d']),('FWD_SYS_PROP', 'eta_p'): copy.deepcopy(inMFs['eta_p']), } outputMFs = {'sys_phi' : copy.deepcopy(output_arrays['sys_phi'])} outputPARAMs = {'sys_phi' : copy.deepcopy(outMFs['sys_phi'])} combinedData = copy.deepcopy(data) print combinedData[0] #generate rules with Timer() as t: rule_grid = train_system(inputMFs, outputMFs, combinedData, inDataMFs=inDataForm, outDataMFs=outDataForm, ruleMethod=3) #write out FCL write_fcl_file_FRBS(inputPARAMs, outputPARAMs, rule_grid, defuzz, 'test_sys_phi.fcl') #get system inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, implication, \ defuzz = build_fuzz_system('test_sys_phi.fcl') sys = Fuzzy_System(inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, implication, defuzz) print '=> ', t.secs, 'secs to build', len(sys.rulebase), 'rules' #test system with Timer() as t: error = getError(combinedData, sys, inMF=inDataForm, outMF=outDataForm, sysOutType=errType) print '=> ', t.secs, 'secs to check error' print 'Total System Error:', sum([err[2] for err in error]) print 'Mean Square System Error:', (1.0/len(error))*sum([err[2]**2 for err in error]) print 'Root Mean Square System Error:', ( (1.0/len(error)) * sum([err[2]**2 for err in error]) )**0.5 #actual vs. predicted plot plt.figure() plt.title('Actual vs. Predicted at Max Alpha Cut'+test_name) for err in error: if outDataForm == 'gauss': AC_actual = fuzzyOps.alpha_cut(0.8, [err[0][0],err[0][1]]) else: AC_actual = fuzzyOps.alpha_at_val(err[0][0],err[0][1]) if outForm == 'gauss': AC_pred = fuzzyOps.alpha_cut(0.8, (err[1][0],err[1][1])) else: AC_pred = fuzzyOps.alpha_at_val(err[1][0],err[1][1]) plt.scatter(AC_actual[0], AC_pred[0], marker='o', c='r') plt.scatter(AC_actual[1], AC_pred[1], marker='x', c='b') plt.plot([1,9],[1,9], '--k') plt.xlim([1,9]) plt.ylim([1,9]) plt.xlabel('Actual') plt.ylabel('Predicted') #visuzlize system with random data point #i = random.randrange(0, len(combinedData)) #inputs = {key[0]+"_"+key[1]:combinedData[i][0][key] for key in combinedData[i][0]} #sys.run(inputs, TESTMODE=True) #check random data points (9) plt.figure() plt.title('Random Tests:'+test_name) for j in range(9): i = random.randrange(0, len(combinedData)) inputs = {key[0]+"_"+key[1]:combinedData[i][0][key] for key in combinedData[i][0]} sysOut = sys.run(inputs) sysOut = sysOut[sysOut.keys()[0]] plt.subplot(3,3,j+1) plt.plot(sysOut[0], sysOut[1], '-r') plt.plot(combinedData[i][2][0], combinedData[i][2][1], '--k') plt.ylim([0,1.1]) plt.xlim([1,9]) #actual vs. error plot plt.figure() plt.title('Actual (Centroid) vs. Error'+test_name) cents = [fuzz.defuzz(err[0][0], err[0][1], 'centroid') for err in error] plt.scatter(cents, [err[2] for err in error]) plt.xlabel('Actual (Centroid)') plt.ylabel('Fuzzy Error')
ax.xaxis.grid(True) plt.subplots_adjust(left=0.09, bottom=0.08, right=0.94, top=0.94, wspace=None, hspace=0.18) """ alts = [0] res_all = results+results_new x_ind = 0 # Empty Weight y_ind = 3 # pts = 20 colors = ['grey', 'r', 'orange', 'coral', 'orange', 'lawngreen', 'c', 'b', 'purple', 'pink'] fig = plt.figure(figsize=(10,8)) ax = fig.add_subplot(111, projection='3d') for i in alts:#range(len(results)): #ax = plt.subplot(4,2,i+1) a_ix = fuzzyOps.alpha_cut(0.05, (res_all[i][x_ind][0],res_all[i][x_ind][1])) a_iy = fuzzyOps.alpha_cut(0.05, (res_all[i][y_ind][0],res_all[i][y_ind][1])) if a_ix <> None and a_iy <> None: xs = np.arange(a_ix[0], a_ix[1], (a_ix[1]-a_ix[0])/pts) ys = np.arange(a_iy[0], a_iy[1], (a_iy[1]-a_iy[0])/pts) mxs = np.interp(xs, results[i][x_ind][0], results[i][x_ind][1]) mys = np.interp(ys, results[i][y_ind][0], results[i][y_ind][1]) ms = np.ones((len(mxs), len(mys))) for j in range(len(mxs)): for k in range(len(mys)): ms[j,k] = min(mxs[j],mys[k]) xdat, ydat = np.meshgrid( mxs, mys ) xdat.flatten() ydat.flatten() ms.flatten()
def testMFs(tData, vData, test_name, inMFs, outMFs, outForm, inDataForm, outDataForm, defuzz=None, sysOutType="fuzzy", errType="dist"): print "*************************************" print "TESTING: ", test_name print len(tData), "training points", len(vData), "validation points." #inMFs = input_5gaussMFs #system in #outMFs = output_7gaussMFs #defuzz = None #outForm = 'gauss' #inDataForm = 'gauss' #outDataForm = 'gauss' #errType = 'fuzzy' input_arrays, output_arrays = generate_MFs(inMFs, outMFs) inputMFs = { inp: copy.deepcopy(input_arrays[inp[1]]) for inp in inputList } inputPARAMs = {inp: copy.deepcopy(inMFs[inp[1]]) for inp in inputList } outputMFs = {'sys_FoM' : copy.deepcopy(output_arrays['sys_FoM'])} outputPARAMs = {'sys_FoM' : copy.deepcopy(outMFs['sys_FoM'])} combinedData = copy.deepcopy(tData) #generate rules with Timer() as t: rule_grid = train_system(inputMFs, outputMFs, combinedData, inDataMFs=inDataForm, outDataMFs=outDataForm) #write out FCL write_fcl_file_FRBS(inputPARAMs, outputPARAMs, rule_grid, defuzz, 'test_sys_fom.fcl') #get system inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, implication, \ defuzz = build_fuzz_system('test_sys_fom.fcl') sys = Fuzzy_System(inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, implication, defuzz) print '=> ', t.secs, 'secs to build', len(sys.rulebase), 'rules' #test system testData = copy.deepcopy(vData) with Timer() as t: error = getError(testData, sys, inMF=inDataForm, outMF=outDataForm, sysOutType=sysOutType, errType=errType) print '=> ', t.secs, 'secs to check error' print 'Total System Error:', sum([err[2] for err in error if err[2] <> None]) print 'Mean Square System Error:', (1.0/ len([err for err in error if err[2] <> None]) ) * \ sum([err[2]**2 for err in error if err[2] <> None]) print 'Root Mean Square System Error:', ( ( 1.0/len([err for err in error if err[2] <> None]) ) *sum([err[2]**2 for err in error if err[2] <> None]) )**0.5 #check random data points for time check = 15 t_tot = 0.0 for j in range(check): i = random.randrange(0, len(testData)) inputs = {key[0]+"_"+key[1]:testData[i][0][key] for key in testData[i][0]} with Timer() as t: sysOut = sys.run(inputs) t_tot = t_tot + float(t.secs) print 'Average system time of %d points => %.5f s' % (check, t_tot/check) print ' => %.5f s per rule' % ((t_tot/check)/len(sys.rulebase)) #actual vs. predicted plot alpha = 0.7 plt.figure() plt.title('Actual vs. Predicted at Max Alpha Cut'+test_name) for err in error: if outDataForm == 'gauss': AC_actual = fuzzyOps.alpha_cut(alpha, [err[0][0],err[0][1]]) else: AC_actual = fuzzyOps.alpha_at_val(err[0][0],err[0][1]) if outForm == 'gauss': AC_pred = fuzzyOps.alpha_cut(alpha, (err[1][0],err[1][1])) else: AC_pred = fuzzyOps.alpha_at_val(err[1][0],err[1][1]) if AC_actual <> None and AC_pred <> None: plt.scatter(AC_actual[0], AC_pred[0], marker='o', c='r') plt.scatter(AC_actual[1], AC_pred[1], marker='x', c='b') plt.plot([0,9],[0,9], '--k') plt.xlim([0.4,1.0]) plt.ylim([0.4, 1.0]) plt.xlabel('Actual') plt.ylabel('Predicted') #visuzlize system with random data point #i = random.randrange(0, len(combinedData)) #inputs = {key[0]+"_"+key[1]:combinedData[i][0][key] for key in combinedData[i][0]} #sys.run(inputs, TESTMODE=True) #check random data points for time """ plotData = copy.deepcopy(vData) plt.figure() plt.title('Random Tests:'+test_name) for j in range(9): i = random.randrange(0, len(plotData)) inputs = {key[0]+"_"+key[1]:plotData[i][0][key] for key in plotData[i][0]} sysOut = sys.run(inputs) sysOut = sysOut[sysOut.keys()[0]] plt.subplot(3,3,j+1) plt.plot(sysOut[0], sysOut[1], '-r') plt.plot(plotData[i][2][0], plotData[i][2][1], '--k') plt.ylim([0,1.1]) plt.xlim([1,9]) """ #actual vs. error plot plt.figure() plt.title('Actual (Centroid) vs. Error'+test_name) cents = [fuzz.defuzz(err[0][0], err[0][1], 'centroid') for err in error] plt.scatter(cents, [err[2] for err in error]) plt.xlabel('Actual (Centroid)') plt.ylabel('Fuzzy Error') plt.show() return len(sys.rulebase), (1.0/len(error))*sum([err[2]**2 for err in error])
alts = [0] res_all = results + results_new x_ind = 0 # Empty Weight y_ind = 3 # pts = 20 colors = [ 'grey', 'r', 'orange', 'coral', 'orange', 'lawngreen', 'c', 'b', 'purple', 'pink' ] fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') for i in alts: #range(len(results)): #ax = plt.subplot(4,2,i+1) a_ix = fuzzyOps.alpha_cut(0.05, (res_all[i][x_ind][0], res_all[i][x_ind][1])) a_iy = fuzzyOps.alpha_cut(0.05, (res_all[i][y_ind][0], res_all[i][y_ind][1])) if a_ix <> None and a_iy <> None: xs = np.arange(a_ix[0], a_ix[1], (a_ix[1] - a_ix[0]) / pts) ys = np.arange(a_iy[0], a_iy[1], (a_iy[1] - a_iy[0]) / pts) mxs = np.interp(xs, results[i][x_ind][0], results[i][x_ind][1]) mys = np.interp(ys, results[i][y_ind][0], results[i][y_ind][1]) ms = np.ones((len(mxs), len(mys))) for j in range(len(mxs)): for k in range(len(mys)): ms[j, k] = min(mxs[j], mys[k]) xdat, ydat = np.meshgrid(mxs, mys) xdat.flatten() ydat.flatten()
def execute(self): """ Translate fuzzy inputs to crisp values to optimize system. """ inputs = [self.fuzzSys_in_1, self.fuzzSys_in_2, self.fuzzSys_in_3, self.fuzzSys_in_4, self.fuzzSys_in_5, self.fuzzSys_in_6, self.fuzzSys_in_7, self.fuzzSys_in_8, self.fuzzSys_in_9] outs = [[self.response_1][0], [self.response_2][0], self.response_3, self.response_4, self.response_5, self.response_6, self.response_7, self.response_8, self.response_9] outs_r = [self.response_1_r, self.response_2_r, self.response_3_r, self.response_4_r, self.response_5_r, self.response_6_r, self.response_7_r, self.response_8_r, self.response_9_r] if self.passthrough == 1: if self.printResults == 1: print "Incompatible combo found..." self.response_1 = 0.0 #phi self.response_1_r = 0.0 self.response_1_POS = -1.0 self.response_2 = 0.0 #FoM self.response_2_r = 0.0 self.response_2_POS = -1.0 self.response_3 = 0.0 #LoD self.response_3_r = 0.0 self.response_3_POS = -1.0 self.response_4 = 0.0 #etaP self.response_4_r = 0.0 self.response_4_POS = -1.0 self.response_5 = 0.0 #GWT self.response_5_r = 0.0 self.response_5_POS = -1.0 self.response_6 = -99999.0 #P self.response_6_r = 0.0 self.response_6_POS = 0.0 self.response_7 = 0.0 #VH self.response_7_r = 0.0 self.response_7_POS = -1.0 return None else: #get alpha cuts for crisp responses and ranges for i in range(len(inputs)): if inputs[i].mf_key <> '': if len(inputs[i].mf_dict[inputs[i].mf_key]) == 1: #crisp value self.ranges_out[inputs[i].mf_key] = [inputs[i].mf_dict[inputs[i].mf_key][0], inputs[i].mf_dict[inputs[i].mf_key][0]] elif len(inputs[i].mf_dict[inputs[i].mf_key]) == 2: #fuzzy function self.ranges_out[inputs[i].mf_key] = fuzzyOps.alpha_cut(self.alpha_val, inputs[i].mf_dict[inputs[i].mf_key]) #capture results for crisp measures if self.ranges_out[inputs[i].mf_key] <> None: y = self.ranges_out[inputs[i].mf_key] else: y = [0.0, 0.0] if inputs[i].mf_key == 'sys_phi': self.response_1 = fuzz.defuzz(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]),'centroid') self.response_1 = self.response_1 * math.exp(-self.incompatCount)**0.5 self.response_1_r = max(y) - min(y) self.response_1_POS = fuzzyOps.fuzzyPOS(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]), self.goalVals['sys_phi']) if inputs[i].mf_key == 'sys_FoM': self.response_2 = fuzz.defuzz(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]),'centroid') self.response_2 = self.response_2 * math.exp(-self.incompatCount)**0.5 self.response_2_r = max(y) - min(y) #if self.response_2 < 0.6: # self.response_2_POS = fuzzyOps.fuzzyPOS(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]), self.goalVals['sys_FoM'], direction='max', plot=True) self.response_2_POS = fuzzyOps.fuzzyPOS(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]), self.goalVals['sys_FoM']) if inputs[i].mf_key == 'sys_LoD': self.response_3 = fuzz.defuzz(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]),'centroid') self.response_2 = self.response_3 * math.exp(-self.incompatCount)**0.5 self.response_3_r = max(y) - min(y) self.response_3_POS = fuzzyOps.fuzzyPOS(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]), self.goalVals['sys_LoD']) if inputs[i].mf_key == 'sys_etaP': self.response_4 = fuzz.defuzz(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]),'centroid') self.response_4 = self.response_4 * math.exp(-self.incompatCount)**0.5 self.response_4_r = max(y) - min(y) self.response_4_POS = fuzzyOps.fuzzyPOS(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]), self.goalVals['sys_etaP']) if inputs[i].mf_key == 'sys_GWT': #invert GWT to maximize all self.response_5 = fuzz.defuzz(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]),'centroid') self.response_5 = self.response_5 * math.exp(-self.incompatCount)**0.5 self.response_5_r = max(y) - min(y) self.response_5_POS = fuzzyOps.fuzzyPOS(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]), self.goalVals['sys_GWT'], direction='min') if inputs[i].mf_key == 'sys_P': #invert GWT to maximize all self.response_6 = 0.0-fuzz.defuzz(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]),'centroid') self.response_6 = self.response_6 * math.exp(-self.incompatCount)**0.5 self.response_6_r = max(y) - min(y) self.response_6_POS = fuzzyOps.fuzzyPOS(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]), self.goalVals['sys_Pin'], direction='min') if inputs[i].mf_key == 'sys_VH': #invert GWT to maximize all self.response_7 = fuzz.defuzz(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]),'centroid') self.response_7 = self.response_7 * math.exp(-self.incompatCount)**0.5 self.response_7_r = max(y) - min(y) self.response_7_POS = fuzzyOps.fuzzyPOS(inputs[i].mf_dict[inputs[i].mf_key][0],np.array(inputs[i].mf_dict[inputs[i].mf_key][1]), self.goalVals['sys_VH']) self.fuzzyPOS = self.response_1_POS*self.response_2_POS*self.response_3_POS*self.response_4_POS*self.response_6_POS if self.printResults == 1: #print results print "Alternative:", self.passthrough, ":", print "PHI: %.1f, (%.3f)" % (self.response_1, self.response_1_POS), print " FoM: %.3f, (%.3f)" % (self.response_2, self.response_2_POS), print " L/D: %.1f, (%.3f)" % (self.response_3, self.response_3_POS), print " etaP: %.3f, (%.3f)" % (self.response_4, self.response_4_POS), print " GWT: %.0f, (%.3f)" % (self.response_5, self.response_5_POS), print " Pinst: %.0f, (%.3f)" % (self.response_6, self.response_6_POS), print " VH: %.0f, (%.3f)" % (self.response_7, self.response_7_POS), print " FPOS: %.3f" % self.fuzzyPOS #plotting for testing if self.PLOTMODE == 1: #plot results plt.figure() i=1 for r in inputs: plt.subplot(3,2,i) if r.mf_key <> '': if len(r.mf_dict[r.mf_key]) == 1: #crisp value pass#self.ranges_out[r.mf_key] = [r.mf_dict[r.mf_key][0], r.mf_dict[r.mf_key][1]] elif len(r.mf_dict[r.mf_key]) == 2: #fuzzy function plt.plot(r.mf_dict[r.mf_key][0],r.mf_dict[r.mf_key][1]) i = i + 1 plt.show()
def testMFs(tData, vData, test_name, inMFs, outMFs, outForm, inDataForm, outDataForm, defuzz=None, sysOutType="fuzzy", errType="dist", plot=True): print "*************************************" print "TESTING: ", test_name print len(tData), "training points", len(vData), "validation points." #inMFs = input_5gaussMFs #system in #outMFs = output_7gaussMFs #defuzz = None #outForm = 'gauss' #inDataForm = 'gauss' #outDataForm = 'gauss' #errType = 'fuzzy' input_arrays, output_arrays = generate_MFs(inMFs, outMFs) inputMFs = { inp: copy.deepcopy(input_arrays[inp[1]]) for inp in inputList } inputPARAMs = {inp: copy.deepcopy(inMFs[inp[1]]) for inp in inputList } outputMFs = {'sys_phi' : copy.deepcopy(output_arrays['sys_phi'])} outputPARAMs = {'sys_phi' : copy.deepcopy(outMFs['sys_phi'])} combinedData = copy.deepcopy(tData) #generate rules with Timer() as t: rule_grid = train_system(inputMFs, outputMFs, combinedData, inDataMFs=inDataForm, outDataMFs=outDataForm) #write out FCL write_fcl_file_FRBS(inputPARAMs, outputPARAMs, rule_grid, defuzz, 'test_sys_phi.fcl') #get system inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, implication, \ defuzz = build_fuzz_system('test_sys_phi.fcl') sys = Fuzzy_System(inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, implication, defuzz) print '=> ', t.secs, 'secs to build', len(sys.rulebase), 'rules' #test system testData = copy.deepcopy(vData) with Timer() as t: error = getError(testData, sys, inMF=inDataForm, outMF=outDataForm, sysOutType=sysOutType, errType=errType) print '=> ', t.secs, 'secs to check error' print 'Total System Error:', sum([err[2] for err in error if err[2] <> None]) print 'Mean Square System Error:', sum([err[2]**2 for err in error if err[2] <> None]) / len([err for err in error if err[2] <> None]) print 'Root Mean Square System Error:', ( sum([err[2]**2 for err in error if err[2] <> None]) / len([err for err in error if err[2] <> None]) )**0.5 #check random data points for time check = 15 t_tot = 0.0 for j in range(check): i = random.randrange(0, len(testData)) inputs = {key[0]+"_"+key[1]:testData[i][0][key] for key in testData[i][0]} with Timer() as t: sysOut = sys.run(inputs) t_tot = t_tot + float(t.secs) print 'Average system time of %d points => %.5f s' % (check, t_tot/check) print ' => %.5f s per rule' % ((t_tot/check)/len(sys.rulebase)) #actual vs. predicted plot alpha = 0.7 plt.figure() plt.title('Actual vs. Predicted at Max Alpha Cut'+test_name) for err in error: if outDataForm == 'gauss': AC_actual = fuzzyOps.alpha_cut(alpha, [err[0][0],err[0][1]]) else: AC_actual = fuzzyOps.alpha_at_val(err[0][0],err[0][1]) if outForm == 'gauss': AC_pred = fuzzyOps.alpha_cut(alpha, (err[1][0],err[1][1])) else: AC_pred = fuzzyOps.alpha_at_val(err[1][0],err[1][1]) if AC_actual <> None and AC_pred <> None: plt.scatter(AC_actual[0], AC_pred[0], marker='o', c='r') plt.scatter(AC_actual[1], AC_pred[1], marker='x', c='b') plt.plot([1,9],[1,9], '--k') plt.xlim([1,9]) plt.ylim([1,9]) plt.xlabel('Actual') plt.ylabel('Predicted') #visuzlize system with random data point #i = random.randrange(0, len(combinedData)) #inputs = {key[0]+"_"+key[1]:combinedData[i][0][key] for key in combinedData[i][0]} #sys.run(inputs, TESTMODE=True) #check random data points for time """ plt.figure() plt.title('Random Tests:'+test_name) for j in range(9): i = random.randrange(0, len(combinedData)) inputs = {key[0]+"_"+key[1]:combinedData[i][0][key] for key in combinedData[i][0]} sysOut = sys.run(inputs) sysOut = sysOut[sysOut.keys()[0]] plt.subplot(3,3,j+1) plt.plot(sysOut[0], sysOut[1], '-r') plt.plot(combinedData[i][2][0], combinedData[i][2][1], '--k') plt.ylim([0,1.1]) plt.xlim([1,9]) """ #actual vs. error plot """ plt.figure() plt.title('Actual (Centroid) vs. Error'+test_name) cents = [fuzz.defuzz(err[0][0], err[0][1], 'centroid') for err in error] plt.scatter(cents, [err[2] for err in error]) plt.xlabel('Actual (Centroid)') plt.ylabel('Fuzzy Error') """ return len(sys.rulebase), sum([err[2]**2 for err in error if err[2] <> None]) / len([err for err in error if err[2] <> None])