Creating Artificial Life with Reinforcement Learning

Overview

Code and instructions for creating Artificial Life in a non-traditional way, namely with Reinforcement Learning instead of Evolutionary Algorithms.

Although Evolutionary Algorithms have shown to result in interesting behavior, they focus on learning across generations whereas behavior could also be learned during ones lifetime. This is where Reinforcement Learning comes in, which learns through a reward/punishment system that allows it to learn new behavior during its live time. Using Reinforcement Learning, entities learn to survive, reproduce, and make sure to maximize the fitness of their kin.

Table of Contents

  1. About the Project
  2. Getting Started
    2.1. Prerequisites
    2.2. Usage
    2.3. Google Colaboratory
  3. Environment
    3.1. Agents
    3.2. Observation
    3.3. Reward
    3.4. Algorithms
  4. Results
  5. Documentation
    5.1. Training
    5.2. Testing

1. About the Project

Back to ToC
The simulation above is a good summary of what this project is about. Entities move and learn independently, eat, attack other entities, and reproduce. This is all possible by applying Reinforcement Learning algorithms to each entity, such as DQN and PPO.

The general principle is simple, each entity starts by randomly executing some actions and will slowly learn, based on specific rewards, whether those actions helped or not. The entity is punished if the action is poor and rewarded if it was helpful.

It is then up to the entities to find a way to survive as long as possible while also making sure their kin is in good shape as possible.


2. Getting Started

Back to ToC

To get started, you will only need to install the requirements and fork/download the ReinLife package, together with the train.py and test.py files.

2.1. Prerequisites

To install the requirements, simply run the following:
pip install -r requirements.txt

2.2. Usage

Due to the many parameters within each model and the environment itself, it is advised to start with train.py and test.py. These files have been prepared such that you can run them as is.

Training

To train one or models, simply run:

from ReinLife.Models import PERD3QN
from ReinLife.Helpers import trainer

brains = [PERD3QN(), 
          PERD3QN()]

trainer(brains, n_episodes=15_000, update_interval=300, width=30, height=30, max_agents=100,
        visualize_results=True, print_results=False, static_families=False, training=True, save=True)

This will start training the models for 15_000 episodes. The most important variable here is static_families. If this is set to True, then there will be at most as many genes as the number of brains chosen. Thus, you will only see two colors. If you set this to False, then any number of genes will be created each with their own brain.

Testing

To test one or models, simply run:

from ReinLife import tester
from ReinLife.Models import DQN, D3QN, PERD3QN, PPO, PERDQN

main_brains = [PPO(load_model="pretrained/PPO/PPO/brain_gene_0.pt"),
               DQN(load_model="pretrained/DQN/DQN/brain_gene_0.pt", training=False),
               D3QN(load_model="pretrained/D3QN/D3QN/brain_gene_0.pt", training=False),
               PERD3QN(load_model="pretrained/PERD3QN/Static Families/PERD3QN/brain_gene_1.pt", training=False),
               PERDQN(load_model="pretrained/PERDQN/PERDQN/brain_gene_1.pt", training=False)]
tester(main_brains, width=30, height=30, max_agents=100, static_families=True, fps=10)

The models above are pre-trained (see results below).
You can choose any number of brains that you have trained previously. Note, make sure to set all models (except PPO) to training=False, otherwise it will demonstrate more random behavior.

2.3. Google Colaboratory

It is possible to run the training code in google colaboratory if you need more computing power. You start by installing pygame and cloning the repo:

!pip install pygame
!git clone https://github.com/MaartenGr/ReinLife.git
%cd ReinLife

After that, you are ready to run the training code:

from ReinLife.Models import PERD3QN
from ReinLife.Helpers import trainer

n_episodes = 15_000

brains = [PERD3QN(train_freq=10), PERD3QN(train_freq=10)]

env = trainer(brains, n_episodes=n_episodes, update_interval=300, width=30, height=30, max_agents=100,
        visualize_results=True, print_results=False, google_colab=True, render=False, static_families=True,
        training=True, save=True)

Then, simply look at the files on the left in ReinLife/experiments/... to find the experiment that was run.


3. Environment

Back to TOC

