예제 #1
0
def generate_experience_one(learning_agent, reference_agent, exp_file,
                            num_games, board_size, temperature, filename):
    experience_files = []
    gpu_frac = 0.95
    games_per_worker = num_games

    do_self_play(
        board_size,
        learning_agent,
        reference_agent,
        games_per_worker,
        temperature,
        filename,
        gpu_frac,
    )

    # Merge experience buffers.
    print('Merging experience buffers...')
    first_filename = experience_files[0]
    other_filenames = experience_files[1:]
    with h5py.File(first_filename, 'r') as expf:
        combined_buffer = rl.load_experience(expf)
    for filename in other_filenames:
        with h5py.File(filename, 'r') as expf:
            next_buffer = rl.load_experience(expf)
        combined_buffer = rl.combine_experience([combined_buffer, next_buffer])
    print('Saving into %s...' % exp_file)
    with h5py.File(exp_file, 'w') as experience_outf:
        combined_buffer.serialize(experience_outf)

    # Clean up.
    for fname in experience_files:
        os.unlink(fname)
예제 #2
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--learning-agent', required=True)
    parser.add_argument('--num-games', '-n', type=int, default=10)
    parser.add_argument('--experience-out', '-o', required=True)
    parser.add_argument('--num-workers', '-w', type=int, default=1)
    parser.add_argument('--temperature', '-t', type=float, default=0.0)
    parser.add_argument('--board-size', '-b', type=int, default=19)

    args = parser.parse_args()

    experience_files = []
    workers = []
    gpu_frac = 0.95 / float(args.num_workers)
    games_per_worker = args.num_games // args.num_workers
    print('Starting workers...')
    for i in range(args.num_workers):
        filename = get_temp_file()
        experience_files.append(filename)
        worker = multiprocessing.Process(
            target=do_self_play,
            args=(
                args.board_size,
                args.learning_agent,
                games_per_worker,
                args.temperature,
                filename,
                gpu_frac,
            )
        )
        worker.start()
        workers.append(worker)

    # Wait for all workers to finish.
    print('Waiting for workers...')
    for worker in workers:
        worker.join()

    # Merge experience buffers.
    print('Merging experience buffers...')
    # first_filename = experience_files[0]
    other_filenames = experience_files[1:]
    combined_buffer = rl.load_experience(h5py.File(filename))
    for filename in other_filenames:
        next_buffer = rl.load_experience(h5py.File(filename))
        combined_buffer = rl.combine_experience([combined_buffer, next_buffer])
    print('Saving into %s...' % args.experience_out)
    with h5py.File(args.experience_out, 'w') as experience_outf:
        combined_buffer.serialize(experience_outf)

    # Clean up.
    for fname in experience_files:
        os.unlink(fname)
예제 #3
0
    def test_3_alphago_value(self):

        print("TEST 3\n=====================================================")
        gpus = tf.config.experimental.list_physical_devices('GPU')
        if gpus:
            # Restrict TensorFlow to only use the first GPU
            try:
                tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
                tf.config.experimental.set_memory_growth(gpus[0], True)
                tf.config.set_soft_device_placement(True)
            except RuntimeError as e:
                print(e)

        rows, cols = 19, 19
        encoder = AlphaGoEncoder()
        input_shape = (encoder.num_planes, rows, cols)
        alphago_value_network = alphago_model(input_shape)

        alphago_value = ValueAgent(alphago_value_network, encoder)

        experience = load_experience(
            h5py.File('test_alphago_rl_experience.h5', 'r'))

        alphago_value.train(experience)

        with h5py.File('test_alphago_value.h5', 'w') as value_agent_out:
            alphago_value.serialize(value_agent_out)
예제 #4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--learning-agent', required=True)
    parser.add_argument('--agent-out', required=True)
    parser.add_argument('--lr', type=float, default=0.0001)
    parser.add_argument('--bs', type=int, default=512)
    parser.add_argument('experience', nargs='+')

    args = parser.parse_args()
    learning_agent_filename = args.learning_agent
    experience_files = args.experience
    updated_agent_filename = args.agent_out
    learning_rate = args.lr
    batch_size = args.bs

    learning_agent = rl.load_ac_agent(h5py.File(learning_agent_filename))
    for exp_filename in experience_files:
        exp_buffer = rl.load_experience(h5py.File(exp_filename))
        learning_agent.train(
            exp_buffer,
            lr=learning_rate,
            batch_size=batch_size)

    with h5py.File(updated_agent_filename, 'w') as updated_agent_outf:
        learning_agent.serialize(updated_agent_outf)
