1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/guofei9987-scikit-opt

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Клонировать/Скачать
Внести вклад в разработку кода
Синхронизировать код
Отмена
Подсказка: Поскольку Git не поддерживает пустые директории, создание директории приведёт к созданию пустого файла .keep.
Loading...
README.md

Swarm Intelligence in Python
(Genetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony Algorithm, Immune Algorithm, Artificial Fish Swarm Algorithm в Python)

Установка

pip install scikit-opt

Для текущей версии разработчика:

git clone git@github.com:guofei9987/scikit-opt.git
cd scikit-opt
pip install .

Возможности

Функция UDF

UDF (пользовательская функция) теперь доступна!

Например, вы только что разработали новый тип функции selection. Теперь ваша функция selection выглядит так:
-> Демо-код: examples/demo_ga_udf.py#s1

# шаг 1: определите свой собственный оператор:
def selection_tournament(algorithm, tourn_size):
    FitV = algorithm.FitV
    sel_index = []
    for i in range(algorithm.size_pop):
        aspirants_index = np.random.choice(range(algorithm.size_pop), size=tourn_size)
        sel_index.append(max(aspirants_index, key=lambda i: FitV[i]))
    algorithm.Chrom = algorithm.Chrom[sel_index, :]  # следующее поколение
    return algorithm.Chrom

Импортируйте и создайте ga
-> Демо-код: examples/demo_ga_udf.py#s2

import numpy as np
from sko.GA import GA, GA_TSP

demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + (x[2] - 0.5) ** 2
ga = GA(func=demo_func, n_dim=3, size_pop=100, max_iter=500, prob_mut=0.001,
        lb=[-1, -10, -5], ub=[2, 10, 2], precision=[1e-7, 1e-7, 1])

Зарегистрируйте свою функцию UDF в GA
-> Демо-код: examples/demo_ga_udf.py#s3

ga.register(operator_name='selection', operator=selection_tournament, tourn_size=3)

Scikit-Opt также предоставляет некоторые операторы
-> Демо-код: examples/demo_ga_udf.py#s4

from sko.operators import ranking, selection, crossover, mutation

ga.register(operator_name='ranking', operator=ranking.ranking). \
    register(operator_name='crossover', operator=crossover.crossover_2point). \
    register(operator_name='mutation', operator=mutation.mutation)

Теперь выполните GA как обычно
-> Демо-код: examples/demo_ga_udf.py#s5

best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
``` **Для продвинутых пользователей:**

**Demo code: [examples/demo_ga_udf.py#s6](https://github.com/guofei9987/scikit-opt/blob/master/examples/demo_ga_udf.py#L31)**
```python
class MyGA(GA):
    def selection(self, tourn_size=3):
        FitV = self.FitV
        sel_index = []
        for i in range(self.size_pop):
            aspirants_index = np.random.choice(range(self.size_pop), size=tourn_size)
            sel_index.append(max(aspirants_index, key=lambda i: FitV[i]))
        self.Chrom = self.Chrom[sel_index, :]  # next generation
        return self.Chrom

    ranking = ranking.ranking


demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + (x[2] - 0.5) ** 2
my_ga = MyGA(func=demo_func, n_dim=3, size_pop=100, max_iter=500, lb=[-1, -10, -5], ub=[2, 10, 2],
             precision=[1e-7, 1e-7, 1])
best_x, best_y = my_ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

feature2: continue to run

(New in version 0.3.6)
Запустите алгоритм на 10 итераций, а затем ещё на 20 итераций на основе 10 предыдущих:

from sko.GA import GA

func = lambda x: x[0] ** 2
ga = GA(func=func, n_dim=1)
ga.run(10)
ga.run(20)

feature3: 4 способа ускорения

  • векторизация
  • многопоточность
  • мультипроцессинг
  • кэширование

см. https://github.com/guofei9987/scikit-opt/blob/master/examples/example_function_modes.py

feature4: вычисления на GPU

Мы разрабатываем вычисления на GPU, которые будут стабильны в версии 1.0.0
Пример уже доступен: https://github.com/guofei9987/scikit-opt/blob/master/examples/demo_ga_gpu.py

Быстрый старт

1. Дифференциальная эволюция

Шаг 1: определите свою задачу
-> Demo code: examples/demo_de.py#s1

'''
min f(x1, x2, x3) = x1^2 + x2^2 + x3^2
s.t.
    x1*x2 >= 1
    x1*x2 <= 5
    x2 + x3 = 1
    0 <= x1, x2, x3 <= 5
'''


def obj_func(p):
    x1, x2, x3 = p
    return x1 ** 2 + x2 ** 2 + x3 ** 2


