Пример #1
0
def swap_columns():
    global field
    temp = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    rand1 = ramdom(0, 2)
    rand2 = ramdom(0, 2)
    if rand1 == 0:
        if rand2 == 0:
            for i in range(9):
                temp[i] = field[i][0]
                field[i][0] = field[i][1]
                field[i][1] = temp[i]
        if rand2 == 1:
            for i in range(9):
                temp[i] = field[i][1]
                field[i][1] = field[i][2]
                field[i][2] = temp[i]
        if rand2 == 2:
            for i in range(9):
                temp[i] = field[i][2]
                field[i][2] = field[i][0]
                field[i][0] = temp[i]
    if rand1 == 1:
        if rand2 == 0:
            for i in range(9):
                temp[i] = field[i][3]
                field[i][3] = field[i][4]
                field[i][4] = temp[i]
        if rand2 == 1:
            for i in range(9):
                temp[i] = field[i][4]
                field[i][4] = field[i][5]
                field[i][5] = temp[i]
        if rand2 == 2:
            for i in range(9):
                temp[i] = field[i][5]
                field[i][5] = field[i][3]
                field[i][3] = temp[i]
    if rand1 == 2:
        if rand2 == 0:
            for i in range(9):
                temp[i] = field[i][6]
                field[i][6] = field[i][7]
                field[i][7] = temp[i]
        if rand2 == 1:
            for i in range(9):
                temp[i] = field[i][7]
                field[i][7] = field[i][8]
                field[i][8] = temp[i]
        if rand2 == 2:
            for i in range(9):
                temp[i] = field[i][8]
                field[i][8] = field[i][6]
                field[i][6] = temp[i]
Пример #2
0
def swap_rows():
    global field
    temp = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    rand1 = ramdom(0, 2)
    rand2 = ramdom(0, 2)
    if rand1 == 0:
        if rand2 == 0:
            for i in range(9):
                temp = field[0]
                field[0] = field[1]
                field[1] = temp
        if rand2 == 1:
            for i in range(9):
                temp = field[1]
                field[1] = field[2]
                field[2] = temp
        if rand2 == 2:
            for i in range(9):
                temp = field[2]
                field[2] = field[0]
                field[0] = temp
    if rand1 == 1:
        if rand2 == 0:
            for i in range(9):
                temp = field[3]
                field[3] = field[4]
                field[4] = temp
        if rand2 == 1:
            for i in range(9):
                temp = field[4]
                field[4] = field[5]
                field[5] = temp
        if rand2 == 2:
            for i in range(9):
                temp = field[5]
                field[5] = field[3]
                field[3] = temp
    if rand1 == 2:
        if rand2 == 0:
            for i in range(9):
                temp = field[6]
                field[6] = field[7]
                field[7] = temp
        if rand2 == 1:
            for i in range(9):
                temp = field[7]
                field[7] = field[8]
                field[8] = temp
        if rand2 == 2:
            for i in range(9):
                temp = field[8]
                field[8] = field[6]
                field[6] = temp
Пример #3
0
def move(cube,rows,cols,size):
    new_cube = np.zeros((rows * cols, size, size))
    move_percent = 0.2 # 左右平移最多移动20% 上下移动最多平移20%
    delta_x = random.ramdom() * move_percent * rows
    delta_y = random.ramdom() * move_percent * cols
    move_right =  1 if ramdom.random() > 0.5 else 0
    move_down = 1 if ramdom.random() > 0.5 else 0
    
    M = np.float32([
        [move_right, 1-move_right, delta_x],  # x轴方向上的平移
        [1-move_down, move_down, delta_y]   # y轴方向上的平移
        ])
    for i in range(len(cube)):
        img = cube[i]
        new_img = cv2.warpAffine(img,M,(size,size))
        new_cube[i] = new_img 
    return new_cube
Пример #4
0
	def rollCheatDice(self, cheatValue):
		roll = random.ramdom()
		if roll < 0.5:
			return cheatValue
		elif roll < 0.7:
			return self.rollDice()
		elif roll < 0.85:
			return min(self.rollDice()*2, 6)
		else:
			self.Mute()
			return cheatValue