예제 #5
0
def train_worker(learning_agent, output_file, experience_file, lr, batch_size):
    learning_agent = load_agent(learning_agent)
    with h5py.File(experience_file, 'r') as expf:
        exp_buffer = rl.load_experience(expf)
    learning_agent.train(exp_buffer, lr=lr, batch_size=batch_size)

    with h5py.File(output_file, 'w') as updated_agent_outf:
        learning_agent.serialize(updated_agent_outf)
예제 #6
0
def generate_experience(learning_agent, reference_agent, exp_file,
                        num_games, board_size, num_workers, temperature):
    experience_files = []
    workers = []
    gpu_frac = 0.95 / float(num_workers)
    games_per_worker = num_games // num_workers
    for i in range(num_workers):
        filename = get_temp_file()
        experience_files.append(filename)
        worker = multiprocessing.Process(
            target=do_self_play,
            args=(
                board_size,
                learning_agent,
                reference_agent,
                games_per_worker,
                temperature,
                filename,
                gpu_frac,
            )
        )
        worker.start()
        workers.append(worker)

    # Wait for all workers to finish.
    print('Waiting for workers...')
    for worker in workers:
        worker.join()

    # Merge experience buffers.
    print('Merging experience buffers...')
    first_filename = experience_files[0]
    other_filenames = experience_files[1:]
    with h5py.File(first_filename, 'r') as expf:
        combined_buffer = rl.load_experience(expf)
    for filename in other_filenames:
        with h5py.File(filename, 'r') as expf:
            next_buffer = rl.load_experience(expf)
        combined_buffer = rl.combine_experience([combined_buffer, next_buffer])
    print('Saving into %s...' % exp_file)
    with h5py.File(exp_file, 'w') as experience_outf:
        combined_buffer.serialize(experience_outf)

    # Clean up.
    for fname in experience_files:
        os.unlink(fname)
예제 #7
0
def main():
    pth = '//home//nail//Code_Go//checkpoints//'
    pth_experience = '//home//nail//Experience//'
    experience = []
    os.chdir(pth_experience)
    lst_files = os.listdir(pth_experience)
    pattern = input('Паттерн для выборки файлов для обучения: ')
    if len(pattern) == 0:
        pattern = "exp*.h5"

    for entry in lst_files:
        if fnmatch.fnmatch(entry, pattern):
            experience.append(entry)

    experience.sort()
    learning_agent = input('learning_agent:')
    learning_agent = pth + learning_agent+'.h5'
    print('learning_agent: ', learning_agent)
    agent_out = input('agent_out:')
    agent_out = pth + agent_out+'.h5'
    print('agent_out: ', agent_out)
    try:
        lr = float(input('lr = '))
    except:
        lr = 0.000001
    try:
        bs = int(input('bs = '))
    except:
        bs = 1024

    # ==================================================
    import tensorflow as tf
    config = tf.compat.v1.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.98
    config.gpu_options.allow_growth = True
    config.log_device_placement = True
    sess = tf.compat.v1.Session(config=config)
    tf.compat.v1.keras.backend.set_session(sess)
    # ==================================================


    learning_agent = agent.load_policy_agent(h5py.File(learning_agent, "r"))

    i = 1
    num_files = len(experience)
    for exp_filename in experience:
        print(50*'=')
        print('Файл для обучения: %s...' % exp_filename)
        print(50 * '=')
        exp_buffer = rl.load_experience(h5py.File(exp_filename, "r"))
        learning_agent.train(exp_buffer, lr=lr, batch_size=bs)
        print('Обработано файлов: ', i, ' из ', num_files)
        i += 1

    with h5py.File(agent_out, 'w') as updated_agent_outf:
        learning_agent.serialize(updated_agent_outf)
예제 #8
0
    def test_3_alphago_value(self):
        rows, cols = 19, 19
        encoder = AlphaGoEncoder()
        input_shape = (encoder.num_planes, rows, cols)
        alphago_value_network = alphago_model(input_shape)

        alphago_value = ValueAgent(alphago_value_network, encoder)

        experience = load_experience(
            h5py.File('test_alphago_rl_experience.h5', 'r'))

        alphago_value.train(experience)

        with h5py.File('test_alphago_value.h5', 'w') as value_agent_out:
            alphago_value.serialize(value_agent_out)