constraint_eq = [
    lambda x: 1 - x[1] - x[2]
]

constraint_ueq = [
    lambda x: 1 - x[0] * x[1],
    lambda x: x[0] * x[1] - 5
]

Шаг 2: выполните дифференциальную эволюцию
-> Demo code: examples/demo_de.py#s2

from sko.DE import DE

de = DE(func=obj_func, n_dim=3, size_pop=50, max_iter=800, lb=[0, 0, 0], ub=[5, 5, 5],
        constraint_eq=constraint_eq, constraint_ueq=constraint_ueq)

best_x, best_y = de.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

2. Генетический алгоритм

Шаг 1: Определите свою задачу
-> Demo code: examples/demo_ga.py#s1

import numpy as np


def schaffer(p):
    '''
    This function has plenty of local minimum, with strong shocks
    global minimum at (0,0) with value 0
    https://en.wikipedia.org/wiki/Test_functions_for_optimization
    '''
    x1, x2 = p
    part1 = np.square(x1) - np.square(x2)
    part2 = np.square(x1) + np.square(x2)
    return 0.5 + (np.square(np.sin(part1)) - 0.5) / np.square(1 + 0.001 * part2)

Шаг 2: Выполните генетический алгоритм
-> Demo code: examples/demo_ga.py#s2

from sko.GA import GA

ga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, prob_mut=0.001, lb=[-1, -1], ub=[1, 1], precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

-> Demo code: examples/demo_ga.py#s3

import pandas as pd
import matplotlib.pyplot as plt

Y_history = pd.DataFrame(ga.all_history_Y)
fig, ax = plt.subplots(2, 1)
ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
``` **2. Генетический алгоритм для задачи коммивояжёра (Travelling Salesman Problem)**

Y_history.min(axis=1).cummin().plot(kind='line')
plt.show()

Рисунок 1-1

2.2 Генетический алгоритм для TSP (задача коммивояжёра)

Просто импортируйте GA_TSP, он перегружает crossover и mutation для решения TSP.

Шаг 1: определите свою задачу. Подготовьте координаты точек и матрицу расстояний. Здесь я генерирую данные случайным образом в качестве демонстрации:

import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt

num_points = 50

points_coordinate = np.random.rand(num_points, 2)  # generate coordinate of points
distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean')

def cal_total_distance(routine):
    '''The objective function. input routine, return total distance.
    cal_total_distance(np.arange(num_points))
    '''
    num_points, = routine.shape
    return sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])

Шаг 2: выполните ГА.

from sko.GA import GA_TSP

ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=500, prob_mut=1)
best_points, best_distance = ga_tsp.run()

Шаг 3: Постройте результат.

fig, ax = plt.subplots(1, 2)
best_points_ = np.concatenate([best_points, [best_points[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')
ax[1].plot(ga_tsp.generation_best_Y)
plt.show()

Рисунок GA_TPS

3. Метод роя частиц (Particle swarm optimization)

3.1 Метод роя частиц

Шаг 1: Определите свою проблему.

def demo_func(x):
    x1, x2, x3 = x
    return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2

Шаг 2: Выполните метод роя частиц.

from sko.PSO import PSO

pso = PSO(func=demo_func, n_dim=3, pop=40, max_iter=150, lb=[0, -1, 0.5], ub=[1, 1, 1], w=0.8, c1=0.5, c2=0.5)
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

Шаг 3: Постройте результат.

import matplotlib.pyplot as plt

plt.plot(pso.gbest_y_hist)
plt.show()

Рисунок PSO_TPS

3.2 Метод роя частиц с нелинейным ограничением

Если вам нужно нелинейное ограничение, например (x[0] - 1) ** 2 + (x[1] - 0) ** 2 - 0.5 ** 2<=0, коды будут выглядеть следующим образом:

constraint_ueq = (
    lambda x: (x[0] - 1) ** 2 + (x[1] - 0) ** 2 - 0.5 ** 2
    ,
)
pso = PSO(func=demo_func, n_dim=2, pop=40, max_iter=max_iter, lb=[-2, -2], ub=[2, 2]
          , constraint_ueq=constraint_ueq)

Обратите внимание, что вы можете добавить более одного нелинейного ограничения. Просто добавьте его в constraint_ueq.

Кроме того, у нас есть анимация.

Рисунок pso_ani

↑ Смотрите examples/demo_pso_ani.py.

4. SA (Simulated Annealing)

4.1 SA для нескольких функций

Шаг 1: Определите вашу проблему.

demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2

Шаг 2: Выполните SA.

from sko.SA import SA
``` **Текст запроса:**