Пример #5
0
def swap_big_rows():
    global field
    rand1 = ramdom(0, 2)
    temp = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0]]
    if rand1 == 0:
        for i in range(0, 3):
            temp[i] = field[i].copy()
            field[i] = field[i + 3].copy()
            field[i + 3] = temp[i]
    if rand1 == 1:
        for i in range(0, 3):
            temp[i] = field[i].copy()
            field[i] = field[i + 6].copy()
            field[i + 6] = temp[i]
    if rand1 == 2:
        for i in range(0, 3):
            temp[i] = field[i + 3].copy()
            field[i + 3] = field[i + 6].copy()
            field[i + 6] = temp[i]
Пример #6
0
    def get_data(self,
                 img_path,
                 label_path,
                 augment,
                 rand_sv_S=None,
                 rand_sv_V=None,
                 rand_lr_flip=None,
                 rand_a=None,
                 rand_s=None,
                 rand_t02=None,
                 rand_t12=None,
                 rand_sh01=None,
                 rand_sh10=None):
        height = self.height
        width = self.width
        img = cv2.imread(img_path)  # BGR
        if img is None:
            raise ValueError('File corrupt {}'.format(img_path))
        augment_hsv = True
        if augment and augment_hsv:
            # SV augmentation by 50%
            fraction = 0.50
            img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            S = img_hsv[:, :, 1].astype(np.float32)
            V = img_hsv[:, :, 2].astype(np.float32)

            if rand_sv_S is None:
                a = (random.random() * 2 - 1) * fraction + 1
            else:
                a = (rand_sv_S * 2 - 1) * fraction + 1
            S *= a
            if a > 1:
                np.clip(S, a_min=0, a_max=255, out=S)

            if rand_sv_V is None:
                a = (random.random() * 2 - 1) * fraction + 1
            else:
                a = (rand_sv_V * 2 - 1) * fraction + 1
            V *= a
            if a > 1:
                np.clip(V, a_min=0, a_max=255, out=V)

            img_hsv[:, :, 1] = S.astype(np.uint8)
            img_hsv[:, :, 2] = V.astype(np.uint8)
            cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)

        h, w, _ = img.shape
        img, ratio, padw, padh = letterbox(img, height=height, width=width)

        # Load labels
        if os.path.isfile(label_path):
            labels0 = np.loadtxt(label_path, dtype=np.float32).reshape(-1, 6)

            # Normalized xywh to pixel xyxy format
            labels = labels0.copy()
            labels[:,
                   2] = ratio * w * (labels0[:, 2] - labels0[:, 4] / 2) + padw
            labels[:,
                   3] = ratio * h * (labels0[:, 3] - labels0[:, 5] / 2) + padh
            labels[:,
                   4] = ratio * w * (labels0[:, 2] + labels0[:, 4] / 2) + padw
            labels[:,
                   5] = ratio * h * (labels0[:, 3] + labels0[:, 5] / 2) + padh
        else:
            labels = np.array([])

        # Augment image and labels
        if augment:
            img, labels, M = random_affine(img,
                                           labels,
                                           degrees=(-5, 5),
                                           translate=(0.10, 0.10),
                                           scale=(0.50, 1.20),
                                           rand_a=rand_a,
                                           rand_s=rand_s,
                                           rand_t02=rand_t02,
                                           rand_t12=rand_t12,
                                           rand_sh01=rand_sh01,
                                           rand_sh10=rand_sh10)

        plotFlag = False
        if plotFlag:
            import matplotlib
            matplotlib.use('Agg')
            import matplotlib.pyplot as plt
            plt.figure(figsize=(50, 50))
            plt.imshow(img[:, :, ::-1])
            plt.plot(labels[:, [2, 4, 4, 2, 2]].T,
                     labels[:, [3, 3, 5, 5, 3]].T, '.-')
            plt.axis('off')
            plt.savefig('test.jpg')
            time.sleep(10)

        nL = len(labels)
        if nL > 0:
            # convert xyxy to xywh (center_x, center_y, width, height)
            labels[:, 2:6] = xyxy2xywh(labels[:, 2:6].copy())  # / height
            labels[:, 2] /= width
            labels[:, 3] /= height
            labels[:, 4] /= width
            labels[:, 5] /= height
        if augment:
            # random left-right flip
            lr_flip = True
            if rand_lr_flip is None:
                lr_flip_prob = random.ramdom()
            else:
                lr_flip_prob = rand_lr_flip
            if lr_flip & (lr_flip_prob > 0.5):
                img = np.fliplr(img)
                if nL > 0:
                    labels[:, 2] = 1 - labels[:, 2]

        img = np.ascontiguousarray(img[:, :, ::-1])  # BGR to RGB
        if self.transforms is not None:
            img = self.transforms(img)

        return img, labels, img_path, (h, w)