예제 #9
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--learning-agent', required=True)
    parser.add_argument('--agent-out', required=True)
    parser.add_argument('--lr', type=float, default=0.0001)
    parser.add_argument('--bs', type=int, default=512)
    parser.add_argument('experience', nargs='+')

    args = parser.parse_args()

    learning_agent = agent.load_policy_agent(h5py.File(args.learning_agent))
    for exp_filename in args.experience:
        print('Training with %s...' % exp_filename)
        exp_buffer = rl.load_experience(h5py.File(exp_filename))
        learning_agent.train(exp_buffer, lr=args.lr, batch_size=args.bs)

    with h5py.File(args.agent_out, 'w') as updated_agent_outf:
        learning_agent.serialize(updated_agent_outf)
예제 #10
0
def train_worker(learning_agent, output_file, experience_file, lr, batch_size):

    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
        # Restrict TensorFlow to only use the first GPU
        try:
            tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
            tf.config.experimental.set_memory_growth(gpus[0], True)
        except RuntimeError as e:
            print(e)

    with h5py.File(learning_agent, 'r') as learning_agentf:
        learning_agent = agent.load_policy_agent(learning_agentf)
    with h5py.File(experience_file, 'r') as expf:
        exp_buffer = rl.load_experience(expf)
    learning_agent.train(exp_buffer, lr=lr, batch_size=batch_size)

    with h5py.File(output_file, 'w') as updated_agent_outf:
        learning_agent.serialize(updated_agent_outf)
예제 #11
0
def main():
    # PLACEHOLDER VARIABLES (CHANGE BEFORE TRAINING MODEL)
    learning_agent_filename = h5py.File("")
    experience_files = ["", ""]
    learning_rate = 0.0001
    clipnorm = 0.5
    batchsize = 1024
    updated_agent_filename = "something"
    #
    learning_agent = agent.load_policy_agent(
        h5py.File(learning_agent_filename))  # 10.7
    for exp_filename in experience_files:
        exp_buffer = rl.load_experience(h5py.File(exp_filename))
        learning_agent.train(exp_buffer,
                             lr=learning_rate,
                             clipnorm=clipnorm,
                             batch_size=batchsize)
    with h5py.File(updated_agent_filename, 'w') as updated_agent_outf:
        learning_agent.serialize(updated_agent_outf)
예제 #12
0
def generator_q(experience= [], num_moves=361, batch_size=512):
    for exp_filename in experience:
        #print('Файл  с играми для обучения: %s...' % exp_filename)
        exp_buffer = rl.load_experience(h5py.File(exp_filename, "r"))

        n = exp_buffer.states.shape[0] # Количество состояний доски
        states = exp_buffer.states     # Состояния доски
        y = np.zeros((n,))             # Целевой вектор для обучения
        actions = np.zeros((n, num_moves))  # Действия к каждому состоянию доски

        for i in range(n):
            action = exp_buffer.actions[i]
            reward = exp_buffer.rewards[i]
            actions[i][action] = 1
            y[i] = reward

        while states.shape[0] >= batch_size:
            states_batch, states = states[:batch_size], states[batch_size:]
            actions_batch, actions = actions[:batch_size], actions[batch_size:]
            y_batch, y = y[:batch_size], y[batch_size:]

            yield [states_batch, actions_batch], y_batch
예제 #13
0
# tag::init_value[]
from dlgo.networks.alphago import alphago_model
from dlgo.encoders.alphago import AlphaGoEncoder
from dlgo.rl import ValueAgent, load_experience
import h5py

rows, cols = 19, 19
encoder = AlphaGoEncoder()
input_shape = (encoder.num_planes, rows, cols)
alphago_value_network = alphago_model(input_shape)

alphago_value = ValueAgent(alphago_value_network, encoder)
# end::init_value[]

# tag::train_value[]
experience = load_experience(h5py.File('alphago_rl_experience.h5', 'r'))

alphago_value.train(experience)

with h5py.File('alphago_value.h5', 'w') as value_agent_out:
    alphago_value.serialize(value_agent_out)
