jenkspt / CMA-ES

A short implementation and demonstration of the Covariance Matrix Adaptation algorithm in numpy
10 stars 2 forks source link

Covariance Matrix Adaptation - Evolutionary Strategy (CMA-ES)

Surface Plot of Rastrigin Function

"Rastrigin Function"

def rastrigin(X, A=10):
    return A + np.sum((X**2 - A * np.cos(2 * np.pi * X)), -1)

The Core Algorithm

X = np.random.normal(0,1.24, (d, n))
fitness = function(X.T)

centered = topk - X.mean(1, keepdims=True) C = (centered @ centered.T)/(k-1)

* Sample the new population for the next iteration from this covariance
matrix using the mean of the top k
```python

w, E = la.eigh(C)
N = np.random.normal(size=(d,n))
X = topk.mean(1,keepdims=True) + (E @ np.diag(np.sqrt(w)) @ N)

"CMA-ES Rastrigin"

Initialization:

n = 100     # Population size
d = 2       # Dimensions
k = 25      # Size of elite population

# Initial random sample
X = np.random.normal(0,1.24, (d, n))

*Note the official implementation of CMA-ES should be used for any actual use cases.