Пример #7
0
def long_time_task(name):
	print('Run task %s (%s)...'%(name, os.getpid()))
	start = time.time()#得到当时的时间戳
	time.sleep(random.ramdom() * 3)
	end = time.time()
	print('Task %s runs %0.2f seconds.'%(name,(end-start)))
Пример #8
0
def write(p):
	for val in ['A','B','C']:
		print 'Put %s to Queue...' % val
		p.put(val)
		time.sleep(random.ramdom())
Пример #9
0
 def __init__(self, nu):
     super(, self).__init__()
     self.nu = nu
     self.theta = 2*pi*random.random()
     self.phi = 2*pi*random.ramdom()
Пример #10
0
def pso(treino, teste):
    # ===============
    # Passo 1: Iniciar as variaveis do enxame de particulas. Onde:
    enxame = object.__new__(Enxame)

    minneuro = 2
    maxneuro = 15
    numparticulas = 10
    parametros = list(range(4))

    parametros[0] = 9
    parametros[3] = 1

    enxame.init(numparticulas, minneuro, maxneuro)
    #enxame.init(10,2,15)
    #dentro de cada posicao do vetor, sera criado uma particula
    for i in range(0, len(enxame.vetParticulas)):
        enxame.vetParticulas[i] = object.__new__(Particula)
        enxame.vetParticulas[i].Particula.init(2)

# - Inicializar os valores das particulas (i = particula, j = elemento da particula):
# - a velocidade da particula:- V[i][j] = ((j_max - j_min) * <sorteio de um valor aleatorio>) - X[i][j],para toda particula;
    for i in range(0, len(enxame.vetParticulas)):
        for j in range(0, len(enxame.vetParticulas[i])):
            enxame.vetParticulas[i].x[j] = random.randrange(minneuro, maxneuro)
            enxame.vetParticulas[i].speed[j] = (
                (maxneuro - minneuro) *
                random.ramdom()) - enxame.vetParticulas[i].x[j]

# - Definir outras variavies:
    for i in range(0, len(enxame.vetParticulas[i].pBest)):
        enxame.vetParticulas[i].pBest[i] = 0

    enxame.vetParticulas[i].pBestFun = 0
    enxame.gBest = 0
    enxame.melhorRede = inicializaRede(parametros, 9)
    enxame.melhorRede.erroFinal.quadratico = 100
    #- Gbestfun (inicialmente 0) representa o valor da funcao objetivo da melhor particula; ( vou guardar a melhor rede que ja tem o erro)

    #- N eh o tamanho do enxame (numero de particulas);
    w = 1 / (2 * math.log(2, 10))  #ponderacao da inehrcia;
    c_1 = 0.5 + math.log(2, 10)  #representa o parametro cognitivo;
    c_2 = c_1  #representa o parametro social.
    # ===============
    # Passo 2: Calcular o valor da funcao-objetivo f(X) para todas as particulas.
    for i in range(0, len(enxame.vetParticulas)):
        parametros[1] = enxame.vetParticulas[i].x[0]
        parametros[2] = enxame.vetParticulas[i].x[1]

        rede = rede = inicializaRede(parametros, 9)
        rede = LM(rede, treino, teste)
        for j in range(0, len(enxame.vetParticulas[i].pBest)):
            #- O vetor Pbest[i] recebe a posicao atual de cada particula;
            enxame.vetParticulas[i].pBest[j] = enxame.vetParticulas[i].x[j]
            #- O vetor Pbestfun[i] recebe o valor da funcao-objetivo da particula;
        enxame.vetParticulas[i].pBestFun = rede.erroFinal.quadratico
        #- Gbest recebe a posicao da melhor particula do enxame;
        #- Gbestfun recebe a funcao-objetivo da melhor particula do enxame.
        if (enxame.melhorRede.erroFinal.quadratico >
                rede.erroFinal.quadratico):
            gBest = i
            enxame.melhorRede = bkpRede(rede)