# end::train_value[]
예제 #14
0
def main():
    pth = "//home//nail//Code_Go//checkpoints//"
    pth_experience = '//home//nail//Experience//'
    # board_size =19
    # hidden_size =512   # Можно экспериментировать. В книге было 256
    learning_agent = input('Агент для обучения "ценность действия": ')
    num_games = int(input('Количество игр для формирования учебных данных = '))
    try:
        chunk = int(input('Порция игр в одном файле для обучения = '))
    except:
        chunk = 100

    delta_games = int(input('Приращение количества игр = '))
    learning_agent = pth+learning_agent+'.h5'  # Это начальный агент либо первый либо для продолжения обучения
    output_file = pth+'new_q_agent.h5'     # Это будет уже агент обновляемый с лучшими результатами игр
    current_agent = pth + 'current_agent.h5' # Текущий обучаемый агент
    try:
        lr = float(input('Скорость обучения lr = '))
    except:
        lr = 0.01

    temp_decay = 0.98
    min_temp = 0.001
    try:
        temperature = float(input('Temperature = '))
    except:
        temperature = min_temp
    try:
        batch_size = int(input("batch_size = "))
    except:
        batch_size = 512
    try:
        epochs = int(input('Epochs = '))
    except:
        epochs = 1

    log_file = input('Журнал обработки: ')
    log_file = pth_experience + log_file+'.txt'

    logf = open(log_file, 'a')
    logf.write('----------------------\n')
    logf.write('Начало обучения агента %s в %s\n' % (
        learning_agent, datetime.datetime.now()))

    # Строится модель для обучения ценность действия
    # Два входа, один выход.
    # Компиляция модели если еще нет модели для ценности действия.
    # Иначе загружаем уже существующую модель.

    if ('q_agent' in learning_agent and os.path.isfile(learning_agent)) == False:
        exit(10)

    pattern = input('Паттерн для выборки файлов для обучения: ')
    if len(pattern) == 0:
        pattern = "exp*.h5"

    total_work = 0  # Счетчик "прогонов" обучения.
    while True:  # Можно всегда прервать обучение и потом продолжть снова.

        l_agent = load_agent(learning_agent)
        model = l_agent.model
        encoder = l_agent.encoder
        num_moves = encoder.num_points()

        logf.write('Прогон = %d\n' % total_work)
        print(50 * '=')
        experience = []
        os.chdir(pth_experience)
        lst_files = os.listdir(pth_experience)
        # ==============================================================
        # Формируем список файлов с экспериментальными игровыми данными
        for entry in lst_files:
            if fnmatch.fnmatch(entry, pattern):
                experience.append(entry)
        # Получили список файлов игр для обучения
        # Сортировка для удобства файлов.
        if len(experience) > 0:
            experience.sort()
        else:
            print(' Нет файлов в папке для обучения!!!!')
            exit(2)

        n = []
        experience.sort()
        len_experience = len(experience)  # Количество файлов для обучения
        exp_buffers = []
        states = []
        for exp_filename in  experience:
            print('Файл  с играми для обучения: %s...' % exp_filename)
            exp_buffer = rl.load_experience(h5py.File(exp_filename, "r"))
            exp_buffers.append(exp_buffer)
            n.append(exp_buffer.states.shape[0])
            states.extend(exp_buffer.states)

            gc.collect()

        n_all = sum(n)    # Общее количество состояний игр во всех файлах
        print(' Количество состояний доски во всех играх = ',n_all)
        del exp_buffer
        gc.collect()
        # Заполняем данными для обучения из считанного буфера с играми  скомпилированную модель.
        y = np.zeros((n_all,))
        actions = np.zeros((n_all, num_moves))
        k = 0
        for j in range(len_experience):
            for i in range(n[j]):
                action = exp_buffers[j].actions[i]
                reward = exp_buffers[j].rewards[i]
                actions[k+i][action] = 1
                y[k+i] = reward
            k +=n[j]
        del exp_buffers
        gc.collect()
        # Обучение модели
        model.fit(
                [states, actions], y,
                batch_size=batch_size,
                verbose=1,
                epochs=epochs)
        # Прошлись по всем файлам
        del states
        del actions
        del y
        gc.collect()
