A fast Evolution Strategy implementation in Python

Overview

Evostra: Evolution Strategy for Python

Evolution Strategy (ES) is an optimization technique based on ideas of adaptation and evolution. You can learn more about it at https://blog.openai.com/evolution-strategies/

Installation

It's compatible with both python2 and python3.

Install from source:

$ python setup.py install

Install latest version from git repository using pip:

$ pip install git+https://github.com/alirezamika/evostra.git

Install from PyPI:

$ pip install evostra

(You may need to use python3 or pip3 for python3)

Sample Usages

An AI agent learning to play flappy bird using evostra

An AI agent learning to walk using evostra

How to use

The input weights of the EvolutionStrategy module is a list of arrays (one array with any shape for each layer of the neural network), so we can use any framework to build the model and just pass the weights to ES.

For example we can use Keras to build the model and pass its weights to ES, but here we use Evostra's built-in model FeedForwardNetwork which is much faster for our use case:

import numpy as np
from evostra import EvolutionStrategy
from evostra.models import FeedForwardNetwork

# A feed forward neural network with input size of 5, two hidden layers of size 4 and output of size 3
model = FeedForwardNetwork(layer_sizes=[5, 4, 4, 3])

Now we define our get_reward function:

solution = np.array([0.1, -0.4, 0.5])
inp = np.asarray([1, 2, 3, 4, 5])

def get_reward(weights):
    global solution, model, inp
    model.set_weights(weights)
    prediction = model.predict(inp)
    # here our best reward is zero
    reward = -np.sum(np.square(solution - prediction))
    return reward

Now we can build the EvolutionStrategy object and run it for some iterations:

# if your task is computationally expensive, you can use num_threads > 1 to use multiple processes;
# if you set num_threads=-1, it will use number of cores available on the machine; Here we use 1 process as the
#  task is not computationally expensive and using more processes would decrease the performance due to the IPC overhead.
es = EvolutionStrategy(model.get_weights(), get_reward, population_size=20, sigma=0.1, learning_rate=0.03, decay=0.995, num_threads=1)
es.run(1000, print_step=100)

Here's the output:

iter 100. reward: -68.819312
iter 200. reward: -0.218466
iter 300. reward: -0.110204
iter 400. reward: -0.001901
iter 500. reward: -0.000459
iter 600. reward: -0.000287
iter 700. reward: -0.000939
iter 800. reward: -0.000504
iter 900. reward: -0.000522
iter 1000. reward: -0.000178

Now we have the optimized weights and we can update our model:

optimized_weights = es.get_weights()
model.set_weights(optimized_weights)

Todo

  • Add distribution support over network
You might also like...
GEA - Code for Guided Evolution for Neural Architecture Search

Efficient Guided Evolution for Neural Architecture Search Usage Create a conda e

Let Python optimize the best stop loss and take profits for your TradingView strategy.

TradingView Machine Learning TradeView is a free and open source Trading View bot written in Python. It is designed to support all major exchanges. It

CryptoFrog - My First Strategy for freqtrade

cryptofrog-strategies CryptoFrog - My First Strategy for freqtrade NB: (2021-04-20) You'll need the latest freqtrade develop branch otherwise you migh

Code for
Code for "Learning the Best Pooling Strategy for Visual Semantic Embedding", CVPR 2021

Learning the Best Pooling Strategy for Visual Semantic Embedding Official PyTorch implementation of the paper Learning the Best Pooling Strategy for V

Improving adversarial robustness by a coupling rejection strategy

Adversarial Training with Rectified Rejection The code for the paper Adversarial Training with Rectified Rejection. Environment settings and libraries

An integration of several popular automatic augmentation methods, including OHL (Online Hyper-Parameter Learning for Auto-Augmentation Strategy) and AWS (Improving Auto Augment via Augmentation Wise Weight Sharing) by Sensetime Research.

An integration of several popular automatic augmentation methods, including OHL (Online Hyper-Parameter Learning for Auto-Augmentation Strategy) and AWS (Improving Auto Augment via Augmentation Wise Weight Sharing) by Sensetime Research.

This is a simple backtesting framework to help you test your crypto currency trading. It includes a way to download and store historical crypto data and to execute a trading strategy.

You can use this simple crypto backtesting script to ensure your trading strategy is successful Minimal setup required and works well with static TP a

[2021][ICCV][FSNet] Full-Duplex Strategy for Video Object Segmentation
[2021][ICCV][FSNet] Full-Duplex Strategy for Video Object Segmentation

Full-Duplex Strategy for Video Object Segmentation (ICCV, 2021) Authors: Ge-Peng Ji, Keren Fu, Zhe Wu, Deng-Ping Fan*, Jianbing Shen, & Ling Shao This