sa = SA(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, L=300, max_stay_counter=150) best_x, best_y = sa.run() print('best_x:', best_x, 'best_y', best_y)


**Перевод:**

`sa = SA(func = demo_func, x0 = [1, 1, 1], T_max = 1, T_min = 1e-09, L = 300, max_stay_counter = 150)`

`best_x, best_y = sa.run()`

`print('best_x: ', best_x, ' best_y')`

*Примечание: в переводе не хватает информации для понимания контекста, поэтому некоторые фразы могут быть интерпретированы неправильно.* Текст запроса представляет собой список научных статей из различных областей, связанных с информационными технологиями.

1. Heinrich, K., Zschech, P., Janiesch, C., & Bonin, M. (2021). Process data properties matter: Introducing gated convolutional neural networks (GCNN) and key-value-predict attention networks (KVP) for next event prediction with deep learning. Decision Support Systems, 143, 113494.

2. Tang, H. K., & Goh, S. K. (2021). A Novel Non-population-based Meta-heuristic Optimizer Inspired by the Philosophy of Yi Jing. arXiv preprint arXiv:2104.08564.
3. Wu, G., Li, L., Li, X., Chen, Y., Chen, Z., Qiao, B., ... & Xia, L. (2021). Graph embedding based real-time social event matching for EBSNs recommendation. World Wide Web, 1-22.
4. Pan, X., Zhang, Z., Zhang, H., Wen, Z., Ye, W., Yang, Y., ... & Zhao, X. (2021). A fast and robust mixture gases identification and concentration detection algorithm based on attention mechanism equipped recurrent neural network with double loss function. Sensors and Actuators B: Chemical, 342, 129982.
5. Castella Balcell, M. (2021). Optimization of the station keeping system for the WindCrete floating offshore wind turbine.
6. Zhai, B., Wang, Y., Wang, W., & Wu, B. (2021). Optimal Variable Speed Limit Control Strategy on Freeway Segments under Fog Conditions. arXiv preprint arXiv:2107.14406.
7. Yap, X. H. (2021). Multi-label classification on locally-linear data: Application to chemical toxicity prediction.
8. Gebhard, L. (2021). Expansion Planning of Low-Voltage Grids Using Ant Colony Optimization Ausbauplanung von Niederspannungsnetzen mithilfe eines Ameisenalgorithmus.
9. Ma, X., Zhou, H., & Li, Z. (2021). Optimal Design for Interdependencies between Hydrogen and Power Systems. IEEE Transactions on Industry Applications.
10. de Curso, T. D. C. (2021). Estudo do modelo Johansen-Ledoit-Sornette de bolhas financeiras.
11. Wu, T., Liu, J., Liu, J., Huang, Z., Wu, H., Zhang, C., ... & Zhang, G. (2021). A Novel AI-based Framework for AoI-optimal Trajectory Planning in UAV-assisted Wireless Sensor Networks. IEEE Transactions on Wireless Communications.
12. Liu, H., Wen, Z., & Cai, W. (2021, August). FastPSO: Towards Efficient Swarm Intelligence Algorithm on GPUs. In 50th International Conference on Parallel Processing (pp. 1–10).
13. Mahbub, R. (2020). Algorithms and Optimization Techniques for Solving TSP.
14. Li, J., Chen, T., Lim, K., Chen, L., Khan, S. A., Xie, J., & Wang, X. (2019). Deep learning accelerated gold nanocluster synthesis. Advanced Intelligent Systems, 1(3), 1900029.

В запросе нет текста на языках программирования, гиперссылок, специальных тегов форматирования в markdown, html, yaml, json, plantuml и других.

Комментарии ( 0 )

Вы можете оставить комментарий после Вход в систему

Введение

Эвристические алгоритмы (генетический алгоритм, оптимизация роя частиц, имитация отжига, муравьиный алгоритм, иммунный алгоритм, алгоритм искусственного рыбного роя и задача коммивояжёра) на Python. *Генетический алгоритм*, *оптимизация роя частиц*, *имитация отжига*, *муравьиный алгоритм*, *иммунный алгоритм*, *алгоритм искусственного рыбного ... Развернуть Свернуть
MIT
Отмена

Обновления (1)

все

Участники

все

Недавние действия

Загрузить больше
Больше нет результатов для загрузки
1
https://api.gitlife.ru/oschina-mirror/guofei9987-scikit-opt.git
git@api.gitlife.ru:oschina-mirror/guofei9987-scikit-opt.git
oschina-mirror
guofei9987-scikit-opt
guofei9987-scikit-opt
master