#---------------------------------------------------------------------------
        # Сохранение обученного агента нужно для оценки улучшения старого агента
        # Если агент в игре будет лучше то он сохранится в out_file и новый обучаемый агент
        # будет загружаться из обновленного с новыми игровыми данными проведенными этим
        # обновленным агентом. Если нет, старый агент без изменений, только добавить
        # дополнительное количество выполненных игр обучаемым агентом к прежним.
        new_agent = rl.QAgent(model, encoder)
        with h5py.File(current_agent, 'w') as outf:  # Сохраняем агента как текущего
            new_agent.serialize(outf)


        print('\n Оцениваем нового  агента с "старым" агентом\n')
        wins = eval(current_agent, learning_agent, num_games=200)
        print('Выиграно %d / %s игр (%.3f)' % (
            wins, str(200), float(wins) / 200))
        logf.write('Выиграно %d / %s игр (%.3f)\n' % (
            wins, str(200), float(wins) / float(200)))
        bt = binom_test(wins, 200, 0.5)*100
        print('Бином тест = ', bt , '%')
        logf.write('Бином тест = %f\n' % bt)
        if bt <= 5 and wins > 115:
            print('Обновление агента!!!!!')
            # Сохраняем обученного агента
            new_agent = rl.QAgent(model, encoder)
            with h5py.File(output_file, 'w') as outf:
                new_agent.serialize(outf)

            logf.write('Выполнено обновление агента после успешного обучения %d  время  %s\n' % (total_work,
                                                              datetime.datetime.now()))
            logf.write('Новый агент : %s\n' % output_file)

            # Очистка каталога с данными игр "старого" агента
            pth_exp_save = pth_experience+'Exp_Save'
            os.chdir(pth_exp_save)
            lst_files = os.listdir(pth_exp_save)
            for entry in lst_files:
                os.remove(entry)

            # Сохраняем игровые данные в каталоге сохранения
            experience = []
            os.chdir(pth_experience)
            lst_files = os.listdir(pth_experience)
            for entry in lst_files:
                if fnmatch.fnmatch(entry, 'exp*'):
                    experience.append(entry)
            for exp_filename in experience:
                shutil.move(exp_filename, pth_experience+'Exp_Save//'+exp_filename)

            # Формируем список файлов с экспериментальными игровыми данными
            temperature = max(min_temp, temp_decay * temperature)
            exp_filename = 'exp'+str(total_work)+'_'
            do_self_play(19, output_file, output_file, num_games=num_games,
                         temperature=temperature, experience_filename=exp_filename, chunk=chunk)
            learning_agent = output_file    # Теперь на следующей шаге обучаемым станет обновленный агент

            logf.write('Новая "температура" = %f\n' % temperature)
        else:
            # print('Агента не меняем, Игровые данные увеличивам \n')
            if num_games < 40000:
            # Добавим порцию игр
            #learning_agent оставляем без изменений. Новый обученный агент не лучше старого.
            # Добавим порцию игр для дополнительного обучения.
               exp_filename = 'exp' + str(total_work) + '_'
               do_self_play(19, learning_agent, learning_agent,
                         num_games=delta_games,  # Добавим новые файлы к уже существующим новые файлы.
                         temperature=temperature, experience_filename=exp_filename, chunk=chunk)


        total_work += 1
        print('Количество выполненных прогонов = ', total_work)
        logf.write('Выполнен прогон %d  время at %s\n' % (total_work,
            datetime.datetime.now()))

        logf.flush()
        if total_work > 1000:
            break