An adaptive hierarchical energy management strategy for hybrid electric vehicles
An adaptive hierarchical energy management strategy for hybrid electric vehicles

An adaptive hierarchical energy management strategy This project contains the source code of an adaptive hierarchical EMS combining heuristic equivale

Comments
  • Mirrored sampling.

    Mirrored sampling.

    https://github.com/alirezamika/evostra/blob/3819a3c1e9f16a99e90f874c141fddb3e26f18e9/evostra/algorithms/evolution_strategy.py#L30

    It is a useful idea to evaluate not only +gaussian noise, but also -gaussian noise. See https://hal.inria.fr/inria-00530202v2/document for details.

    opened by pushnyakov 0
  • Improve sampler.

    Improve sampler.

    https://github.com/alirezamika/evostra/blob/3819a3c1e9f16a99e90f874c141fddb3e26f18e9/evostra/algorithms/evolution_strategy.py#L44

    Actually, it makes sense to improve this step by the following. Let's assume that we are solving a huge optimization problem. What is the point of generating a random gaussian at each step? We can generate a huge list of gaussian at the very beginning of the training and at each step we just sample subset of given length from the already generated list of gaussians.

    Moreover, if a neural network is super huge (or our objective has a huge number of parameters) it might be costly to generate (or sample from already generated) gaussian at each step. We may do that for a small subset of weights (=parameters) which should significantly speed up convergence in the case of huge parameters space.

    opened by pushnyakov 0
  • Add GPU support

    Add GPU support

    Since one of the greatest strengths of Evolution Strategies is the parallelism it would be a real shame not to include the use of GPUs.

    https://weeraman.com/put-that-gpu-to-good-use-with-python-e5a437168c01

    Great code by the way.

    opened by cliftonarms 0
Owner
Mika
Mika
Official implement of Evo-ViT: Slow-Fast Token Evolution for Dynamic Vision Transformer

Evo-ViT: Slow-Fast Token Evolution for Dynamic Vision Transformer This repository contains the PyTorch code for Evo-ViT. This work proposes a slow-fas

YifanXu 53 Dec 5, 2022
Pytorch implementation of FlowNet 2.0: Evolution of Optical Flow Estimation with Deep Networks

flownet2-pytorch Pytorch implementation of FlowNet 2.0: Evolution of Optical Flow Estimation with Deep Networks. Multiple GPU training is supported, a

NVIDIA Corporation 2.8k Dec 27, 2022
This is the official pytorch implementation of Student Helping Teacher: Teacher Evolution via Self-Knowledge Distillation(TESKD)

Student Helping Teacher: Teacher Evolution via Self-Knowledge Distillation (TESKD) By Zheng Li[1,4], Xiang Li[2], Lingfeng Yang[2,4], Jian Yang[2], Zh

Zheng Li 9 Sep 26, 2022
Offical implementation for "Trash or Treasure? An Interactive Dual-Stream Strategy for Single Image Reflection Separation".

Trash or Treasure? An Interactive Dual-Stream Strategy for Single Image Reflection Separation (NeurIPS 2021) by Qiming Hu, Xiaojie Guo. Dependencies P

Qiming Hu 31 Dec 20, 2022
Genetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony Optimization Algorithm,Immune Algorithm, Artificial Fish Swarm Algorithm, Differential Evolution and TSP(Traveling salesman)

scikit-opt Swarm Intelligence in Python (Genetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony Algorithm, Immune Algorithm,A

郭飞 3.7k Jan 3, 2023
Code for the paper Task Agnostic Morphology Evolution.

Task-Agnostic Morphology Optimization This repository contains code for the paper Task-Agnostic Morphology Evolution by Donald (Joey) Hejna, Pieter Ab

Joey Hejna 18 Aug 4, 2022
This implements one of result networks from Large-scale evolution of image classifiers

Exotic structured image classifier This implements one of result networks from Large-scale evolution of image classifiers by Esteban Real, et. al. Req

null 54 Nov 25, 2022
Evolution Strategies in PyTorch

Evolution Strategies This is a PyTorch implementation of Evolution Strategies. Requirements Python 3.5, PyTorch >= 0.2.0, numpy, gym, universe, cv2 Wh

Andrew Gambardella 333 Nov 14, 2022
Embodied Intelligence via Learning and Evolution

Embodied Intelligence via Learning and Evolution This is the code for the paper Embodied Intelligence via Learning and Evolution Agrim Gupta, Silvio S

Agrim Gupta 111 Dec 13, 2022
An atmospheric growth and evolution model based on the EVo degassing model and FastChem 2.0

EVolve Linking planetary mantles to atmospheric chemistry through volcanism using EVo and FastChem. Overview EVolve is a linked mantle degassing and a

Pip Liggins 2 Jan 17, 2022