def adaBoostTrainDS(dataArr, classLabels, numInt=40): weakClassArr = [] m = dataArr.shape[0] D = np.zeros((m, 1)) #D在迭代过程中需要优化的 aggClassEnt = np.mat(np.zeros((m, 1))) for i in range(numInt): bestStump, error, classEst = bulidStump(dataArr, classLabels, D) print("D:", D.T) # 为什么是max(error,1e-16) alpha = float(0.5 * math.log((1.0 - error) / max(error, 1e-16))) bestStump['alpha'] = alpha # 弱学习器添加 weakClassArr.append(bestStump) # 预测分类 print("classEst: ", classEst.T) expon = np.multiply(-1 * alpha * np.mat(classLabels).T, classEst) D = np.multiply(D, math.exp(expon)) D = D / D.sum() aggClassEnt += alpha * classEst print("aggClassEst : ", aggClassEnt.T) # 累加的当前弱分类器的错误率 aggErrors = np.multiply( math.sign(aggClassEnt) != np.mat(classLabels).T, np.ones((m, 1))) errorRate = aggErrors.sum() / m print("total error: ", errorRate) if errorRate == 0.0: break # python浮点数的比较? return weakClassArr
def main(): minDist = 4.0 # Minimal distance to maintain between mouse and cat height = 2.5 # The height for the flying cat with Morse() as simu: while True: catPosition = get_agent_position(simu.r2.pose2) mousePosition = get_agent_position(simu.r1.pose1) if mousePosition and catPosition: # go behind the mouse waypoint = { "x": mousePosition['x'] - minDist*math.cos(mousePosition['yaw']),\ "y": mousePosition['y'] - minDist*math.sin(mousePosition['yaw']),\ "z": height, \ "yaw": catPosition['yaw'], \ "tolerance": 0.5 } # look at the mouse if mousePosition['x']==catPosition['x']: waypoint['yaw']=math.sign(mousePosition['y']-catPosition['y'])*math.pi else: waypoint['yaw']=math.atan2(mousePosition['y']-catPosition['y'], mousePosition['x']-catPosition['x']) # send command through the socket simu.r2.waypoint.publish(waypoint)
def frighten_mouse(): """ Use the mouse pose sensor to locate and "chase" it """ with Morse() as morse: catPose = morse.cat.catPose mousePose = morse.mouse.mousePose motion = morse.cat.waypoint while True: catPosition = where_is(catPose) mousePosition = where_is(mousePose) if mousePosition and catPosition: # go behind the mouse waypoint = { "x": mousePosition["x"] - minDist * math.cos(mousePosition["yaw"]), "y": mousePosition["y"] - minDist * math.sin(mousePosition["yaw"]), "z": height, "yaw": catPosition["yaw"], "tolerance": 0.5, } # look at the mouse if mousePosition["x"] == catPosition["x"]: waypoint["yaw"] = math.sign(mousePosition["y"] - catPosition["y"]) * math.pi else: waypoint["yaw"] = math.atan2( mousePosition["y"] - catPosition["y"], mousePosition["x"] - catPosition["x"] ) # send the command through the socket motion.publish(waypoint)
def frighten_mouse(): """ Use the mouse pose sensor to locate and "chase" it """ with Morse() as morse: catPose = morse.cat.catPose mousePose = morse.mouse.mousePose motion = morse.cat.waypoint while True: catPosition = where_is(catPose) mousePosition = where_is(mousePose) if mousePosition and catPosition: # go behind the mouse waypoint = { "x": mousePosition['x'] - minDist*math.cos(mousePosition['yaw']), \ "y": mousePosition['y'] - minDist*math.sin(mousePosition['yaw']), \ "z": height, \ "yaw": catPosition['yaw'], \ "tolerance": 0.5 \ } # look at the mouse if mousePosition['x']==catPosition['x']: waypoint['yaw']= math.sign(mousePosition['y']-catPosition['y']) * math.pi else: waypoint['yaw']= math.atan2(mousePosition['y']-catPosition['y'],mousePosition['x']-catPosition['x']) # send the command through the socket motion.publish(waypoint)
def perceptronR(x_y, w, lr): x, y = x_y[0], x_y[1] ynext = dot(x, w) if sign(1, ynext) != y or ynext == 0: for i in range(len(w)): w[i] = w[i] + lr*y*x[i] perceptronR(x_y, w, lr)
def update(self): """ move the bullet forward, return its position for collision and bound checking """ xMove = 0 if self.homing and self.father != None: xMove = sign(self.speed/5, self.father.centerx - self.rect.centerx) self.move(xMove, self.speed * self.moveDir) return self.rect.y
def mape(preds, train): gaps = train[:, -1] grad = [] hess = [] for index, gap in enumerate(gaps): if gap == 0: grad.append(0) hess.append(0) else: grad.append(math.sign(preds[index] - gap)) hess = abs(preds[index] - gap)/10 return grad, hess
def frighten_mouse(): """ Use the mouse pose sensor to locate and "chase" it """ with pymorse.Morse() as simu, Morse() as morse: catPose = morse.cat.catPose mousePose = morse.mouse.mousePose motion = morse.cat.waypoint bat = morse.cat.cat_battery bat_lev = battery_life(bat) is_free = True while (bat_lev > 50 and is_free == True): catPosition = where_is(catPose) mousePosition = where_is(mousePose) if mousePosition and catPosition: # go behind the mouse waypoint = { "x": mousePosition['x'] - minDist*math.cos(mousePosition['yaw']), \ "y": mousePosition['y'] - minDist*math.sin(mousePosition['yaw']), \ "z": height, \ "yaw": catPosition['yaw'], \ "tolerance": 0.5 \ } # look at the mouse if((catPosition['y'] - mousePosition['y']) < 1 and (catPosition['x'] - mousePosition['x']) < 1 and is_hiding(mousePosition) = False): is_free = False print("CAPTURE") #print("%s" % is_free) elif mousePosition['x']==catPosition['x']: waypoint['yaw']= math.sign(mousePosition['y']-catPosition['y']) * math.pi else: waypoint['yaw']= math.atan2(mousePosition['y']-catPosition['y'],mousePosition['x']-catPosition['x']) # send the command through the socket motion.publish(waypoint) cnt = 0 while True: cnt+1
def running(screenpos, scale, fcycle): x, y = screenpos C, S = math.CS(fcycle * math.tau) C2, S2 = math.CS(2 * fcycle * math.tau) # Arms and legs don't quite follow a sinusoidal pattern. They spend extra time at the extrema. # This gives them a more natural swing. fC = abs(C)**0.7 * math.sign(C) # foots x0, y0 = x - 1 * scale, y - 1 * scale dx = 1.3 * fC dy = 0.4 * S + 0.2 * C drawfoot((x0 + dx * scale, y0 + dy * scale), scale) drawfoot((x0 - dx * scale, y0 - dy * scale), scale) # back fist x0 = x + 0.2 * scale y0 = y + (-2.9 - 0.2 * S2) * scale dx, dy = 1.6 * fC, 0.4 * abs(S) drawfoot((x0 - dx * scale, y0 + dy * scale), scale) # dress x0, y0 = x - 0.3 * scale, y - (1.7 + 0.2 * S2) * scale path = [(-2.5, 0), (-0.5, -0.5), (1.5, -0.8), (1.5, 1), (2, 3), (1, 3.2), (-0.7, 1.5)] ps = [(i(x0 + scale * dx), i(y0 - scale * dy)) for dx, dy in path] pygame.draw.polygon(pview.screen, (0, 0, 0), ps, i(0.6 * scale)) pygame.draw.polygon(pview.screen, (100, 100, 250), ps, 0) # front fist x0 = x + 0.2 * scale y0 = y + (-2.9 - 0.2 * S2) * scale dx, dy = 1.6 * fC, 0.4 * abs(S) drawfoot((x0 + dx * scale, y0 + dy * scale), scale) # noggin Snoggin = math.sin(2 * fcycle * math.tau - 0.6) x0, y0 = x + 1.1 * scale, y - (5 + 0.2 * Snoggin) * scale drawnoggin((x0, y0), scale, angle=0.2 + 0.1 * Snoggin) if settings.DEBUG: pygame.draw.circle(pview.screen, (255, 0, 255), screenpos, i(0.3 * scale))
def other_reverse_invert(lst): """Best practice solution from codewars.""" from math import copysign as sign return [-int(sign(int(str(abs(x))[::-1]), x)) for x in lst if isinstance(x, int)]
def signstr(num): if math.sign(num.real) == -1: return '-' else: return '+'
def trayectoria(puntos, tiempoEP): pos = 0 pos1 = 0 vel1 = 0 acel1 = 0 posTot = 0 #Defino parametros del ejercicio theta = puntos t = tiempoEP #tiempo entre segmentos #Establezco parametros de tiempo y vectores para almacenar los valores: paso = 0.025 N = t / paso #puntos por segmento tiempo = arange(1, (len(theta) - 1) * N, paso) #tiempo total th = t / 2 for k in range(1, len(theta) - 1): theta_pp = 100 tb = t / 2 - math.sqrt(theta_pp**2 * t**2 - 4 * theta_pp * abs(theta[k + 1] - theta[k])) / (2 * theta_pp) #tb_1=tb; theta_h = (theta[k + 1] + theta[k]) / 2 theta_b = theta[k] + 1 / 2 * math.sign(theta[k + 1] - theta[k]) * theta_pp * tb**2 i = 0 r = 0 for i in range(1, math.floor(tb / paso)): pos1[i] = theta[k] + 1 / 2 * math.sign(theta[k + 1] - theta[k]) * theta_pp * r**2 vel1[i] = theta_pp * r acel1[i] = theta_pp r = r + paso r = 0 for i in range(math.floor(tb / paso + 1), math.floor(N - tb / paso)): r = r + paso pos1[i] = (theta_h - theta_b) / (th - tb) * r + pos1[math.floor( tb / paso)] vel1[i] = (theta_h - theta_b) / (th - tb) acel1[i] = 0 r = tb for i in range(math.floor((N - tb / paso) + 1), N): pos1[i] = theta[k + 1] - 1 / 2 * math.sign( theta[k + 1] - theta[k]) * theta_pp * (r)**2 #invertir el orden de r vel1[i] = theta_pp * r #signo invertido porque el calculo se realiza a la inversa acel1[i] = -theta_pp r = r - paso pos[k, :] = pos1 #almaceno cada segmento en filas posTot = pos[0, :] # Loop para realinear las filas con segmentos en una función continua for h in range(1, len(theta) - 1): l = len(posTot) #variable auxiliar for m in range(1, len[pos]): posTot[l + m] = pos[h, m] #figure(1) plt.plot(tiempo, posTot) #plot(tiempo,round(posTot),'r'); #ylim([(min(posTot)-5), (max(posTot)+5)]) return posTot
stop_condition = 100 while (stop_condition != 0 or err != 0): prev_error = error for j in range(0, cols): d[j] = 1 for i in range(0, rows): #print i delta = dot(d, data[i]) if (delta != 0): ####CREATE THE NEW DATA AND APPEND IT TO DATA_PRIME AND LABEL_PRIME data_prim.append(dot(W, data[i])) label_prim.append(int(sign(float(labelset[i]), delta))) #print data_prim #print label_prim alpha = find_alpha(data_prim, label_prim) error = 0 ### CHANGE W AND COMPUTE ERROR for k in range(cols): w_new[k] = W[k] + alpha * d[k] wtx = 0.0 sign_array = array('i') for i in range(rows + 1): wtx = dot(w_new, data[i]) if (wtx > 0.0):
def classify(image): positives = [] summation = 0 for weak in self.classifiers: summation += weak.hypothesis(image) return math.sign(summation)
def checkIntersect(self, l1p1, l1p2, l2p1, l2p2): checkDir = lambda pt1, pt2, pt3: math.sign(((pt2[0]-pt1[0])*(pt3[1]-pt1[1])) - ((pt3[0]-pt1[0])*(pt2[1]-pt1[1]))) return (checkDir(l1p1,l1p2,l2p1) != checkDir(l1p1,l1p2,l2p2)) and (checkDir(l2p1,l2p2,l1p1) != checkDir(l2p1,l2p2,l1p2))
def sign(x): """Get the sign of x, with x a float scalar or vector. The result is 1.0 if x > 0, -1 if x < 0, and 0.0 otherwise. If x is NaN, the result can be any of the former. """ return math.sign(x)
def pos2log(value): if (abs(value) > 0.5): value = math.sign(value) * 0.5 return ((math.pow(10, value) - 1) / 9)
def classify(x_y, w): for x, y in x_y: if sign(1, dot(x, w)) != y: return False return True
def signe(number): return (math.sign(number))