예제 #15
0
def main():
    pth = "//home//nail//Code_Go//checkpoints//"
    pth_experience = '//home//nail//Experience//'
    board_size = 19
    network = 'small'
    hidden_size = 512
    learning_agent = input('Агент для обучения "ценность действия": ')
    num_games = int(input('Количество игр для формирования учебных данных = '))
    delta_games = int(input('Приращение количества игр = '))
    learning_agent = pth + learning_agent + '.h5'  # Это агент либо от политики градиентов(глава 10),либо из главы 7"
    output_file = pth + 'new_value_model.h5'  # Это будет уже агент с двумя входами для ценности действия
    current_agent = pth + 'current_model.h5'  # Текущий обучаемый агент
    lr = 0.0001
    temp_decay = 0.98
    min_temp = 0.00001
    try:
        temperature = float(input('Temperature = '))
    except:
        temperature = min_temp
    try:
        batch_size = int(input("batch_size = "))
    except:
        batch_size = 512
    try:
        epochs = int(input('Epochs = '))
    except:
        epochs = 1

    log_file = input('Журнал обработки: ')
    log_file = pth_experience + log_file + '.txt'

    logf = open(log_file, 'a')
    logf.write('----------------------\n')
    logf.write('Начало обучения агента %s в %s\n' %
               (learning_agent, datetime.datetime.now()))

    # Строится модель для обучения ценность действия
    # Два входа, один выход.
    # Компиляция модели если еще нет модели для ценности действия.
    # Иначе загружаем уже существующую модель.

    if 'value_model' in learning_agent and os.path.isfile(learning_agent):
        New_QAgent = False  # Модель уже есть, надо продолжить обучение
        encoder = ''  # Чтобы не было предупреждений о возможной ошибке в коде ниже.
        model = ''
    else:
        # Еще только надо создать модель для обучения
        # Нет модели с двумя входами.
        New_QAgent = True
        encoder = encoders.get_encoder_by_name('simple', board_size)
        board_input = Input(shape=encoder.shape(), name='board_input')
        action_input = Input(shape=(encoder.num_points(), ),
                             name='action_input')

        processed_board = board_input
        network = getattr(dlgo.networks, network)
        for layer in network.layers(encoder.shape()):
            processed_board = layer(processed_board)

        board_plus_action = concatenate([action_input, processed_board])
        hidden_layer = Dense(hidden_size, activation='relu')(board_plus_action)
        value_output = Dense(1, activation='sigmoid')(hidden_layer)

        model = Model(inputs=[board_input, action_input], outputs=value_output)
        opt = SGD(lr=lr)
        model.compile(loss='mse', optimizer=opt)


# "Заполнение" данными модели обучения из игр

    experience = []
    os.chdir(pth_experience)
    lst_files = os.listdir(pth_experience)
    pattern = input('Паттерн для выборки файлов для обучения: ')
    if len(pattern) == 0:
        pattern = "exp*.h5"
    #==============================================================
    # Формируем список файлов с экспериментальными игровыми данными
    for entry in lst_files:
        if fnmatch.fnmatch(entry, pattern):
            experience.append(entry)
    # Получили список файлов игр для обучения
    exp_filename = ''
    if len(experience) > 0:
        experience.sort()
        exp_filename = experience[0]  # Нужен только один файл
    else:
        print(' Нет файлов в папке для обучения!!!!')
        exit(2)

    #==============================================================
    # callback_list = [ModelCheckpoint(pth, monitor='val_accuracy',
    #                                  save_best_only=True)]

    total_work = 0  # Счетчик "прогонов" обучения.
    exp_buffer = 'empty'  # Буфер с игровыми данными
    while True:  # Можно всегда прервать обучение и потом продолжть снова.
        if New_QAgent == False:
            q_agent = load_agent(
                learning_agent)  # Текущая обучаемая модель cуществует
            model = q_agent.model  # загружаем модель
            encoder = q_agent.encoder
            #temperature = q_agent.temperature

        logf.write('Прогон = %d\n' % total_work)
        print(50 * '=')
        print('Файл  с играми для обучения: %s...' % exp_filename)
        print(50 * '=')
        if exp_buffer == 'empty':
            exp_buffer = rl.load_experience(h5py.File(exp_filename, "r"))
        # Заполняем данными для обучения из считанного буфера с играми  скомпилированную модель.
        n = exp_buffer.states.shape[0]
        num_moves = encoder.num_points()
        y = np.zeros((n, ))
        actions = np.zeros((n, num_moves))
        for i in range(n):
            action = exp_buffer.actions[i]
            reward = exp_buffer.rewards[i]
            actions[i][action] = 1
            y[i] = 1 if reward > 0 else -1  # было 0
        # Обучение модели
        model.fit([exp_buffer.states, actions],
                  y,
                  batch_size=batch_size,
                  epochs=epochs)

        if total_work == 0:  # Нового обученного агента для сравнения еще нет.
            print('Обновление агента!!!!! Это первый обновленный агент.')
            logf.write('Первое начальное обновление обученного агента\n')
            # Сохраняем обученного агента
            #output_file = output_file + '_' + str(total_work) + '.h5'
            new_agent = rl.QAgent(model, encoder)
            with h5py.File(current_agent, 'w') as outf:
                new_agent.serialize(outf)

            # os.chdir(pth_experience)
            #
            # lst_files = os.listdir(pth_experience)
            # next_filename = 'exp_q_' + str(total_work) + '.h5'
            # for entry in lst_files:
            #     if fnmatch.fnmatch(entry, "exp*"):
            #         shutil.move(exp_filename, pth_experience + 'Exp_Save//' + next_filename)
            #         #os.remove('//home//nail//Experience//'+entry)  # Очистка каталога с данными игр "старого" агента
            # # Формируем новые игровые данные с новым агентом.
            # exp_filename = pth_experience+next_filename
            # do_self_play(19, output_file, output_file, num_games=num_games,
            #              temperature=temperature, experience_filename=exp_filename)
            # total_work += 1
            if New_QAgent == True:  # Не было еще агента с двумя входами.
                total_work += 1
                New_QAgent = False  # Теперь есть сохраненная модельс двумя входами.
                learning_agent = current_agent  # Обучать будем нового созданного с двумя входами.
                new_agent = rl.QAgent(model, encoder)
                with h5py.File(current_agent,
                               'w') as outf:  # Сохраняем агента как текущего
                    new_agent.serialize(outf)
                continue  # Сравнивать пока не с чем. Старые игровые данные оставляем

        new_agent = rl.QAgent(model, encoder)
        with h5py.File(current_agent,
                       'w') as outf:  # Сохраняем агента как текущего
            new_agent.serialize(outf)

        # Сравниваем результат игры нового текущего агента с "старым" агентом.
        wins = eval(current_agent, learning_agent, num_games=num_games)
        print('Выиграно %d / %s игр (%.3f)' %
              (wins, str(num_games), float(wins) / float(num_games)))
        logf.write('Выиграно %d / %s игр (%.3f)\n' %
                   (wins, str(num_games), float(wins) / float(num_games)))
        bt = binom_test(wins, num_games, 0.5) * 100
        print('Бином тест = ', bt, '%')
        logf.write('Бином тест = %f\n' % bt)
        if bt <= 5 and wins > num_games / 2 + num_games / 10:  # Означает не меньше чем 95% за то что новый бот играет лучше предыдущего
            print('Обновление агента!!!!!')
            # Сохраняем обученного агента
            new_agent = rl.QAgent(model, encoder)
            with h5py.File(output_file, 'w') as outf:
                new_agent.serialize(outf)

            logf.write(
                'Выполнено обновление агента после успешного обучения %d  время  %s\n'
                % (total_work, datetime.datetime.now()))
            logf.write('Новый агент : %s\n' % output_file)

            #os.remove('//home//nail//Experience//*')  # Очистка каталога с данными игр "старого" агента
            next_filename = 'exp_q_' + str(total_work) + '.h5'
            shutil.move(exp_filename,
                        pth_experience + 'Exp_Save//' + next_filename)
            # Формируем новые игровые данные с новым агентом.
            exp_filename = pth_experience + next_filename
            temperature = max(min_temp, temp_decay * temperature)
            do_self_play(19,
                         output_file,
                         output_file,
                         num_games=num_games,
                         temperature=temperature,
                         experience_filename=exp_filename)

            logf.write('Новая "температура" = %f\n' % temperature)
        else:
            print(
                'Агента не меняем, Игровые данные тоже оставляем прежними \n')

        total_work += 1
        print('Количество выполненных прогонов = ', total_work)
        logf.write('Выполнен прогон %d  время at %s\n' %
                   (total_work, datetime.datetime.now()))
        # Новая генерация учебных данных.
        # num_games += delta_games  # Увеличиваем количество игр для обучения.
        # #temperature = max(min_temp, temp_decay * temperature)
        # next_filename = 'exp_q_' + str(total_work) + '.h5'
        # shutil.move(exp_filename, pth_experience + 'Exp_Save//' + next_filename)
        # exp_filename = pth_experience + next_filename
        # do_self_play(19, current_agent, current_agent, num_games=num_games,
        #              temperature=0, experience_filename=exp_filename)
        #
        #
        # exp_buffer = rl.load_experience(h5py.File(exp_filename, "r"))  # Загружаем в буфер новый файл с играми.
        learning_agent = current_agent  # Обновляем "предыщуго обучаемого агента
        logf.flush()