The environment is build upon a numpy matrix of size n * m where each grid has a pixel size of 24 by 24. Each location within the matrix represents a location which can be occupied by only a single entity.

3.1. Agents

Agents are entities or organisms in the simulation that can move, attack, reproduce, and act independently.

Each agent has the following characteristics:

  • Health
    • Starts at 200 and decreases with 10 each step
    • Their health cannot exceed 200
  • Age
    • Starts at 0 and increases 1 with each step
    • Their maximum age is 50, after which they die
  • Gene
    • Each agents is given a gene, which simply represents an integer
    • All their offspring have the same gene value
    • Any new agent that is created not through reproduction gets a new value
    • This gene is represented by the color of the body

An agent can perform one of the following eight actions:

  • Move one space left, right, up, or down
  • Attack in the left, right, up, or down direction

The order of action execution is as follows:

  • Attack -> Move -> Eat -> Reproduce

Movement

An agent can occupy any un-occupied space and, from that position, can move up, down, left or right. Entities cannot move diagonally. The environment has no walls, which means that if an entity moves left from the most left position in the numpy matrix, then it will move to the most right position. In other words, the environment is a fully-connected world.

Although the movement in itself is not complex, it becomes more difficult as multiple entities want to move into the same spot. For that reason, each entity checks whether the target coordinate is unoccupied and if no other entity wants to move in that space. It does this iteratively as the target coordinate changes if an entity cannot move.

Attacking

An agent can attack in one of four directions:

  • Up, Down, Left, or Right

They stand still if they attack. However, since it is the first thing they do, the other agent cannot move away. When the agent successfully attacks another agent, the other agent dies and the attacker increases its health. Moreover, if the agent successfully attacks another agent, its border becomes red.

(Re)production

Each agent learns continuously during its lifetime. The end of an episode is marked by the end of an agents life.

When a new entity is reproduced, it inherits its brain (RL-algorithm) from its parents.

When a new entity is produced, it inherits its brain (RL-algorithm) from one of the best agents we have seen so far. A list of 10 of the best agents is tracked during the simulation.

3.2. Observation

The field of view of each agent is a square surrounding the agent. Since the world is fully-connected, the agent can see "through" walls.

The input for the neural network can be see in the image below:

test

There are three grids of 7x7 (example shows 5x5) that each show a specific observation of the environment:

  • Health
    • Shows the health of all agents within the agent's fov
  • Kinship
    • Shows whether agents within the agent's fov are related to the agent
  • Nutrition
    • Shows the nutritrional value of food items within the agent's fov

Thus, there are 3 * (7 * 7) + 6 = 153 input values.

3.3. Reward

The reward structure is tricky as you want to minimize the amount you steer the entity towards certain behavior. For that reason, I've adopted a simple and straightforward fitness measure, namely:

test

Where r is the reward given to agent i at time t. The δ is the Kronecker delta which is one if the the gene of agent i, gi, equals the gene of agent j, gj, and zero otherwise. n is the total number of agents that are alive at time t. Thus, the reward essentially checks how many agents are alive that share a gene with agent i at time t and divides by the total number of agents alive.

The result is that an agent's behavior is only steered towards making sure its gene lives on for as long as possible.

3.4. Algorithms

Currently, the following algorithms are implemented that can be used as brains:

  • Deep Q Network (DQN)
  • Prioritized Experience Replay Deep Q Network (PER-DQN)
  • Double Dueling Deep Q Network (D3QN)
  • Prioritized Experience Replay Double Dueling Deep Q Network (PER-D3QN)
  • Proximal Policy Optimization (PPO)

4. Results

Back to TOC

In order to test the quality of the trained algorithms, I ran each algorithm independently against a copy of itself to test the speed at which they converge to a high fitness. Below, you can see all algorithms battling it out with PER-D3QN coming out on top. Note, this does not mean it is necessarily the best algorithm. It might have converged faster than others which limits their learning ability.

test

Moreover, for each algorithm, I ran simulations with and without static families.

DQN

With static families

PER-DQN

With static families

D3QN

With static families

PER-D3QN

With static families
With static families

PPO

With static families

5. Documentation

Back to TOC

5.1. Training

The parameters for train.py:

Parameter Description Default value
brains Contains a list of brains defined as Agents by the ReinLife.Models folder.
n_episodes The number of epsiodes to run the training sequence. 10_000
width, height The width and height of the environment. 30, 30
visualize_results Whether to visualize the results interactively in matplotlib. False
google_colab If you want to visualize your results interactively in google_colab, also set this parameter to True as well as the one above. False
update_interval The interval at which average the results 500
print_results Whether to print the results to the console True
max_agents The maximum number of agents can occupy the environment. 100
render Whether to render the environment in pygame whilst training. False
static_families Whether you want a set number of families to be used. Each family has its own brain defined by the models in the variable brains. False
training Whether you want to train using the settings above or simply show the result. True
limit_reproduction If False, agents can reproduce indefinitely. If True, all agents can only reproduce once. False
incentivize_killing Whether to incentivize killing by adding 0.2 everytime an agent kills another True

5.2. Testing

The parameters for test.py:

Parameter Description Default value
brains Contains a list of brains defined as Agents by the ReinLife.Models folder.
width, height The width and height of the environment. 30, 30
pastel_colors Whether to automatically generate random pastel colors False
max_agents The maximum number of agents can occupy the environment. 100
static_families Whether you want a set number of families to be used. Each family has its own brain defined by the models in the variable brains. False
limit_reproduction If False, agents can reproduce indefinitely. If True, all agents can only reproduce once. False
fps Frames per second 10

Other work

ReinLife was based on:

  • Abrantes, J. P., Abrantes, A. J., & Oliehoek, F. A. (2020). Mimicking Evolution with Reinforcement Learning. arXiv preprint arXiv:2004.00048.
You might also like...
Wordplay, an artificial Intelligence based crossword puzzle solver.

Wordplay, AI based crossword puzzle solver A crossword is a word puzzle that usually takes the form of a square or a rectangular grid of white- and bl

Artificial Intelligence playing minesweeper 🤖
Artificial Intelligence playing minesweeper 🤖

AI playing Minesweeper ✨ Minesweeper is a single-player puzzle video game. The objective of the game is to clear a rectangular board containing hidden

Framework that uses artificial intelligence applied to mathematical models to make predictions
Framework that uses artificial intelligence applied to mathematical models to make predictions

LiconIA Framework that uses artificial intelligence applied to mathematical models to make predictions Interface Overview Table of contents [TOC] 1 Ar

Artificial Intelligence search algorithm base on Pacman
Artificial Intelligence search algorithm base on Pacman

Pacman Search Artificial Intelligence search algorithm base on Pacman Source The Pacman Projects by the University of California, Berkeley. Layouts Di

AI Flow is an open source framework that bridges big data and artificial intelligence.
AI Flow is an open source framework that bridges big data and artificial intelligence.

Flink AI Flow Introduction Flink AI Flow is an open source framework that bridges big data and artificial intelligence. It manages the entire machine

Inteligência artificial criada para realizar interação social com idosos.

IA SONIA 4.0 A SONIA foi inspirada no assistente mais famoso do mundo e muito bem conhecido JARVIS. Todo mundo algum dia ja sonhou em ter o seu própri

Python Rapid Artificial Intelligence Ab Initio Molecular Dynamics

Python Rapid Artificial Intelligence Ab Initio Molecular Dynamics

With this package, you can generate mixed-integer linear programming (MIP) models of trained artificial neural networks (ANNs) using the rectified linear unit (ReLU) activation function

With this package, you can generate mixed-integer linear programming (MIP) models of trained artificial neural networks (ANNs) using the rectified linear unit (ReLU) activation function. At the moment, only TensorFlow sequential models are supported. Interfaces to either the Pyomo or Gurobi modeling environments are offered.

I created My own Virtual Artificial Intelligence named genesis, He can assist with my Tasks and also perform some analysis,,

Virtual-Artificial-Intelligence-genesis- I created My own Virtual Artificial Intelligence named genesis, He can assist with my Tasks and also perform