# ===============
# Passo 3: Atualizar as posicoes e velocidades das particulas de acordo com asequacoes a seguir:
# ===============
# Passo 4: Calcular o valor da funcao-objetivo f(X) para todas as particulas considerando a quantidade de neuronios na camada escondida.
# ===============
# Passo 5: Para cada particula, comparar o valor da funcao-objetivo atual com o
#valor de Pbest[i]. Caso o atual seja melhor, Pbest[i] recebe a posicao atual e
#Pbestfun[i] recebe o valor da funcao-objetivo atual.
# ===============
# Passo 6: Encontrar o melhor valor objetivo entre as particulas atuais e comparar com o Gbest. Caso haja melhora, Gbest recebe a posicao e Gbestfun recebe a funcao-objetivo da melhor particula.
# ===============
# Passo 7: Repetir o processo a partir do Passo 3 ateh que uma condicao de parada seja encontrada.
# ===============
# Exemplo de implementacao para os Passos 3 ao 7:
# Enquanto o criterio de parada nao for satisfeito, faca:
    ciclo = 0
    while (ciclo < 100):
        # Para cada particula do enxame, faca:
        #Passo 3: Atualizar as posicoes e velocidades das particulas de acordo com asequacoes a seguir:
        for i in range(0, len(enxame.vetParticulas)):
            # Para cada dimensao, faca:
            for d in range(0, len(enxame.vetParticulas[i].pBest)):
                # Escolha valores aleatorios entre 0 e 1.
                rp = random.random()
                rg = random.random()
                # Atualize a velocidade da particula.
                enxame.vetParticulas[i].speed[d] = (
                    w * enxame.vetParticulas[i].speed[d]) + (
                        c_1 * random.random() *
                        (enxame.vetParticulas[i].pBest[d] -
                         enxame.vetParticulas[i].x[d])) + (
                             c_2 * random.random() *
                             (enxame.vetParticulas[gBest].pBest[d] -
                              enxame.vetParticulas[i].x[d]))

                enxame.vetParticulas[i].x[d] = enxame.vetParticulas[i].x[
                    d] + enxame.vetParticulas[i].speed[d]
    # ===============
    #Passo 4: Calcular o valor da funcao-objetivo f(X) para todas as particulas considerando a quantidade de neuronios na camada escondida.
        for i in range(0, len(enxame.vetParticulas)):
            parametros[1] = enxame.vetParticulas[i].x[0]
            parametros[2] = enxame.vetParticulas[i].x[1]

            rede = rede = inicializaRede(parametros, 9)
            rede = LM(rede, treino, teste)
            for j in range(0, len(enxame.vetParticulas[i].pBest)):
                #- O vetor Pbest[i] recebe a posicao atual de cada particula;
                enxame.vetParticulas[i].pBest[j] = enxame.vetParticulas[i].x[j]
                #- O vetor Pbestfun[i] recebe o valor da funcao-objetivo da particula;
            enxame.vetParticulas[i].pBestFun = rede.erroFinal.quadratico
            #- Gbest recebe a posicao da melhor particula do enxame;
            #- Gbestfun recebe a funcao-objetivo da melhor particula do enxame.
            if (enxame.melhorRede.erroFinal.quadratico >
                    rede.erroFinal.quadratico):
                gBest = i
                enxame.melhorRede = bkpRede(rede)
            # Atualiza o criterio de parada.

    return enxame
Пример #11
0
            field[i + 6] = temp[i]
    if rand1 == 2:
        for i in range(0, 3):
            temp[i] = field[i + 3].copy()
            field[i + 3] = field[i + 6].copy()
            field[i + 6] = temp[i]


def swap_big_columns():
    transpose()
    swap_big_rows()
    transpose()


for i in range(10000):
    rand1 = ramdom(0, 4)
    if rand1 == 0:
        swap_rows()
    elif rand1 == 1:
        swap_columns()
    elif rand1 == 2:
        swap_big_rows()
    elif rand1 == 3:
        swap_big_columns()
    else:
        transpose()
show_field()

i = 0
j = 0
print('┏━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓')