コード例 #1
0
def GenKnapsack(n=1000,
                v=10,
                r=5,
                type_wp='uc',
                type_c='rk',
                addr="problems/knapsack"):

    assert type_wp in ['uc', 'wc', 'sc'], 'type_wp is not valid'
    assert type_c in ['rk', 'ak'], 'type_wp is not valid'
    #    type_wp = 'uc';  strong or weakly or un-correlated
    #    type_c = 'rk';  average or restrictive knapsack --- ALWAYS we choose average
    w = (1 + np.round(np.random.rand(n) * (v - 1)))
    if type_wp == 'uc':
        p = 1 + np.round(np.random.rand(n) * (v - 1))
    elif type_wp == 'wc':
        p = w + np.round(r - 2 * r * np.random.rand(n))
        p[p <= 0] = w[p <= 0]
    elif type_wp == 'sc':
        p = w + r

    if type_c == 'rk':
        cap = int(2 * v)
    elif type_c == 'ak':
        cap = int(0.5 * np.sum(w))

#     print(w, p, cap)
    th_best, _ = knapsack(w, p, cap)

    KP_uc_rk = {}
    KP_uc_rk['w'] = w
    KP_uc_rk['p'] = p
    KP_uc_rk['cap'] = cap
    KP_uc_rk['opt'] = th_best

    Tools.save_to_file(os.path.join(addr, 'KP_{}_{}'.format(type_wp, type_c)),
                       KP_uc_rk)
def BGA(problem,
        dims,
        th_best,
        pop=200,
        gen=1000,
        addr="problems/toy_problem"):
    """[bestSol, fitness_hist] = BGA(problem,dims,th_best): simple binary GA with
        uniform crossover and bit-flip mutation. 
       INPUT:
         problem: problem type, 'onemax', 'onemin', or 'trap5'
         dims: problem dimensionality
         th_best: global best fitness value (used for early stop to build
         probabilistic models)
        
       OUTPUT:
         bestSol: best solution
         fitness: history of best fitness for each generation"""
    bestSol = None
    all_models = Tools.load_from_file(os.path.join(addr, 'all_models'))

    fitness_hist = np.zeros(gen)
    population = np.round(np.random.rand(pop, dims))
    fitness = fitness_eval(population, problem, dims)
    buildmodel = True
    fitness_hist[0] = max(fitness)
    print('Generation 0 best fitness = ', str(fitness_hist[0]))

    for i in range(1, gen):
        parent1 = population[np.random.permutation(pop), :]
        parent2 = population[np.random.permutation(pop), :]
        tmp = np.random.rand(pop, dims)
        offspring = np.zeros((pop, dims))
        index = tmp >= 0.5
        offspring[index] = parent1[index]
        index = tmp < 0.5
        offspring[index] = parent2[index]
        tmp = np.random.rand(pop, dims)
        index = tmp < (1 / dims)
        offspring[index] = np.abs(1 - offspring[index])
        cfitness = fitness_eval(offspring, problem, dims)
        interpop = np.append(population, offspring, 0)
        interfitness = np.append(fitness, cfitness)
        index = np.argsort((-interfitness))
        interfitness = interfitness[index]
        fitness = interfitness[:pop]
        interpop = interpop[index, :]
        population = interpop[:pop, :]
        fitness_hist[i] = fitness[0]
        print('Generation ', str(i), ' best fitness = ', str(fitness_hist[i]))

        if (fitness[1] >= th_best or i == gen) and buildmodel:
            print('Building probablistic model...')
            model = ProbabilityModel('umd')
            model.buildmodel(population)
            all_models.append(model)
            Tools.save_to_file(os.path.join(addr, 'all_models'), all_models)
            print('Complete!')
            fitness_hist[i + 1:] = fitness[0]
            bestSol = population[0, :]
            break
    return bestSol, fitness_hist
def KP_BGA(problem,
           dims,
           premSTOP,
           pop=100,
           gen=100,
           addr="problems/toy_problem"):
    """[bestSol, fitness_hist] = BGA(problem,dims,th_best): simple binary GA with
        uniform crossover and bit-flip mutation. 
        INPUT:
         problem: problem generated by GenKnapsack
         dims: problem dimensionality
         premSTOP: used for early stop if no improvement is made for 20
         consecutive generations
        
        OUTPUT:
         bestSol: best solution
         fitness: history of best fitness for each ge  neration"""
    bestSol = None
    all_models = Tools.load_from_file(os.path.join(addr, 'all_models'))

    fitness_hist = np.zeros(gen)
    population = np.round(np.random.rand(pop, dims))
    fitness = knapsack_fitness_eval(population, problem, dims, pop)
    fitness_hist[0] = bestfitness = max(fitness)
    print('Generation 0 best fitness = ', str(fitness_hist[0]))

    counter = 0
    for i in range(1, gen):
        parent1 = population[np.random.permutation(pop), :]
        parent2 = population[np.random.permutation(pop), :]
        tmp = np.random.rand(pop, dims)
        offspring = np.zeros((pop, dims))
        index = tmp >= 0.5
        offspring[index] = parent1[index]
        index = tmp < 0.5
        offspring[index] = parent2[index]
        tmp = np.random.rand(pop, dims)
        index = tmp < (1 / dims)
        offspring[index] = np.abs(1 - offspring[index])
        cfitness = knapsack_fitness_eval(population, problem, dims, pop)
        interpop = np.append(population, offspring, 0)
        interfitness = np.append(fitness, cfitness)
        index = np.argsort((-interfitness))
        interfitness = interfitness[index]
        fitness = interfitness[:pop]
        interpop = interpop[index, :]
        population = interpop[:pop, :]
        fitness_hist[i] = fitness[0]
        print('Generation ', str(i), ' best fitness = ', str(fitness_hist[i]))

        if fitness[0] > bestfitness:
            bestfitness = fitness[0]
            counter = 0
        else:
            counter += 1
        if counter == 20 and premSTOP:
            fitness_hist[i:] = fitness_hist[i]
            break
    bestSol = population[0, :]
    model = ProbabilityModel('umd')
    model.buildmodel(population)
    all_models.append(model)
    Tools.save_to_file(os.path.join(addr, 'all_models'), all_models)

    return bestSol, fitness_hist