def main(): QALL = [] global handles global Rn RBF.set_handles(handles,env) env.SetViewer('qtcoin') Pd, q0 = initialPoint() sign = 1 q0=q0[0][0] robot.SetDOFValues(q0,ikmodel.manip.GetArmIndices()) manipulabilityNUM = coating.manipulabilityDET(manip) for i in range(0,loops): yR, yL, Q = drawParallel(Pd,q0,sign) if sign==1: P0=yL[-1] qi=Q[0] else: P0=yR[-1] qi=Q[-1] QALL.extend(Q) Rn+=loopdistance*0.003 Pd, Qd=meridian2(P0,1,qi) yM = getPointsfromQ(Qd) QALL.extend(Qd) handles=plotPoints(yM, handles,array((1,0,0))) sign*=-1 q0=Qd[-1] return QALL
def main2(): global handles RBF.set_handles(handles,env) #env.SetViewer('qtcoin') yR, yL, Q = main() handles=plotPoints(yL, handles,array((0,0,0))) handles=plotPoints(yR, handles,array((0,0,0))) P0=yL[-1] Rn=nextLine(P0) Rn+=33*0.003 Pd, Qd=meridian2(P0,Rn,1,Q[0]) yM = getPointsfromQ(Qd) yR2, yL2, Q2 = drawParallel(Pd,Qd[-1],-1) handles=plotPoints(yM, handles,array((0,0,0))) handles=plotPoints(yL2, handles,array((0,0,0))) handles=plotPoints(yR2, handles,array((0,0,0))) P0=yR2[-1] Rn=nextLine(P0) Rn+=33*0.003 Pd, Qd=meridian2(P0,Rn,1,Q[-1]) yM = getPointsfromQ(Qd) yR3, yL3, Q3 = drawParallel(Pd,Qd[-1],1) handles=plotPoints(yM, handles,array((0,0,0))) handles=plotPoints(yL3, handles,array((0,0,0))) handles=plotPoints(yR3, handles,array((0,0,0))) return yR3, yL3, Q3,yR2, yL2, Q2, yR, yL, Q
def calFitness(self, x): # # sum = 0 # # length = len(x) # # x = x ** 2 # # for i in range(length): # # sum += x[i] # if(x[0]>1 or x[0]<0): # x[0]=0.1 # result = start_cluster(self.data, x[0]) # centers = [] # for i in range(len(result)): # #print("----------第" + str(i + 1) + "个聚类----------",result[i]) # #y=0 # center=np.zeros(5) # for j in range(len(result[i])): # center+=np.array(result[i][j]) # #y+=self.Y[self.data.index(result[i][j])] # center/=len(result[i]) # #y/=len(result[i]) # centers.append(center) # b = self.calbeta(result,centers) centers = [] b = [] for i in range(int(self.dim / 6)): temp = x[i * 6:(i + 1) * 6 - 1] centers.append(temp) temp = x[(i + 1) * 6 - 1] b.append(temp) rbf = RBF(5, int(self.dim / 6), 1, centers, b) rbf.train(self.data, self.Y) fitness = rbf.cal_distance(self.data, self.Y) #print('fitness:',fitness) return fitness
def testDigits(kTup=('rbf', 10)): dataArr, labelArr = loadImages('trainingDigits') b, alphas = RBF.smoP(dataArr, labelArr, 200, 0.0001, 10000, kTup) datMat = mat(dataArr) labelMat = mat(labelArr).transpose() svInd = nonzero(alphas.A > 0)[0] sVs = datMat[svInd] labelSV = labelMat[svInd] print "there are %d Support Vectors" % shape(sVs)[0] m, n = shape(datMat) errorCount = 0 for i in range(m): kernelEval = RBF.kernelTrans(sVs, datMat[i, :], kTup) predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b if sign(predict) != sign(labelArr[i]): errorCount += 1 print "the training error rate is: %f" % (float(errorCount) / m) dataArr, labelArr = loadImages('testDigits') errorCount = 0 datMat = mat(dataArr) labelMat = mat(labelArr).transpose() m, n = shape(datMat) for i in range(m): kernelEval = RBF.kernelTrans(sVs, datMat[i, :], kTup) predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b if sign(predict) != sign(labelArr[i]): errorCount += 1 print "the test error rate is: %f" % (float(errorCount) / m)
def predict_frame_pixel(data, def_param=(shared_v_data, shared_u_data)): y, x = data shared_delayed_v_data = create_0d_delay_coordinates(shared_v_data[:, y, x], ddim, tau=32) delayed_patched_v_data_train = shared_delayed_v_data[:trainLength] u_data_train = shared_u_data[:trainLength, y, x] delayed_patched_v_data_test = shared_delayed_v_data[ trainLength:trainLength + testLength] u_data_test = shared_u_data[trainLength:trainLength + testLength, y, x] flat_v_data_train = delayed_patched_v_data_train.reshape(-1, ddim) flat_u_data_train = u_data_train.reshape(-1, 1) flat_v_data_test = delayed_patched_v_data_test.reshape(-1, ddim) flat_u_data_test = u_data_test.reshape(-1, 1) rbf = RBF(sigma=5.0) rbf.fit(flat_v_data_train, flat_u_data_train, basisQuota=0.02) pred = rbf.predict(flat_v_data_test) pred = pred.ravel() return pred
def FindNextParallel(P0,sign): dt = 1e-4 y=array([float(P0[0]),float(P0[1]),float(P0[2])]) d = sqrt(P0[0]**2+P0[1]**2+P0[2]**2) R0=1.425 n = math.ceil((d-R0)/0.003) Rn = R0+n*0.003 dif = d-Rn S=(dif>0) tol=1e-6 while abs(dif)>1e-4: tand = tangentd(y,sign)*dt pnew = y+tand res = RBF.optmizeTan(y, pnew, tol) if dot(res.x-y,res.x-y)==0:tol*=0.1 y = res.x d = sqrt(res.x[0]**2+res.x[1]**2+res.x[2]**2) dif = d-Rn if S!=(dif>0): sign*=-1 dt*=0.5 S=(dif>0) norm = RBF.df([y[0],y[1],y[2]]) norm /= sqrt(dot(norm,norm)) y = array([y[0],y[1],y[2],norm[0],norm[1],norm[2]]) return y
def predict_inner_pixel(data, def_param=(shared_v_data, shared_u_data)): y, x = data shared_delayed_v_data = create_2d_delay_coordinates( shared_v_data[:, y - patch_radius:y + patch_radius + 1, x - patch_radius:x + patch_radius + 1][:, ::sigma_skip, ::sigma_skip], ddim, tau=32) shared_delayed_patched_v_data = np.empty( (ndata, 1, 1, ddim * eff_sigma * eff_sigma)) shared_delayed_patched_v_data[:, 0, 0] = shared_delayed_v_data.reshape( -1, ddim * eff_sigma * eff_sigma) delayed_patched_v_data_train = shared_delayed_patched_v_data[:trainLength, 0, 0] u_data_train = shared_u_data[:trainLength, y, x] delayed_patched_v_data_test = shared_delayed_patched_v_data[ trainLength:trainLength + testLength, 0, 0] u_data_test = shared_u_data[trainLength:trainLength + testLength, y, x] flat_v_data_train = delayed_patched_v_data_train.reshape( -1, shared_delayed_patched_v_data.shape[3]) flat_u_data_train = u_data_train.reshape(-1, 1) flat_v_data_test = delayed_patched_v_data_test.reshape( -1, shared_delayed_patched_v_data.shape[3]) flat_u_data_test = u_data_test.reshape(-1, 1) rbf = RBF(sigma=5.0) rbf.fit(flat_v_data_train, flat_u_data_train, basisQuota=0.02) pred = rbf.predict(flat_v_data_test) pred = pred.ravel() return pred
def FindNextParallel(P0, sign): dt = 1e-4 y = array([float(P0[0]), float(P0[1]), float(P0[2])]) d = sqrt(P0[0]**2 + P0[1]**2 + P0[2]**2) R0 = 1.425 n = math.ceil((d - R0) / 0.003) Rn = R0 + n * 0.003 dif = d - Rn S = (dif > 0) tol = 1e-6 while abs(dif) > 1e-4: tand = tangentd(y, sign) * dt pnew = y + tand res = RBF.optmizeTan(y, pnew, tol) if dot(res.x - y, res.x - y) == 0: tol *= 0.1 y = res.x d = sqrt(res.x[0]**2 + res.x[1]**2 + res.x[2]**2) dif = d - Rn if S != (dif > 0): sign *= -1 dt *= 0.5 S = (dif > 0) norm = RBF.df([y[0], y[1], y[2]]) norm /= sqrt(dot(norm, norm)) y = array([y[0], y[1], y[2], norm[0], norm[1], norm[2]]) return y
def Qvector(y, Q, sign): global handles suc = True while suc: tan, q, suc = tangentOptm(y[-1], Q[-1]) if not coating.CheckDOFLimits(robot, q): wait = input("deu bode, PRESS 1 ENTER TO CONTINUE.") iksolList = fullSolution(y[-1]) Q = [iksolList[0][0]] Q = Qvector_backtrack(y, Q) continue if suc: Q.append(q) xold = y[-1][0:3] pnew = xold + sign * tan * dt tol = 1e-5 xnew = xold while dot(xnew - xold, xnew - xold) <= tol: res = coating.optmizeTan(xold, pnew, tol) tol *= 0.1 xnew = res.x temp = RBF.f([xnew[0], xnew[1], xnew[2]]) dv = array(RBF.df([xnew[0], xnew[1], xnew[2]])) normdv = sqrt(dot(dv, dv)) #print 'success:', res.success, ' fn:', polynomial_spline.fn4(xnew[0],xnew[1],xnew[2])/normdv n = dv / normdv P = concatenate((xnew, n)) y.append(P) handles = plotPoint(P, handles, array((0, 1, 0))) print RBF.f(P[0:3]) return Q, y
def Qvector(y,Q,sign): global handles suc=True while suc: tan, q, suc = tangentOptm(y[-1],Q[-1]) if not coating.CheckDOFLimits(robot,q): wait = input("deu bode, PRESS 1 ENTER TO CONTINUE.") iksolList = fullSolution(y[-1]) Q=[iksolList[0][0]] Q = Qvector_backtrack(y,Q) continue if suc: Q.append(q) xold = y[-1][0:3] pnew = xold + sign*tan*dt tol=1e-5 xnew = xold while dot(xnew-xold,xnew-xold)<=tol: res = coating.optmizeTan(xold, pnew, tol) tol*=0.1 xnew = res.x temp = RBF.f([xnew[0], xnew[1], xnew[2]]) dv = array(RBF.df([xnew[0],xnew[1],xnew[2]])) normdv = sqrt(dot(dv,dv)) #print 'success:', res.success, ' fn:', polynomial_spline.fn4(xnew[0],xnew[1],xnew[2])/normdv n = dv/normdv P=concatenate((xnew,n)) y.append(P) handles=plotPoint(P, handles,array((0,1,0))) print RBF.f(P[0:3]) return Q,y
def main3(): QALL = [] global handles RBF.set_handles(handles, env) env.SetViewer('qtcoin') Pd, q0 = initialPoint() sign = 1 q0 = q0[0][0] robot.SetDOFValues(q0, ikmodel.manip.GetArmIndices()) manipulabilityNUM = coating.manipulabilityDET(manip) for i in range(0, loops): yR, yL, Q = drawParallel(Pd, q0, sign) if sign == 1: P0 = yL[-1] qi = Q[0] else: P0 = yR[-1] qi = Q[-1] QALL.extend(Q) Rn = nextLine(P0) Rn += loopdistance * 0.003 Pd, Qd = meridian2(P0, Rn, 1, qi) yM = getPointsfromQ(Qd) QALL.extend(Qd) #handles=plotPoints(yL, handles,array((1,0,0))) #handles=plotPoints(yR, handles,array((1,0,0))) handles = plotPoints(yM, handles, array((1, 0, 0))) sign *= -1 q0 = Qd[-1] return QALL
def main2(): global handles RBF.set_handles(handles, env) #env.SetViewer('qtcoin') yR, yL, Q = main() handles = plotPoints(yL, handles, array((0, 0, 0))) handles = plotPoints(yR, handles, array((0, 0, 0))) P0 = yL[-1] Rn = nextLine(P0) Rn += 33 * 0.003 Pd, Qd = meridian2(P0, Rn, 1, Q[0]) yM = getPointsfromQ(Qd) yR2, yL2, Q2 = drawParallel(Pd, Qd[-1], -1) handles = plotPoints(yM, handles, array((0, 0, 0))) handles = plotPoints(yL2, handles, array((0, 0, 0))) handles = plotPoints(yR2, handles, array((0, 0, 0))) P0 = yR2[-1] Rn = nextLine(P0) Rn += 33 * 0.003 Pd, Qd = meridian2(P0, Rn, 1, Q[-1]) yM = getPointsfromQ(Qd) yR3, yL3, Q3 = drawParallel(Pd, Qd[-1], 1) handles = plotPoints(yM, handles, array((0, 0, 0))) handles = plotPoints(yL3, handles, array((0, 0, 0))) handles = plotPoints(yR3, handles, array((0, 0, 0))) return yR3, yL3, Q3, yR2, yL2, Q2, yR, yL, Q
def onecurvepoint(p0): tol=1e-4 while True: df = RBF.df(p0) p1 = p0 - RBF.f(p0)*df/dot(df,df) dif = p1-p0 if sqrt(dot(dif,dif))<tol: return p1 else: p0=p1
def layoutBest(self): centers = [] b = [] for i in range(int(self.dim / 6)): temp = self.gbest[i * 6:(i + 1) * 6 - 1] centers.append(temp) temp = self.gbest[(i + 1) * 6 - 1] b.append(temp) dim = int(self.dim / 6) rbf = RBF(5, dim, 1, centers, b) rbf.train(self.data, self.Y) return rbf
def main(): global handles global Rn RBF.set_handles(handles,env) env.SetViewer('qtcoin') Pd = initialPoint() for i in range(0,loops): y = drawParallel(Pd) P0=y[-1] Rn+=loopdistance*0.003 #Pd, Qd=meridian2(P0,1,qi) return y
def main(): global handles global Rn RBF.set_handles(handles, env) env.SetViewer("qtcoin") Pd = initialPoint() for i in range(0, loops): y = drawParallel(Pd) P0 = y[-1] Rn += loopdistance * 0.003 # Pd, Qd=meridian2(P0,1,qi) return y
def curvepoint(p0): tol=1e-4 while True: df1 = RBF.df(p0); f1 = RBF.f(p0) df2 = array([2*p0[0],2*p0[1],2*p0[2]]); f2 = p0[0]**2+p0[1]**2+p0[2]**2-Rn**2 df1df2 = dot(df1,df2); df1df1 = dot(df1,df1); df2df2 = dot(df2,df2) beta = (-f1+f2*df1df1/df1df2)/(df1df2-df1df1*df2df2/df1df2) alpha = (-f1+f2*df1df2/df2df2)/(df1df1-df1df2*df1df2/df2df2) dk = alpha*df1+beta*df2 p1 = p0+dk dif = p1-p0 if sqrt(dot(dif,dif))<tol: return p1 else: p0=p1
def meridian2(P0,Rn,sign,q0): print 'meridian2' Q=[q0] dt = 1e-4 y=array([float(P0[0]),float(P0[1]),float(P0[2])]) d = sqrt(P0[0]**2+P0[1]**2+P0[2]**2) dif = d-Rn S=(dif>0) tol=1e-6 notstop = True while abs(dif)>1e-4: tand = tangentd(y,sign)*dt pnew = y+tand res = coating.optmizeTan(y, pnew,tol) if dot(res.x-y,res.x-y)==0:tol*=0.1 y=res.x if notstop: norm = RBF.df([y[0],y[1],y[2]]) norm /= sqrt(dot(norm,norm)) ray = array([y[0],y[1],y[2],norm[0],norm[1],norm[2]]) resQ = coating.optmizeQ(robot,ikmodel,manip,ray,Q[-1]) if resQ.success: Q.append(resQ.x) else: print 'Meridian Error' d = sqrt(res.x[0]**2+res.x[1]**2+res.x[2]**2) dif = d-Rn if S!=(dif>0): notstop = False sign*=-1 dt*=0.5 S=(dif>0) norm = RBF.df([y[0],y[1],y[2]]) norm /= sqrt(dot(norm,norm)) ray = array([y[0],y[1],y[2],norm[0],norm[1],norm[2]]) resQ = coating.optmizeQ(robot,ikmodel,manip,ray,Q[-1]) if resQ.success: Q.append(resQ.x) else: print 'Meridian Error' return ray, Q
def run(self): # Train an RBF network based on its input parameters and dataset print( "Thread {0}: starting {1} TRAINING with {2} dimensions and {3} basis functions at {4}" .format(self.thread_ID, self.name, self.num_dim, self.num_basis, time.ctime(time.time()))) rbf = RBF.RBF(self.num_basis, self.training_data) loss_set = rbf.train() with open('RBF_{0}.csv'.format(self.thread_ID), 'wb') as csvfile: results_writ = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) results_writ.writerow(loss_set) # Test the same RBF network on a portion of the dataset print( "Thread {0}: starting {1} TESTING with {2} dimensions and {3} basis functions at {4}" .format(self.thread_ID, self.name, self.num_dim, self.num_basis, time.ctime(time.time()))) result = rbf.hypothesis_of(self.testing_data) print( "Thread {0}: {1} result {5} with {2} dimensions and {3} basis functions at {4}" .format(self.thread_ID, self.name, self.num_dim, self.num_basis, time.ctime(time.time()), '?'))
def fit_predict_pixel(y, x, running_index, training_data, test_data, generate_new): training_data_in = training_data[1][:, y - patch_radius:y + patch_radius+1, x - patch_radius:x + patch_radius+1][:, ::sigma_skip, ::sigma_skip].reshape(-1, eff_sigma*eff_sigma) training_data_out = training_data[0][:, y, x].reshape(-1, 1) test_data_in = test_data[1][:, y - patch_radius:y + patch_radius+1, x - patch_radius:x + patch_radius+1][:, ::sigma_skip, ::sigma_skip].reshape(-1, eff_sigma*eff_sigma) test_data_out = test_data[0][:, y, x].reshape(-1, 1) rbf = RBF(sigma=5.0) rbf.fit(training_data_in, training_data_out, basisQuota=0.02) pred = rbf.predict(test_data_in) pred = pred.ravel() pred[pred>1.0] = 1.0 pred[pred<0.0] = 0.0 return pred
def meridian2(P0, Rn, sign, q0): print 'meridian2' Q = [q0] dt = 1e-4 y = array([float(P0[0]), float(P0[1]), float(P0[2])]) d = sqrt(P0[0]**2 + P0[1]**2 + P0[2]**2) dif = d - Rn S = (dif > 0) tol = 1e-6 notstop = True while abs(dif) > 1e-4: tand = tangentd(y, sign) * dt pnew = y + tand res = coating.optmizeTan(y, pnew, tol) if dot(res.x - y, res.x - y) == 0: tol *= 0.1 y = res.x if notstop: norm = RBF.df([y[0], y[1], y[2]]) norm /= sqrt(dot(norm, norm)) ray = array([y[0], y[1], y[2], norm[0], norm[1], norm[2]]) resQ = coating.optmizeQ(robot, ikmodel, manip, ray, Q[-1]) if resQ.success: Q.append(resQ.x) else: print 'Meridian Error' d = sqrt(res.x[0]**2 + res.x[1]**2 + res.x[2]**2) dif = d - Rn if S != (dif > 0): notstop = False sign *= -1 dt *= 0.5 S = (dif > 0) norm = RBF.df([y[0], y[1], y[2]]) norm /= sqrt(dot(norm, norm)) ray = array([y[0], y[1], y[2], norm[0], norm[1], norm[2]]) resQ = coating.optmizeQ(robot, ikmodel, manip, ray, Q[-1]) if resQ.success: Q.append(resQ.x) else: print 'Meridian Error' return ray, Q
def run_RBF(self, key, dataset, train, test, isClassification, output_neuron, type_): prot = ld.LoadDataset().getRBFhiddenLayer(key, type_) rbf = RBF.RBF(train, prot, isClassification, output_neuron) epoch, result = rbf.train() plot_graph(key+' with RBF type '+ type_, epoch, result) x_test, test_label = ld.LoadDataset().get_neural_net_input_shape(dataset, test, isClassification) predicted = rbf.test(x_test) return predicted, test.iloc[:, -1]
def tRBF(): ''' Radial basis function test ''' Loc, POI, Prec = DataLoad.lcsv('TestData\GaugeLoc.csv', 'TestData\InterpPts.csv', 'TestData\Dataset.csv') Z, Zavg = RBF.Interp_bat(Loc, POI, Prec, 0, 20) return 'Radial Basis Function Interpolation working fine!'
def drawParallel(ray,q0,sign): viable=isViable(q0,ray[3:6]) Ql=[]; yL=[]; Qr=[]; yR=[] if viable: print 'drawParallel: is viable' QL=[q0] QR=[q0] y=[ray] #Arriscado - Pode caminhar em duas funcoes esquerda-direita if sign==1: Qr, yR = Qvector(y,QR,sign) #print 'sign 1: Qr -',array(Qr).shape,', yR -',array(yR).shape y=[ray] sign*=-1 Ql, yL = Qvector(y,QL,sign) #print 'sign -1: Ql -',array(Ql).shape,', yL -',array(yL).shape else: Ql, yL = Qvector(y,QL,sign) y=[ray] sign*=-1 Qr, yR = Qvector(y,QR,sign) else: sign*=-1 print 'drawParallel: solution not found' tol = 1e-6 while not viable: y=ray[0:3] tan, q0, viable = tangentOptm(ray,q0) tan *= sign*dt pnew = y+tan res = coating.optmizeTan(y, pnew, tol) if dot(res.x-y,res.x-y)==0: tol*=0.1 y=res.x norm = RBF.df([y[0],y[1],y[2]]) norm /= sqrt(dot(norm,norm)) ray = array([y[0],y[1],y[2],norm[0],norm[1],norm[2]]) print 'drawParallel: solution found' QL=[q0] QR=[q0] y=[ray] #Arriscado - Pode caminhar em duas funcoes esquerda-direita if sign==1: Qr, yR = Qvector(y,QR,sign) else: Ql, yL = Qvector(y,QL,sign) #return drawParallel(ray,q0,sign) print 'Ql -',array(list(reversed(Ql))).shape,', Qr -',array(Qr[1:]).shape if Ql and Qr[1:]: Q=concatenate((list(reversed(Ql)),Qr[1:])) elif Ql: Q=Ql else: Q=Qr return yR, yL, Q
def curvepoint(p0): tol = 1e-4 while True: df1 = RBF.df(p0) f1 = RBF.f(p0) df2 = array([2 * p0[0], 2 * p0[1], 2 * p0[2]]) f2 = p0[0] ** 2 + p0[1] ** 2 + p0[2] ** 2 - Rn ** 2 df1df2 = dot(df1, df2) df1df1 = dot(df1, df1) df2df2 = dot(df2, df2) beta = (-f1 + f2 * df1df1 / df1df2) / (df1df2 - df1df1 * df2df2 / df1df2) alpha = (-f1 + f2 * df1df2 / df2df2) / (df1df1 - df1df2 * df1df2 / df2df2) dk = alpha * df1 + beta * df2 # print 'preso= ', sqrt(dot(dk,dk)) p1 = p0 + dk if sqrt(dot(dk, dk)) < tol: return p1 else: p0 = p1
def fit_predict_frame_pixel(y, x, running_index, training_data, test_data, generate_new): ind_y, ind_x = y, x min_border_distance = np.min([y, x, N-1-y, N-1-x]) training_data_in = training_data[1][:, y - min_border_distance:y + min_border_distance+1, x - min_border_distance:x + min_border_distance+1].reshape(-1, int((2*min_border_distance+1)**2)) training_data_out = training_data[0][:, y, x].reshape(-1, 1) test_data_in = test_data[1][:, y - min_border_distance:y + min_border_distance+1, x - min_border_distance:x + min_border_distance+1].reshape(-1, int((2*min_border_distance+1)**2)) test_data_out = test_data[0][:, y, x].reshape(-1, 1) rbf = RBF(sigma=5.0) rbf.fit(training_data_in, training_data_out, basisQuota=0.02) pred = rbf.predict(test_data_in) pred = pred.ravel() pred[pred>1.0] = 1.0 pred[pred<0.0] = 0.0 return pred
def tangent(ray,sign): P=ray x=P[0];y=P[1];z=P[2] dv = array(RBF.df([x,y,z])) n = dv/sqrt(dot(dv,dv)) P=concatenate((P,n)) tan = cross(n,[x,y,z]) a = tan/sqrt(dot(tan,tan)) return a
def FindNextParallel(P0,sign): global Rn d = sqrt(P0[0]**2+P0[1]**2+P0[2]**2) R0=1.425 n = math.ceil((d-R0)/0.003) Rn = R0+n*0.003 y = curvepoint(P0) norm = RBF.df([y[0],y[1],y[2]]) norm /= sqrt(dot(norm,norm)) y = array([y[0],y[1],y[2],norm[0],norm[1],norm[2]]) return y
def tangentd(ray,sign): P=ray x=P[0];y=P[1];z=P[2] dv = array(RBF.df([x,y,z])) n = dv/sqrt(dot(dv,dv)) P=concatenate((P,n)) tan = cross(n,[x,y,z]) a = tan/sqrt(dot(tan,tan)) tand = sign*cross(a,n) return tand
def determin_model(stock_name, scaler, X_train, X_test, y_train, epochs=50, path=""): # path of the old model print("RNN Training ...") regressor = RNN.train(X_train, y_train, epochs=epochs) print("save Trained model ...") RNN.save_model(stock_name, regressor, path=path) model_path = path + "{}-RNN.h5".format(stock_name) _, rnn_mape = RNN.test(model_path, scaler, X_test) print("RBF Training ...") regressor = RBF.train(X_train, y_train, epochs=epochs) print("save Trained model ...") RBF.save_model(stock_name, regressor, path=path) model_path = path + "{}-RBF.h5".format(stock_name) _, rbf_mape = RBF.test(model_path, scaler, X_test) print("BKP Training ...") regressor = BKP.train(X_train, y_train, epochs=epochs) print("save Trained model ...") BKP.save_model(stock_name, regressor, path=path) model_path = path + "{}-BKP.h5".format(stock_name) _, bkp_mape = BKP.test(model_path, scaler, X_test) print("RNN: " + str(rnn_mape)) print("RBF: " + str(rbf_mape)) print("BKP: " + str(bkp_mape)) if rnn_mape < rbf_mape and rnn_mape < bkp_mape: return "RNN" elif rbf_mape < rnn_mape and rbf_mape < bkp_mape: return "RBF" else: return "BKP"
def drawParallel(ray): global handles y = [ray] while True: tan = tangent(y[-1]) #print 'tan= ', tan[0],tan[1],tan[2] p1 = curvepoint(y[-1][0:3]-tan*dt) dv = array(RBF.df(p1)) normdv = sqrt(dot(dv,dv)) n = dv/normdv P=concatenate((p1,n)) y.append(P) handles=plotPoint(P, handles,array((0,1,0))) return y
def drawParallel(ray): global handles y = [ray] while True: tan = tangent(y[-1]) # print 'tan= ', tan[0],tan[1],tan[2] p1 = curvepoint(y[-1][0:3] - tan * dt) dv = array(RBF.df(p1)) normdv = sqrt(dot(dv, dv)) n = dv / normdv P = concatenate((p1, n)) y.append(P) handles = plotPoint(P, handles, array((0, 1, 0))) return y
def drawParallel(ray,q0,sign): viable=isViable(q0,ray[3:6]) Ql=[]; yL=[]; Qr=[]; yR=[] if viable: print 'drawParallel: is viable' QL=[q0] QR=[q0] y=[ray] #Arriscado - Pode caminhar em duas funcoes esquerda-direita if sign==1: Qr, yR = Qvector(y,QR,sign) #print 'sign 1: Qr -',array(Qr).shape,', yR -',array(yR).shape y=[ray] sign*=-1 Ql, yL = Qvector(y,QL,sign) #print 'sign -1: Ql -',array(Ql).shape,', yL -',array(yL).shape else: Ql, yL = Qvector(y,QL,sign) y=[ray] sign*=-1 Qr, yR = Qvector(y,QR,sign) else: sign*=-1 print 'drawParallel: solution not found' while not viable: y=ray[0:3] tan, q0, viable = tangentOptm(ray,q0) y=curvepoint(y+sign*tan*dt) norm = RBF.df([y[0],y[1],y[2]]) norm /= sqrt(dot(norm,norm)) ray = array([y[0],y[1],y[2],norm[0],norm[1],norm[2]]) print 'drawParallel: solution found' QL=[q0] QR=[q0] y=[ray] #Arriscado - Pode caminhar em duas funcoes esquerda-direita if sign==1: Qr, yR = Qvector(y,QR,sign) else: Ql, yL = Qvector(y,QL,sign) #return drawParallel(ray,q0,sign) print 'Ql -',array(list(reversed(Ql))).shape,', Qr -',array(Qr[1:]).shape if Ql and Qr[1:]: Q=concatenate((list(reversed(Ql)),Qr[1:])) elif Ql: Q=Ql else: Q=Qr return yR, yL, Q
def meridian2(P0,sign,q0): print 'meridian2' Q=[q0] P0=array([P0[0],P0[1],P0[2]]) y = curvepoint(P0) norm = RBF.df(y) norm /= sqrt(dot(norm,norm)) ray = array([y[0],y[1],y[2],norm[0],norm[1],norm[2]]) resQ = coating.optmizeQ(robot,ikmodel,manip,ray,Q[-1]) if resQ.success: Q.append(resQ.x) else: print 'Meridian Error' return ray, Q
def Qvector(y,Q,sign): global handles suc=True while suc: tan, q, suc = tangentOptm(y[-1],Q[-1]) if not coating.CheckDOFLimits(robot,q): #wait = input("deu bode, PRESS 1 ENTER TO CONTINUE.") iksolList = fullSolution(y[-1]) Q=[iksolList[0][0]] Q = Qvector_backtrack(y,Q) continue if suc: Q.append(q) p1 = curvepoint(y[-1][0:3]+sign*tan*dt) dv = array(RBF.df(p1)) normdv = sqrt(dot(dv,dv)) #print 'success:', res.success, ' fn:', polynomial_spline.fn4(xnew[0],xnew[1],xnew[2])/normdv n = dv/normdv P=concatenate((p1,n)) y.append(P) handles=plotPoint(P, handles,array((0,1,0))) return Q,y
def tangent(ray,sign): x=ray[0];y=ray[1];z=ray[2] dv = array(RBF.df([x,y,z])) n = dv/sqrt(dot(dv,dv)) tan = cross(n,[x,y,z]) return tan/sqrt(dot(tan,tan))
import RBF best = ES.find_circle_coordinates(MU=10, LAMBDA=100, evaluator=RBF.multiclass_evaluator, loss=RBF.multiclass_classification_loss, NGEN=10, x_train=x, y_train=y, number_of_circles=number_of_circles, MIN_VALUE=-1.5, MAX_VALUE=1.5, MIN_STRATEGY=0.5, MAX_STRATEGY=9) print("best", best) print( "train", RBF.multiclass_evaluator(RBF.multiclass_classification_loss, x, y, x, y, best)) save_obj(np.array(best), "IND_MULCLS") save_obj(RBF.get_W_multi(x, y, best, number_of_circles), "W_MULCLS") ans = RBF.get_y_multi_classification(best, x, y, x) import matplotlib.pyplot as plt plots.draw_circles(dim, number_of_circles, best) print("ans", ans) plots.plot_classification_data(x, ans, [0, 1, 2, 3, 4])
[ -1.51211605e+00, -3.22000000e+00, 3.34232687e-01], [ -1.35417734e+00, -3.22000000e+00, 6.67255206e-01], [ -1.19623863e+00, -3.22000000e+00, 1.00027773e+00]]) pN=gbase_position[4] normal = [-1,0,0] pN = concatenate((pN,normal)) QList = [] dt = 3e-3 # parallel step loops = 20 loopdistance = 1 #==================================================================================================================== # DIREITA E PARA BAIXO = 1 rR = RBF.rays Tree = RBF.makeTree(rR) Rn = 0 manipulabilityNUM = 0 globalManipPos = [] globalManipOri = [] def tangentOptm(ray,q0): tan = cross(ray[3:6],ray[0:3]) tan = tan/sqrt(dot(tan,tan)) res = coating.optmizeQ(robot,ikmodel,manip,ray,q0) angle_suc = isViable(res.x,ray[3:6]) return tan, res.x, (res.success and angle_suc) def solution(ray):
for i in range(num_trials): # print("Building training array") dataHandler = trainingArray.trainingArray(num_inputs, num_examples) data = dataHandler.createTrainingData() split = int((len(data) / 3) * 2) training_data = data[:split] testing_data = data[split:] training_inputs = [example.inputs for example in training_data] # print("Computing kmeans") centroids = Kmeans.kMeans(gauss, training_inputs, num_inputs).calculateKMeans() net_layers = get_rbf_layers(num_inputs, gauss, num_outputs) # print("Centroids computed!\n") # net = MLP.network([1, 35, 35, 1], "sigmoid") net = RBF.network(net_layers, "gaussian", centroids) # print("Training Network:") train_rbf(net, training_data, learning_rate, num_iterations) result = test_network(net, testing_data) total += result print(result) # print("\n") print("Average: %f" % (total / num_trials))
def get_data(): if sys.platform[:3] =='win': data_loc = 'D:/Data/Loyalty Vision/' else: data_loc = "/home/tom/data/" filenm = "rbf_data.csv" return(pd.read_csv(data_loc+filenm, delimiter=',')) if __name__ == "__main__": parms = [[a,b,c,d] for a in sigma for b in clusters for c in nodes for d in test] out = open('/home/tom/data/rbf_results.csv', 'w') rec = '{}{}{}{}{}{}{}'.format('Sigma,','Cluster,','Nodes,','TestPct,','RMSE,','Time,','\n') out.write(rec) df = get_data() sigma=2. cluster='random' nodes=8 t0 = time.time() for x in parms: start = time.time() for y in range(loops): rmse = RBF.process(df, x) # Pass the data and the parameters end = time.time() rec = str(x[0])+','+x[1]+','+str(x[2])+','+str(x[3])+','+str(rmse)+','+str(end-start)+'\n' out.write(rec) t1 = time.time() print('all done, elapsed time: {:.1f} minutes'.format((t1-t0)/60)) os.system("aplay /usr/share/sounds/bicycle_bell.wav")
points = np.array([ random.uniform(0.000001, 0.2), random.uniform(0.000001, 0.2), random.uniform(0.000001, 0.2) ]) values = np.array([]) for i in range(0, points.size): values = np.append(values, evaluate(points[i], x_train, y_train, x_test, y_test)) print("Learning rate: ", points) print("Loss value: ", values) plot = np.copy(np.log10(points)) for i in range(1, numberOfIterations + 1): rbf = r.RBF(points, values) rbf.interpolate() if i % 3 == 0: newx = rbf.newxGivenf(True) else: newx = rbf.newxGivenf() # find the new learning rate points = np.append(points, np.power(10, newx)) print("new learning rate: ", np.power(10, newx)) plot = np.append(plot, newx) # evauate the model with the new learning rate newf = evaluate(np.power(10, -newx), x_train, y_train, x_test, y_test) values = np.append(values, newf) rbf = r.RBF(points, values) rbf.interpolate()
[-1.51211605e+00, -3.22000000e+00, 3.34232687e-01], [-1.35417734e+00, -3.22000000e+00, 6.67255206e-01], [-1.19623863e+00, -3.22000000e+00, 1.00027773e+00]]) pN = gbase_position[4] normal = [-1, 0, 0] pN = concatenate((pN, normal)) QList = [] dt = 1e-3 # parallel step loops = 6 loopdistance = 1 #==================================================================================================================== # DIREITA E PARA BAIXO = 1 rR = RBF.rays Tree = RBF.makeTree(rR) manipulabilityNUM = 0 globalManipPos = [] globalManipOri = [] def tangentOptm(ray, q0): global manipulabilityNUM global globalManipPos global globalManipOri tan = cross(ray[3:6], ray[0:3]) tan *= 1.0 / sqrt(dot(tan, tan)) res = coating.optmizeQ(robot, ikmodel, manip, ray, q0) angle_suc = isViable(res.x, ray[3:6])