Comments
  • Bump numpy from 1.17.4 to 1.22.0

    Bump numpy from 1.17.4 to 1.22.0

    Bumps numpy from 1.17.4 to 1.22.0.

    Release notes

    Sourced from numpy's releases.

    v1.22.0

    NumPy 1.22.0 Release Notes

    NumPy 1.22.0 is a big release featuring the work of 153 contributors spread over 609 pull requests. There have been many improvements, highlights are:

    • Annotations of the main namespace are essentially complete. Upstream is a moving target, so there will likely be further improvements, but the major work is done. This is probably the most user visible enhancement in this release.
    • A preliminary version of the proposed Array-API is provided. This is a step in creating a standard collection of functions that can be used across application such as CuPy and JAX.
    • NumPy now has a DLPack backend. DLPack provides a common interchange format for array (tensor) data.
    • New methods for quantile, percentile, and related functions. The new methods provide a complete set of the methods commonly found in the literature.
    • A new configurable allocator for use by downstream projects.

    These are in addition to the ongoing work to provide SIMD support for commonly used functions, improvements to F2PY, and better documentation.

    The Python versions supported in this release are 3.8-3.10, Python 3.7 has been dropped. Note that 32 bit wheels are only provided for Python 3.8 and 3.9 on Windows, all other wheels are 64 bits on account of Ubuntu, Fedora, and other Linux distributions dropping 32 bit support. All 64 bit wheels are also linked with 64 bit integer OpenBLAS, which should fix the occasional problems encountered by folks using truly huge arrays.

    Expired deprecations

    Deprecated numeric style dtype strings have been removed

    Using the strings "Bytes0", "Datetime64", "Str0", "Uint32", and "Uint64" as a dtype will now raise a TypeError.

    (gh-19539)

    Expired deprecations for loads, ndfromtxt, and mafromtxt in npyio

    numpy.loads was deprecated in v1.15, with the recommendation that users use pickle.loads instead. ndfromtxt and mafromtxt were both deprecated in v1.17 - users should use numpy.genfromtxt instead with the appropriate value for the usemask parameter.

    (gh-19615)

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Owner
Maarten Grootendorst
Data Scientist | Psychologist
Maarten Grootendorst
This project uses reinforcement learning on stock market and agent tries to learn trading. The goal is to check if the agent can learn to read tape. The project is dedicated to hero in life great Jesse Livermore.

Reinforcement-trading This project uses Reinforcement learning on stock market and agent tries to learn trading. The goal is to check if the agent can

Deepender Singla 1.4k Dec 22, 2022
Conservative Q Learning for Offline Reinforcement Reinforcement Learning in JAX

CQL-JAX This repository implements Conservative Q Learning for Offline Reinforcement Reinforcement Learning in JAX (FLAX). Implementation is built on

Karush Suri 8 Nov 7, 2022
Reinforcement-learning - Repository of the class assignment questions for the course on reinforcement learning

DSE 314/614: Reinforcement Learning This repository containing reinforcement lea

Manav Mishra 4 Apr 15, 2022
Real life contra a deep learning project built using mediapipe and openc

real-life-contra Description A python script that translates the body movement into in game control. Welcome to all new real life contra a deep learni

Programminghut 7 Jan 26, 2022
An AI made using artificial intelligence (AI) and machine learning algorithms (ML) .

DTech.AIML An AI made using artificial intelligence (AI) and machine learning algorithms (ML) . This is created by help of some members in my team and

null 1 Jan 6, 2022
Python-experiments - A Repository which contains python scripts to automate things and make your life easier with python

Python Experiments A Repository which contains python scripts to automate things

Vivek Kumar Singh 11 Sep 25, 2022
Art Project "Schrödinger's Game of Life"

Repo of the project "Team Creative Quantum AI: Schrödinger's Game of Life" Installation new conda env: conda create --name qcml python=3.8 conda activ

ℍ◮ℕℕ◭ℍ  ℝ∈ᛔ∈ℝ 2 Sep 15, 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
simple artificial intelligence utilities

Simple AI Project home: http://github.com/simpleai-team/simpleai This lib implements many of the artificial intelligence algorithms described on the b

null 921 Dec 8, 2022
An Artificial Intelligence trying to drive a car by itself on a user created map

An Artificial Intelligence trying to drive a car by itself on a user created map

Akhil Sahukaru 17 Jan 13, 2022