{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "zibeebvdRm8M"
},
"source": [
"# Evolutionary Operations\n",
"\n",
"[](https://colab.research.google.com/github/google/pyglove/blob/main/docs/notebooks/intro/search/evolution_ops.ipynb)\n",
"\n",
"PyGlove provides a rich set of operations for creating evolutionary algorithms.\n",
"This notebook explains them through examples. To understand how an evolutionary operation works within an evolutionary algorithm, please see [Evolution Algorithm](https://colab.research.google.com/github/google/pyglove/blob/main/docs/notebooks/intro/search/evolution_algorithm.ipynb)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4XFfnnRsrBvu"
},
"outputs": [],
"source": [
"!pip install pyglove"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yJ_3TkVqrDe2"
},
"outputs": [],
"source": [
"import pyglove as pg"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "S0giqROSvC4K"
},
"source": [
"## Preparation\n",
"\n",
"To make examples easy to understand, we use the same DNA list as the input for all operations unless individual cells overrule."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529813779,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "hqRHwQyr2KO7",
"outputId": "8a93c44a-5467-46f4-ebb7-06541031aba1"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[DNA(0), DNA(1), DNA(2), DNA(3), DNA(4), DNA(5), DNA(6), DNA(7), DNA(8), DNA(9)]\n"
]
}
],
"source": [
"dna_spec = pg.dna_spec(pg.oneof(range(10)))\n",
"inputs = [pg.evolution.set_fitness(pg.DNA(i, spec=dna_spec), i) for i in range(10)]\n",
"print(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "J8K0kGK2WPek"
},
"source": [
"\n",
"## Generic Operations\n",
"\n",
"Generic operations are operations that work with any element types, which can be chained together for representing a complex process.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5n16yaE3rMwi"
},
"source": [
"\n",
"### **Pipeline**: chains operations together\n",
"\n",
"For example, to find the fittest item among the 3 items randomly chosen from the input, we can do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529813958,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "97EczQj3rO7z",
"outputId": "2cad496f-9f5f-462f-dba3-3631bdec51d8"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(4)]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Pipeline the randomly selected DNAs to Top1.\n",
"(pg.evolution.selectors.Random(3, seed=1) >> pg.evolution.selectors.Top(1))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XIVFnXC63DIQ"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529814159,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "GdlmeXZ03F26",
"outputId": "c3aaf999-4e3b-4a73-ecf9-de009415ce11"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(4)]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Pipeline([\n",
" pg.evolution.selectors.Random(3, seed=1),\n",
" pg.evolution.selectors.Top(1)\n",
"])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9TJsdNcKwc9F"
},
"source": [
"\n",
"### **Union**: unions the outputs of operations based on the same input\n",
"\n",
"For example, find top 1 item unioned with the first 3 items from the input."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 57,
"status": "ok",
"timestamp": 1658529814380,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "rNV1cQ1gwpTJ",
"outputId": "d2d54f24-458d-4097-83b7-425cfc794f70"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(0), DNA(1), DNA(2)]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(1) | pg.evolution.selectors.First(3))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QWJ12zHcw455"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 53,
"status": "ok",
"timestamp": 1658529814563,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "xQg9EbTmxImJ",
"outputId": "868d3996-cd2b-4e47-e0f5-33c5c5ae3465"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(0), DNA(1), DNA(2)]"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Union([\n",
" pg.evolution.selectors.Top(1),\n",
" pg.evolution.selectors.First(3)\n",
"])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WQ5BJex3xvxw"
},
"source": [
"\n",
"### **Intersection**: intersects the outputs of operations based on the same input\n",
"\n",
"For example, Find within first 6 items whose fitnesses are among the top 6:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529814745,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "lzmVzPZ0yBiW",
"outputId": "cc20a856-4960-4b15-d301-846f6e26642c"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(5), DNA(4)]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(6) & pg.evolution.selectors.First(6))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0_cqLGM-yLq1"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529814948,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "-dcTuWOeyQxJ",
"outputId": "9075979a-6508-41f3-f21a-02728031292f"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(5), DNA(4)]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Intersection([\n",
" pg.evolution.selectors.Top(6),\n",
" pg.evolution.selectors.First(6)\n",
"])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oglWncSwyX0E"
},
"source": [
"\n",
"\n",
"### **Difference**: computes the difference between operation outputs\n",
"\n",
"For example: Find top 5 items that is not among the first 6 items:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529815129,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "FqEr3n9pzBeG",
"outputId": "a14a9c0e-91ec-49e7-a8c7-73d2d001e2ea"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(8), DNA(7), DNA(6)]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(5) - pg.evolution.selectors.First(6))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "n2it70l0zG04"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529815343,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "6C-ynVb5zNPD",
"outputId": "1451dada-ea24-47b6-ae2f-15d7ec251777"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(8), DNA(7), DNA(6)]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Difference([\n",
" pg.evolution.selectors.Top(5),\n",
" pg.evolution.selectors.First(6),\n",
"])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NWRuQE4Vzf_H"
},
"source": [
"\n",
"\n",
"### **Symmetric Difference**: Computes the items that appear only once among the operation outputs\n",
"\n",
"For example, items are either in top 6 or within last 5, but not both:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529815544,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "AVXGy1Ko4Rbb",
"outputId": "3613d2ab-d6b7-478e-9e2e-b64b6c96f459"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(4)]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(6) ^ pg.evolution.selectors.Last(5))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pXh9uU0OzjU7"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 57,
"status": "ok",
"timestamp": 1658529815760,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "n0ziXc9d4m4P",
"outputId": "9c13d523-df30-4c5d-bbd6-8ac757518c94"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(4)]"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.SymmetricDifference([\n",
" pg.evolution.selectors.Top(6),\n",
" pg.evolution.selectors.Last(5)\n",
"])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "63PZXahFTP41"
},
"source": [
"\n",
"### **Concatenation**: Concatenates the outputs of multiple operations\n",
"\n",
"For example: the top 5 items and the last 3 items (Items that match both condition will be duplicated):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529815982,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "MSy1t47HTmHw",
"outputId": "192f9317-7751-45b5-d2e7-ac0d1c4ab59a"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(8), DNA(7), DNA(6), DNA(5), DNA(7), DNA(8), DNA(9)]"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(5) + pg.evolution.selectors.Last(3))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cyqGJ7UMTs0z"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 57,
"status": "ok",
"timestamp": 1658529816162,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "dIC6JfUzTuEf",
"outputId": "4c901be8-ec45-454a-f8b6-8797b47e7d0a"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(8), DNA(7), DNA(6), DNA(5), DNA(7), DNA(8), DNA(9)]"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Concatenation([\n",
" pg.evolution.selectors.Top(5), \n",
" pg.evolution.selectors.Last(3)\n",
"])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qQc60WOUU0JD"
},
"source": [
"\n",
"\n",
"### **Repeat**: Repeats an operation multiple times on the same input and concatenate the outputs\n",
"\n",
"For example, selecting the top 1 candidate and generate 3 children by mutating it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529816357,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "6DNlFGCDXeSQ",
"outputId": "299c2122-8b9e-46bf-8e2f-fdf5f9ce422b"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(4), DNA(7)]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(1) >> pg.evolution.mutators.Uniform(seed=1) * 3)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eCBIm6JVXm56"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529816561,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "SdiDOe8VXoU1",
"outputId": "0d5be322-b073-458b-9e85-be308fc39092"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(4), DNA(7)]"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Pipeline([\n",
" pg.evolution.selectors.Top(1),\n",
" pg.evolution.Repeat(pg.evolution.mutators.Uniform(seed=1), 3)\n",
"])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nZk7VlxPY5rp"
},
"source": [
"\n",
"### **Power**: Chains an operation itself multiple times\n",
"\n",
"For example, mutate the top 1 DNA 3 times:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 57,
"status": "ok",
"timestamp": 1658529816761,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "noWCfxzVT1Fd",
"outputId": "60d2b71e-e61e-4722-c055-e689cfa7f190"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(7)]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(1) >> pg.evolution.mutators.Uniform(seed=1) ** 3)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Q0X9eeaMT_Pv"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529816958,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "rU74Y5nWUAXv",
"outputId": "38613268-1fbc-43a3-eaaa-a559d5f4cc2b"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(7)]"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Pipeline([\n",
" pg.evolution.selectors.Top(1),\n",
" pg.evolution.Power(pg.evolution.mutators.Uniform(seed=1), 3)\n",
"])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ml25CwrxVMyx"
},
"source": [
"\n",
"### **Inversion/Negation**: Computes the complementary set of the operation output based on the input\n",
"\n",
"For example, items that are not within the top 5:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529817148,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "B6QZ0Cq7VkuU",
"outputId": "96473669-6317-4cea-96d3-15519e4baa8b"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0), DNA(1), DNA(2), DNA(3), DNA(4)]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(~pg.evolution.selectors.Top(5))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7obCQayUVrRC"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529817327,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "_6-MdOFmVsea",
"outputId": "f4e271d7-6e21-444c-c960-399c36eede99"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0), DNA(1), DNA(2), DNA(3), DNA(4)]"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(-pg.evolution.selectors.Top(5))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rsSlzDD8VwdG"
},
"source": [
"which is also equivalent to:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 139,
"status": "ok",
"timestamp": 1658529817670,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "qMy9qKlxVzo_",
"outputId": "9a62f051-a292-427f-970c-13414ecf47f5"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0), DNA(1), DNA(2), DNA(3), DNA(4)]"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.Identity() - pg.evolution.selectors.Top(5))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DAt6HkX6V6nR"
},
"source": [
"\n",
"### **Slice**: A slice of the input as the output\n",
"\n",
"For example, the first 2 elements from 5 random items:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 59,
"status": "ok",
"timestamp": 1658529817863,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "eRwtr_FuWEq8",
"outputId": "3b4a278d-00d2-4d7e-c058-f121eb05e43a"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(2), DNA(1)]"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Random(5, seed=1)[:2])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wvkCQmfzWr8c"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529818062,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "cdfzUpseWxTy",
"outputId": "e494271a-5cc8-4dec-ceaa-1fba80d7788f"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(2), DNA(1)]"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Slice(\n",
" pg.evolution.selectors.Random(5, seed=1),\n",
" slice(2))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NQj8ugJ6WRvw"
},
"source": [
"`Slice` can also work with a single integer as the index for requested item, which generates an output list of 1 element."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 72,
"status": "ok",
"timestamp": 1658529818276,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "TNzrTqzsWNmK",
"outputId": "c7a434a0-ad89-45d7-8394-127e0728b004"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(1)]"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Random(5, seed=1)[1])(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jkgRtgZ3XDQU"
},
"source": [
"\n",
"### **Identity**: Returns the input as the output\n",
"\n",
"For example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529818519,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "N-15ms7VXKX6",
"outputId": "2b196042-7dad-4be2-d3eb-fbe9b5cedada"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0),\n",
" DNA(1),\n",
" DNA(2),\n",
" DNA(3),\n",
" DNA(4),\n",
" DNA(5),\n",
" DNA(6),\n",
" DNA(7),\n",
" DNA(8),\n",
" DNA(9)]"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Identity()(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "keEAFvpUXPbR"
},
"source": [
"\n",
"### **Lambda**: Wraps a user function into a `Operator`.\n",
"\n",
"For example, return all the even-indexed items:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529818695,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "Jm5JFuENXdtF",
"outputId": "0766c7f7-f434-4b1a-afdb-880d193c0d16"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0), DNA(2), DNA(4), DNA(6), DNA(8)]"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.Lambda(lambda x: x[::2]))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KrbhctjdXpm6"
},
"source": [
"`pg.evolution.Lambda` is often used when we want to chain multiple user functions together, or combine with built-in operations. For example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529818914,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "k0CmcHIsX7-t",
"outputId": "e99057d4-3938-4830-a123-1b0934e9a907"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0),\n",
" DNA(1),\n",
" DNA(2),\n",
" DNA(3),\n",
" DNA(4),\n",
" DNA(5),\n",
" DNA(6),\n",
" DNA(7),\n",
" DNA(8),\n",
" DNA(9)]"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.Lambda(lambda x: x[::2]).with_prob(0.1, seed=1))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "IJFfs7dwYTbo"
},
"source": [
"\n",
"### **Choice**: Pipeline a sequence of operations with probabilities.\n",
"\n",
"How `Choice` works is to visit each sub-operation in order, and draw lots (generate a random number within [0, 1]) to determine whether to execute current operation or not. The execution will stop either when all operations have been visited, or the `limit` of the number of operations to execute is reached.\n",
"\n",
"For example, random select one element or choose the top 1 element with equal probability:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 53,
"status": "ok",
"timestamp": 1658529819122,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "4DSggm8JZb08",
"outputId": "24ce6e09-b48c-41d2-c89b-2249cd4443f3"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9)]"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.Choice([\n",
" (pg.evolution.selectors.Random(1, seed=1), 0.5),\n",
" (pg.evolution.selectors.Top(1), 1.0),\n",
"], limit=1)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "EYG7Fn4yZsU7"
},
"source": [
"If there is no limit, the `Top` operation will continue to apply on top of `Random`'s output when the first operation is executed.\n",
"\n",
"`Choice` also power `Operation.with_prob()` for chaining the operations:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "P-ZlKZA0aHBI"
},
"outputs": [],
"source": [
"def with_prob(self, prob):\n",
" return pg.evolution.Choice([\n",
" (self, prob)\n",
" ])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SRfJ5YoCajKm"
},
"source": [
"\n",
"### **Conditional**: Conditional execution based on a predicate.\n",
"\n",
"For example, if current step is greater than 10, choose top 3 items, otherwise choose random 5 items:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529819471,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "PQWgG5IIa21a",
"outputId": "7e07c4b0-b882-4ee7-819a-f3c0c5f24a83"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(2), DNA(1), DNA(4), DNA(0), DNA(3)]"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"op = pg.evolution.Conditional(\n",
" lambda xs, step: step > 10,\n",
" pg.evolution.selectors.Top(3),\n",
" pg.evolution.selectors.Random(5, seed=1))\n",
"op(inputs, step=4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529819649,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "jTYWcSe3bEkL",
"outputId": "656797bc-c21b-410a-89fa-06af0d6cf126"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(8), DNA(7)]"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"op(inputs, step=11)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dgwC0jF6bIRx"
},
"source": [
"`Conditional` also power `Operation.if_true()` and `Operation.if_false()`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GuMOy4lHbWAo"
},
"outputs": [],
"source": [
"def if_true(self, predicate):\n",
" return pg.evolution.Conditional(\n",
" predicate,\n",
" self, \n",
" pg.evolution.Identity())"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MJpY0LTqbjK9"
},
"source": [
"\n",
"### **ElementWise**: Perform an operation on each child (which is a list)\n",
"\n",
"For example, random select 2 groups from 5 DNA groups, for each selected group, select the top 1 individual:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529820003,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "jmf-3_8McMcq",
"outputId": "8abc840e-8c54-4054-cf6d-4f5d7a7104e1"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[DNA(0), DNA(1), DNA(2)], [DNA(1), DNA(2), DNA(3)], [DNA(2), DNA(3), DNA(4)], [DNA(3), DNA(4), DNA(5)], [DNA(4), DNA(5), DNA(6)]]\n"
]
}
],
"source": [
"custom_inputs = [\n",
" [pg.evolution.set_fitness(pg.DNA(i + j), i + j) for i in range(3)]\n",
" for j in range(5)\n",
"]\n",
"print(custom_inputs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529820211,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "9g1tJcaMchl3",
"outputId": "5a147174-5641-4803-8afc-389b31f52b6f"
},
"outputs": [
{
"data": {
"text/plain": [
"[[DNA(3)], [DNA(2)]]"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Random(2, seed=1)\n",
" >> pg.evolution.ElementWise(pg.evolution.selectors.Top(1)))(custom_inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zMDMq3Smc74b"
},
"source": [
"This can also be expressed as:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529820399,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "DudjmqNZc-ty",
"outputId": "8b595db0-cbc9-4772-9fea-de79f5379b12"
},
"outputs": [
{
"data": {
"text/plain": [
"[[DNA(3)], [DNA(2)]]"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Random(2, seed=1).for_each(\n",
" pg.evolution.selectors.Top(1))(custom_inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jO3oqYwjdGrh"
},
"source": [
"\n",
"### **Flatten**: Flatten nested lists into a flat list\n",
"\n",
"For example, to flatten the outputs from previous example, we can do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529820578,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "5wA5NN07df9u",
"outputId": "c8461155-8310-4bb1-f534-3d98e9b8bc59"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(3), DNA(2)]"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Random(2, seed=1) \n",
" >> pg.evolution.ElementWise(pg.evolution.selectors.Top(1))\n",
" >> pg.evolution.Flatten())(custom_inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NkQwXKnueAkh"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 53,
"status": "ok",
"timestamp": 1658529820770,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "ITM5rKy0dbms",
"outputId": "1e1be92c-2640-4985-8765-21790b5aa933"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(3), DNA(2)]"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Random(2, seed=1).for_each(\n",
" pg.evolution.selectors.Top(1)).flatten()(custom_inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fmU2FwWyeD_J"
},
"source": [
"`Flatten` supports an argument `max_level`, which specifies the maximum level to flatten, for example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529820948,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "X3wKyTXKeUod",
"outputId": "0c59c86f-b1bc-4ba6-c323-a172af3983fb"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[[DNA(0), DNA(1)], [DNA(1), DNA(2)]], [[DNA(0), DNA(1)], [DNA(1), DNA(2)]]]\n",
"[[DNA(0), DNA(1)], [DNA(1), DNA(2)], [DNA(0), DNA(1)], [DNA(1), DNA(2)]]\n",
"[DNA(0), DNA(1), DNA(1), DNA(2), DNA(0), DNA(1), DNA(1), DNA(2)]\n"
]
}
],
"source": [
"custom_inputs = [[\n",
" [pg.evolution.set_fitness(pg.DNA(i + j), i + j) for i in range(2)]\n",
" for j in range(2)]\n",
" for k in range(2)]\n",
"\n",
"print(custom_inputs)\n",
"print(pg.evolution.Flatten(max_level=1)(custom_inputs))\n",
"print(pg.evolution.Flatten(max_level=2)(custom_inputs))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "g4VsX9bDfFz8"
},
"source": [
"\n",
"### **UntilChange**: Repeat the operation on the input until the output has a difference from its input\n",
"\n",
"For example, mutate the input DNA until the output DNA is different from the input:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529821128,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "Z7kygSgPfluP",
"outputId": "5bb496d0-f15f-470a-a22f-6fedde69e50a"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(4)]"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(1) \n",
" >> pg.evolution.UntilChange(\n",
" pg.evolution.mutators.Uniform(seed=1).with_prob(0.01)))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "vGNZzj65f3dZ"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529821323,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "j5YScJvef4uZ",
"outputId": "02a2cddb-0f00-40c8-e42b-6e4862602f0d"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(4)]"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(1) \n",
" >> pg.evolution.mutators.Uniform(seed=1).with_prob(0.01).until_change())(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0ctvgrTugEcY"
},
"source": [
"`UntilChange` also allows the user to specify a `max_attempts`, for example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529821501,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "kY-iKBqDf_78",
"outputId": "e0fd0963-3ad6-438a-cd9e-1d404cfe4468"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9)]"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(1) \n",
" >> pg.evolution.mutators.Uniform(seed=1).with_prob(0.01).until_change(\n",
" max_attempts=2))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MT-YVlfRmwPh"
},
"source": [
"\n",
"### **GlobalStateSetter**: Set a value to the global state with a key\n",
"\n",
"For most common evolutionary algorithms, reproduction is simply a procedure of list processing based on current population. Complex evolutionary algorithms, such as NEAT, NSGA2, however, are based on clusters of individuals, like species, frontiers, etc. In such case, the algorithms need to maintain additional information beyond the population, which should be accessible by all the operations that are involved in the evolution process. \n",
"\n",
"Global state is introduced for this purpose. To understand the design of global state in details, see [Evolutionary Algorithm](https://colab.research.google.com/github/google/pyglove/blob/main/docs/notebooks/evolution/algorithm.ipynb). `GlobaStateSetter` is the built-in operation for writing global state.\n",
"\n",
"For example: To save the top 5 individuals as a global state associated with key 'top5', we can do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529821680,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "VMcC2tGaoqWV",
"outputId": "b4ecf402-3fff-4099-9487-d89a7e0e8895"
},
"outputs": [
{
"data": {
"text/plain": [
"[]"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"global_state = pg.geno.AttributeDict()\n",
"(pg.evolution.selectors.Top(5) >> pg.evolution.GlobalStateSetter('top5'))(\n",
" inputs, global_state=global_state)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "IytMe1CEpS6I"
},
"source": [
"Or:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529821872,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "RhPCNa0Ot_aU",
"outputId": "f7c48417-39a8-40db-88b8-f2af2328fcc8"
},
"outputs": [
{
"data": {
"text/plain": [
"[]"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Top(5).as_global_state('top5')(\n",
" inputs, global_state=global_state)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QbOwj34-vOZ7"
},
"source": [
"We can print the global state:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529822050,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "RemeyDLivRvx",
"outputId": "5af63483-a000-49d3-fdd3-c6aafed72b86"
},
"outputs": [
{
"data": {
"text/plain": [
"{'top5': [DNA(9), DNA(8), DNA(7), DNA(6), DNA(5)]}"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"global_state"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f4oxSw4NoyKg"
},
"source": [
"We can see `GlobalStateSetter` returns an empty list. If we want the inputs of global state setter to be returned, we can do the following:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529822226,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "blPTJe9po86D",
"outputId": "55dbdd61-329e-48fa-e458-34be72828c05"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(8), DNA(7), DNA(6), DNA(5)]"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(pg.evolution.selectors.Top(5) >> (\n",
" pg.evolution.GlobalStateSetter('top5')\n",
" + pg.evolution.Identity()))(\n",
" inputs, global_state=global_state)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "slRILbbFmrX8"
},
"source": [
"`GlobalStateSetter` also supports setting global state with constant values, which is useful when we want to put some flags."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529822404,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "CV_WItogvaol",
"outputId": "f7e3529c-5181-4085-dd14-5c12ead6bbac"
},
"outputs": [
{
"data": {
"text/plain": [
"[]"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.GlobalStateSetter('sorted', False)(inputs, global_state=global_state)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529822584,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "oQ5WsSrKvmH5",
"outputId": "f8506966-d818-4c0c-f358-c2305650ecbc"
},
"outputs": [
{
"data": {
"text/plain": [
"{'sorted': False, 'top5': [DNA(9), DNA(8), DNA(7), DNA(6), DNA(5)]}"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"global_state"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "r3_2xqvVlVcV"
},
"source": [
"\n",
"### **GlobalStateGetter**: Access a value from the global state\n",
"\n",
"With global state, an operation can access the values stored in the global state. `GlobalStateGetter` can be used for such purpose. Instead of consuming the inputs, it does key-value look up from the global state, and use the value as the output. \n",
"\n",
"*Disclaimer: It's up to the user to ensure that the value stored in global state is a list.*\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529822763,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "mbyGXGUOopkU",
"outputId": "6f06b0a5-670d-43ee-f9bf-71b1794c64ad"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(8), DNA(7), DNA(6), DNA(5)]"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.GlobalStateGetter('top5')(inputs, global_state=global_state)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pg3ym7tRWVUf"
},
"source": [
"## Selectors\n",
"\n",
"A selector is an operation that takes a list of items (of any type) as input, and returns a list of selected items as the output.\n",
"\n",
"It's defined by interface:\n",
"\n",
"```python\n",
"class Selector(pg.evolution.Operation):\n",
" \"\"\"Base class for selectors.\"\"\"\n",
"\n",
" @abc.abstractmethod\n",
" def select(\n",
" self,\n",
" inputs: List[Any],\n",
" global_state: pg.geno.AttributeDict,\n",
" step: int) -> List[Any]:\n",
"```\n",
"\n",
"PyGlove provides a list of built-in selectors, which can work with an arbitrary input element type.\n",
"\n",
"* First\n",
"* Last\n",
"* Top\n",
"* Bottom\n",
"* Random\n",
"* Sample\n",
"* Proportional"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CACRByYUx1_e"
},
"source": [
"\n",
"\n",
"### **First**: Selects the first N items from the input\n",
"\n",
"For example, the code below selects the first 3 items:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529822952,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "2QuDkdOfzA17",
"outputId": "c5116399-2229-4515-e065-3d91bbaadb51"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0), DNA(1), DNA(2)]"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.First(3)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PL4zwBd9y7fP"
},
"source": [
"\n",
"### **Last**: Selects the last N items from the input\n",
"\n",
"For example, the code below selects the last 3 items:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529823131,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "gcOM4GEyzFkn",
"outputId": "86923100-a63f-484a-d779-886972a3fcd6"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(7), DNA(8), DNA(9)]"
]
},
"execution_count": 51,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Last(3)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PD4FUxQpzNCf"
},
"source": [
"\n",
"### **Top**: Selects the top N items from the input\n",
"\n",
"By default, selecting the top is based on the fitness, for example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529823321,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "zrX7XUR4zXbW",
"outputId": "03edf28b-dafc-4f7c-9698-6fd41c187baa"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(9), DNA(8), DNA(7), DNA(6), DNA(5)]"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Top(5)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GBwf-Zzqza8f"
},
"source": [
"Users can also provide a custom ordering key:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529823498,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "QscaEalnzjVK",
"outputId": "d0e3893e-9d66-4830-94c0-91e16f1caafe"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0), DNA(1), DNA(9), DNA(2), DNA(8)]"
]
},
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Top(\n",
" 5, key=lambda x: abs(5 - pg.evolution.get_fitness(x)))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "n10Ix1Tqz8aa"
},
"source": [
"\n",
"### **Bottom**: Selects the bottom N items from the input\n",
"\n",
"Similarly, `Bottom` returns the bottom N items:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529823700,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "BMM5rf350Imh",
"outputId": "bc8e2f99-6fae-4188-dc96-a8e32c87eadf"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(0), DNA(1), DNA(2), DNA(3), DNA(4)]"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Bottom(5)(inputs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529823881,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "h3RVBle50KjH",
"outputId": "9f666efd-d736-416b-eb0d-315e59c1fbe3"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(5), DNA(4), DNA(6), DNA(3), DNA(7)]"
]
},
"execution_count": 55,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Bottom(\n",
" 5, key=lambda x: abs(5 - pg.evolution.get_fitness(x)))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FSQWFZVg0VP1"
},
"source": [
"\n",
"### **Random**: Selects N items randomly from the input\n",
"\n",
"Randomly select 10 items without replacement:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529824070,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "Yowk_EgB02BG",
"outputId": "1afa9fd6-8d7c-465a-bbe5-eb5e6a21e985"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(2),\n",
" DNA(1),\n",
" DNA(4),\n",
" DNA(0),\n",
" DNA(3),\n",
" DNA(5),\n",
" DNA(7),\n",
" DNA(9),\n",
" DNA(8),\n",
" DNA(6)]"
]
},
"execution_count": 56,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Random(10, seed=1)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kIj5BW04093e"
},
"source": [
"Randomly select 10 items with replacement:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529824249,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "Ob6KiiuS4fK8",
"outputId": "f95638ae-411c-4547-ae8b-c009dc9aa246"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(2),\n",
" DNA(9),\n",
" DNA(1),\n",
" DNA(4),\n",
" DNA(1),\n",
" DNA(7),\n",
" DNA(7),\n",
" DNA(7),\n",
" DNA(6),\n",
" DNA(3)]"
]
},
"execution_count": 57,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Random(10, replacement=True, seed=1)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "01Ev9vgt4y7P"
},
"source": [
"\n",
"### **Sample**: Samples items based on sampling weights\n",
"\n",
"Sample all items with equal weights:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529824435,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "pqgU0XEX5F2j",
"outputId": "3d94300e-e6a5-4a80-bb66-a2ff81eb3715"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(1), DNA(8), DNA(7), DNA(2), DNA(4)]"
]
},
"execution_count": 58,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Sample(\n",
" 5, weights=lambda xs: [1.0] * len(xs), seed=1)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oaKdwgDO5oME"
},
"source": [
"Sample items with exponential increasing weights:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 57,
"status": "ok",
"timestamp": 1658529824617,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "wEsvH3Av5wvH",
"outputId": "16fe1440-df81-4e90-cb28-536dcde690fa"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(7), DNA(9), DNA(9), DNA(8), DNA(8)]"
]
},
"execution_count": 59,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Sample(\n",
" 5, \n",
" weights=lambda xs: [1.0 * 2**i for i in range(len(xs))],\n",
" seed=1)(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LdeuMPTV6DBS"
},
"source": [
"\n",
"### **Proportional**: Selects items from the input proportionally\n",
"\n",
"Proportionally selects items from the input based on equal weights:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529824831,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "ZPOENhYr6b_6",
"outputId": "6a3aee94-925c-40eb-d8c4-36987f107942"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(5), DNA(6), DNA(7), DNA(8), DNA(9)]"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Proportional(\n",
" 5, weights=lambda xs: [1.0] * len(xs))(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ao5BM1V76sgI"
},
"source": [
"Sample items with exponential increasing weights:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 53,
"status": "ok",
"timestamp": 1658529825022,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "wAUop87B6kYs",
"outputId": "f2ef0b24-fd25-43f3-88cb-fcf7df444769"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA(7), DNA(8), DNA(9), DNA(9), DNA(9)]"
]
},
"execution_count": 61,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pg.evolution.selectors.Proportional(\n",
" 5, weights=lambda xs: [1.0 * 2**i for i in range(len(xs))]\n",
" )(inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "edX_7RLeWXU4"
},
"source": [
"\n",
"\n",
"## Recombinators\n",
"\n",
"Recombinators are operatons that take a DNA list (length > 1) as the input, and outputs a DNA list. Based on the mechanisms of recombination, there are three types of recombinators:\n",
"\n",
"* Point-wise: recombine values at each decision point level.\n",
"* Segment-wise: recombine DNA sequences\n",
"* Permutational: change the order of decisions in the DNA sequence."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "n2I8PZwd8Voa"
},
"source": [
"\n",
"\n",
"### **Point-wise**\n",
"\n",
"A point-wise recombinator works for an arbitrary number of parents, it\n",
"crossovers the parents' DNA into offspring's DNA point-by-point. For example,\n",
"`Uniform` takes a random parent's decisions per decision point, `Sample` samples\n",
"one of the parents' decision with probabilities computed from a weighting\n",
"function provided by the user, and `Average` works for float decision points\n",
"by averaging parents' values into the child's. When dealing with categorical\n",
"decision points (e.g. `pg.oneof`, `pg.manyof`), `Sample` can be very sample\n",
"efficient when the decision points are orthgonal to each other."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 102,
"status": "ok",
"timestamp": 1658529825244,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "EiByam-Rbf-K",
"outputId": "5d051225-a1a2-40f4-9ebe-8398d7d8293d"
},
"outputs": [
{
"data": {
"text/plain": [
"DNA([2, 0.6, [3, 3]])"
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dna_spec = pg.dna_spec(pg.List(\n",
" [pg.oneof(range(10))]\n",
" + [pg.floatv(0.1, 1.)]\n",
" + [pg.manyof(2, range(10), False, False)]))\n",
"\n",
"x = pg.DNA([1, 0.2, [1, 2]], spec=dna_spec)\n",
"y = pg.DNA([3, 0.5, [4, 5]], spec=dna_spec)\n",
"z = pg.DNA([2, 0.6, [3, 3]], spec=dna_spec)\n",
"\n",
"# Set the fitness of x, y and z.\n",
"pg.evolution.set_fitness(x, 0.5)\n",
"pg.evolution.set_fitness(y, 0.5)\n",
"pg.evolution.set_fitness(z, 0.)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ljkBtus3YJEl"
},
"source": [
"\n",
"\n",
"#### **Uniform Recombinator**: Uniformly sample decisions from parents"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529825423,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "2hOrkRV6YHWl",
"outputId": "66544a69-5c01-409a-a313-290022faaa08"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([1, 0.6, [3, 3]])]"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r = pg.evolution.recombinators.Uniform(seed=1)\n",
" \n",
"# For manyof decision points, uniform takes the decisions from one parent\n",
"# as a whole.\n",
"r([x, y, z])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lzT4foKob5vu"
},
"source": [
"All point-wise recombinators supports a `where` argument, which specifies the function that determines what decision should be included for recombination. Excluded decision points will be left in children intact (this means multiple children could be produced, inherting values from their parents), for example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 57,
"status": "ok",
"timestamp": 1658529825602,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "wZB0mmBjcPts",
"outputId": "bda630a7-64f0-4fa7-fde5-6563ae55eaf8"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([1, 0.5, [4, 3]]), DNA([1, 0.6, [4, 3]]), DNA([1, 0.2, [4, 3]])]"
]
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r = pg.evolution.recombinators.Uniform(\n",
" where=lambda ds: [d for d in ds if not isinstance(d, pg.geno.Float)],\n",
" seed=1)\n",
"\n",
"# Recombining on oneof and manyof, and leave floatv intact.\n",
"r([x, y, z])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ReUIa-fHaZVW"
},
"source": [
"\n",
"\n",
"#### **Sample Recombinator**: Sample decisions from parents based on a weighting function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529825778,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "SdFLTuCUaia8",
"outputId": "f16310db-f235-4d61-ac2c-fcad3ed9f352"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([3, 0.6, [3, 5]])]"
]
},
"execution_count": 65,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r = pg.evolution.recombinators.Sample(lambda parents: [0.0, 0.5, 0.5], seed=1)\n",
"\n",
"# Per decision-point sampling with 50% chance from `y` and 50% chance from `z`.\n",
"r([x, y, z])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qWaWFf0pc8HU"
},
"source": [
"\n",
"\n",
"#### **Average Recominbator**: Averaging the float decision points from the parents"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529825954,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "zORuhyoqdHYE",
"outputId": "e3f821f5-02ef-490a-c719-133a570b2d70"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([3, 0.4333333333333333, [4, 5]]),\n",
" DNA([2, 0.4333333333333333, [3, 3]]),\n",
" DNA([1, 0.4333333333333333, [1, 2]])]"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r = pg.evolution.recombinators.Average()\n",
"\n",
"# Per decision-point sampling with 50% chance from `y` and 50% chance from `z`.\n",
"r([x, y, z])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "q_3trOTldNfj"
},
"source": [
"\n",
"\n",
"#### **WeightedAverage Recombinator**: Weighted averaging the float decision points from the parents"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529826136,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "18gHPp6ldVfn",
"outputId": "3e5fc3de-26d1-47f2-98a3-2db7bb34fcb0"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([1, 0.55, [1, 2]]), DNA([3, 0.55, [4, 5]]), DNA([2, 0.55, [3, 3]])]"
]
},
"execution_count": 67,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r = pg.evolution.recombinators.WeightedAverage(lambda parents: [0.0, 0.5, 0.5])\n",
"\n",
"# Weighted averaging float decision point, with weights: [x=0.0, y=0.5, z=0.5].\n",
"r([x, y, z])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "vqgQkYpm8ZoR"
},
"source": [
"\n",
"\n",
"### **Segment-wise**\n",
"\n",
"A segment-wise recombinator works on 2 parents, it cuts the parents' DNA into multiple segments, and chooses alternating semgents from the parents. For example, if the i'th segment of one parent is taken as the `i`'th segment of a child, the `i + 1`'th segment of the child will be taken from another parent.\n",
"Each recombination produces 2 children which start with a segment from different\n",
"parents. For example::\n",
"\n",
" parent 1: 1 2 | 3 4 5 6 | 7 8 9\n",
" parent 2: 10 20 | 30 40 50 60 | 70 80 90\n",
"\n",
" child 1: 1 2 | 30 40 50 60 | 7 8 9\n",
" child 2: 10 20 | 3 4 5 6 | 70 80 90\n",
"\n",
"Well-known segment-wise recombinators are single-point crossover (SPX), two-point crossover (TPX), K-point crossover and more generally, the segmented crossover. While each of the former three chooses a fixed number of cutting points randomly, the segmented crossover allows the user to specify a function to produce the cutting points, which can be done dynamically based on the global\n",
"state and step. Also the customized cutting point can be effective when the user knows how the search space should be partitioned based on the application."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5J4r3StWd1MH"
},
"source": [
"\n",
"\n",
"#### **KPoint**: Cuts parents into K + 1 segements and alternate the segments\n",
"\n",
"K-point crossover is one of the basic crossovers in evolutionary algorithms.\n",
" It cuts both parents' DNA at K positions, which forms K + 1 segments. Then it\n",
" takes the K + 1 segments from both parents in an interleaving manner.\n",
" For example, a two-point crossover that takes places at cutting points 2 and 5\n",
" will result in 2 children as follows::\n",
"\n",
" Parent 1: [1, 2, | 3, 4, 5, | 6, 7]\n",
" Parent 2: [10, 20, | 30, 40, 50, | 60, 70]\n",
" | |\n",
" Child 1: [1, 2, | 30, 40, 50, | 6, 7]\n",
" Child 2: [10, 20, | 3, 4, 5, | 60, 70]\n",
"\n",
" 2 children as follows:\n",
" When K=1, we get a single-point crossover. Similarily, when K=2, we get a\n",
" two-point crossover.\n",
"\n",
" When K equals or is greater than the length of DNA sequence, we get an\n",
" alternating-position (APX) crossover.\n",
"\n",
" Reference:\n",
" https://mitpress.mit.edu/books/introduction-genetic-algorithms\n",
" https://dl.acm.org/doi/abs/10.5555/93126.93134\n",
" https://www.intechopen.com/chapters/335\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529826316,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "NI9LBFUfecyM",
"outputId": "ebc8bf03-66e7-4a5d-88b1-2cecc6635836"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[DNA([1, 0.5, [4, 5]]), DNA([3, 0.2, [1, 2]])]\n",
"[DNA([1, 0.2, [1, 5]]), DNA([3, 0.5, [4, 2]])]\n"
]
}
],
"source": [
"# Single-point recombination\n",
"r = pg.evolution.recombinators.KPoint(1, seed=1)\n",
"\n",
"# x = pg.DNA([1, 0.2, [1, 2]], spec=dna_spec)\n",
"# y = pg.DNA([3, 0.5, [4, 5]], spec=dna_spec)\n",
"\n",
"# Cut at position 1\n",
"print(r([x, y]))\n",
"\n",
"# Cut at position 3\n",
"print(r([x, y]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529826527,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "xt0DQS1ae_xg",
"outputId": "d24be60e-6277-4843-b688-789c54c71130"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[DNA([1, 0.5, [4, 2]]), DNA([3, 0.2, [1, 5]])]\n",
"[DNA([1, 0.5, [1, 2]]), DNA([3, 0.2, [4, 5]])]\n"
]
}
],
"source": [
"# Two-point recombination\n",
"r = pg.evolution.recombinators.KPoint(2, seed=1)\n",
"\n",
"# x = pg.DNA([1, 0.2, [1, 2]], spec=dna_spec)\n",
"# y = pg.DNA([3, 0.5, [4, 5]], spec=dna_spec)\n",
"\n",
"# Cut at position 1, 3\n",
"print(r([x, y]))\n",
"\n",
"# Cut at position 1, 2\n",
"print(r([x, y]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "P14VLFcsgM81"
},
"source": [
"\n",
"\n",
"#### **Segmented**: Alternating segments with a custom cutting strategy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529826707,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "ZBejzRqkgeNI",
"outputId": "500170f5-1894-4270-d400-3124c6fbbdbb"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([1, 0.2, [4, 5]]), DNA([3, 0.5, [1, 2]])]"
]
},
"execution_count": 70,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# A fixed single-point crossover at the mid of the chrosome:\n",
"r = pg.evolution.recombinators.Segmented(lambda xs: [len(xs) // 2])\n",
"\n",
"# x = pg.DNA([1, 0.2, [1, 2]], spec=dna_spec)\n",
"# y = pg.DNA([3, 0.5, [4, 5]], spec=dna_spec)\n",
"\n",
"r([x, y])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ko7KgSO88ci0"
},
"source": [
"\n",
"###**Permutational**\n",
"\n",
"A permutation recombinator works on 2 parents by permutating the order of the\n",
"subchoices of multi-choice decision points, which can be useful in applications\n",
"in which the order of choices matters (e.g. the traveling salesman problem).\n",
"Well-know permutation crossovers are partially mapped crossover (PMX), order\n",
"crossover (OX) and cycle crossover (CX)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XsGONIuioSGi"
},
"outputs": [],
"source": [
"dna_spec = pg.dna_spec(pg.permutate(range(5)))\n",
"x = pg.DNA([0, 1, 2, 4, 3], spec=dna_spec)\n",
"y = pg.DNA([1, 2, 3, 4, 0], spec=dna_spec)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2yxqepcLniTv"
},
"source": [
"\n",
"#### **PMX**: Partially mapped crossover\n",
"\n",
"The partially mapped crossover (PMX) was proposed by D. Goldberg and\n",
" R. Lingle, “Alleles, Loci and the Traveling Salesman Problem,” in\n",
" Proceedings of the 1st International Conference on Genetic Algorithms and\n",
" Their Applications, vol. 1985, pp. 154–159, Los Angeles, USA.\n",
"\n",
" Reference: https://dl.acm.org/doi/10.5555/645511.657095\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529827059,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "0ozEOzb1oG63",
"outputId": "4e8223d6-6c7e-4f33-c154-d9b4de6ec4c5"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([0, 2, 3, 4, 1]), DNA([1, 0, 2, 4, 3])]"
]
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r = pg.evolution.recombinators.PartiallyMapped(seed=1)\n",
"r([x, y])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ytpLYMfSn4Qr"
},
"source": [
"\n",
"#### **OX**: Order crossover\n",
"\n",
"The order crossover (OX) was proposed by L. Davis, “Applying adaptive\n",
" algorithms to epistatic domains,” IJCAI, vol. 85, pp. 162–164, 1985.\n",
"\n",
" It builds offspring by choosing a subtour of a parent and preserving the\n",
" relative order of bits of the other parent.\n",
"\n",
" Reference: https://dl.acm.org/doi/10.5555/1625135.1625164"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DHlaJ32VGgkX"
},
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529827241,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "IFk02nBeoHko",
"outputId": "2e755229-95e3-45ef-f8c1-58423e18ad87"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([1, 2, 4, 3, 0]), DNA([0, 2, 3, 4, 1])]"
]
},
"execution_count": 73,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r = pg.evolution.recombinators.Order(seed=1)\n",
"r([x, y])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bFmcWQfTn_wh"
},
"source": [
"\n",
"#### **CX**: Cycle crossover\n",
"\n",
"The cycle crossover (CX) operator was first proposed by I. M. Oliver,\n",
" D. J. d. Smith, and R. C. J. Holland, “Study of permutation crossover\n",
" operators on the traveling salesman problem,” in Genetic algorithms and\n",
" their applications: proceedings of the second International Conference\n",
" on Genetic Algorithms: July 28-31, 1987 at the Massachusetts Institute of\n",
" Technology, Cambridge, MA, USA, 1987.\n",
"\n",
" Reference: https://dl.acm.org/doi/10.5555/42512.42542."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1Wn5uI09GjjO"
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 56,
"status": "ok",
"timestamp": 1658529827418,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "Mm1gEGz3n2HL",
"outputId": "f7e5517d-e3b7-4f43-f8be-b7cf919ca2ae"
},
"outputs": [
{
"data": {
"text/plain": [
"[DNA([1, 2, 3, 4, 0]), DNA([0, 1, 2, 4, 3])]"
]
},
"execution_count": 74,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r = pg.evolution.recombinators.Cycle(seed=1)\n",
"r([x, y])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1P85e2otXAij"
},
"source": [
"\n",
"### **Semantics with PyGlove hyper primitives**\n",
"\n",
"```{eval-rst}\n",
"+-------------+-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"| | | # | | | manyof |\n",
"| | | parents | floatv | oneof | sorted Y | sorted N |\n",
"| | | | | | distinct | distinct |\n",
"| | | | | | Y | N | Y | N |\n",
"+=============+===========+=========+========+=======+=====+=====+=====+=====+\n",
"|Point-wise | Uniform | > 0 | X | X | X | X | X | X |\n",
"+ +-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"| | Sample | > 0 | X | X | X | X | X | X |\n",
"+ +-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"| | Average | > 0 | X | | | | | |\n",
"+ +-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"| | W-Average | > 0 | X | | | | | |\n",
"+-------------+-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"|Segment-wise | KPoint | 2 | X | X | X (treated as a | X |\n",
"| | | | | | single decision | |\n",
"+-------------+-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"| | Segmented | 2 | X | X | point) | X |\n",
"+-------------+-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"|Permutation | PMX | 2 | | | | | X | |\n",
"+-------------+-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"| | Order | 2 | | | | | X | |\n",
"+-------------+-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"| | Cycle | 2 | | | | | X | |\n",
"+-------------+-----------+---------+--------+-------+-----+-----+-----+-----+\n",
"```\n",
"**A blank cell means the recombinator works as a no-op on the hyper primitive.*"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0NSYhNJlWa3h"
},
"source": [
"\n",
"## Mutators\n",
"\n",
"A mutator is an operation that takes a list of DNA as input, and returns a list of DNA by mutating each of them.\n",
"\n",
"Mutators are defined by interface:\n",
"\n",
"```python\n",
"class Mutator(DNAOperation):\n",
" \"\"\"Base class for mutators.\n",
"\n",
" A mutator performs a mutation, i.e. a random transformation that converts\n",
" a parent DNA to a child DNA. Mutations should reach the full search space\n",
" through composition and should prefer local transformations individually.\n",
" \"\"\"\n",
"\n",
" def mutate(\n",
" self,\n",
" dna: pg.DNA,\n",
" global_state: pg.geno.AttributeDict,\n",
" step: int = 0) -> typing.Union[pg.DNA, List[pg.DNA]]:\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OD4tQ7d5YFUI"
},
"source": [
"PyGlove provides a list of mutators:\n",
" * `Uniform`\n",
" * `Swap`. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529827630,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "RSV_Fli1_9QL",
"outputId": "0692c7d5-3456-4aee-ba7c-e867a08632b2"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"DNA([0, [0, 1, 2], 0.0, (0, 0)])\n"
]
}
],
"source": [
"dna_spec = pg.dna_spec(pg.List([\n",
" pg.oneof(range(5), name='x'),\n",
" pg.manyof(3, range(4), name='y'),\n",
" pg.floatv(0.0, 1.0, name='z'),\n",
" pg.oneof([\n",
" pg.oneof(range(3)),\n",
" 1\n",
" ])\n",
"]))\n",
"\n",
"dna = dna_spec.first_dna()\n",
"print(dna)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UkPycRtJqFXv"
},
"source": [
"\n",
"### **Uniform Mutator**: Select 1 decision point for random mutation\n",
"\n",
"Uniform mutator does the following things:\n",
"\n",
" * It randomly select one decision point (node) from the search space for mutation.\n",
" * It then generates a random value for that node, and make necessary adjustment to honor the constraint (e.g. the distinct constraint of `pg.manyof`). If it mutate a decision point that has child decision points (e.g. nested `pg.oneof`s), the child desion points will be randomly generated.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 2,
"status": "ok",
"timestamp": 1658529827798,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "FqlZlQtkqabz",
"outputId": "7fb914bd-1e96-4426-9170-cc2f536a93c4"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[DNA([0, [3, 1, 2], 0.0, (0, 0)])]\n",
"[DNA([0, [0, 1, 3], 0.0, (0, 0)])]\n",
"[DNA([0, [0, 1, 2], 0.0, (0, 1)])]\n"
]
}
],
"source": [
"m = pg.evolution.mutators.Uniform(seed=1)\n",
"\n",
"# Mutate the first decision of `pg.manyof`.\n",
"print(m([dna]))\n",
"\n",
"# Mutate the 3rd decision of `pg.manyof`.\n",
"print(m([dna]))\n",
"\n",
"# Mutate the decision of the nested `pg.oneof`.\n",
"print(m([dna]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Z6cjs0AWBMWN"
},
"source": [
"PyGlove mutators provides a `where` statement to select applicable nodes. For example, if we want to mutate the `pg.floatv` from the DNA, we can do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529827981,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "NcWareQPBoT_",
"outputId": "d11a09df-0409-47a1-dadb-71ce65d8c209"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[DNA([0, [0, 1, 2], 0.5692038748222122, (0, 0)])]\n",
"[DNA([0, [0, 1, 2], 0.2550690257394217, (0, 0)])]\n"
]
}
],
"source": [
"m = pg.evolution.mutators.Uniform(\n",
" where=lambda d: isinstance(d.spec, pg.geno.Float),\n",
" seed=1)\n",
"\n",
"print(m([dna]))\n",
"print(m([dna]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aDpTaTwhCBiY"
},
"source": [
"We can also filter decision points to mutate by names:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 54,
"status": "ok",
"timestamp": 1658529828176,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "Y-4PiaBiCLdk",
"outputId": "8d2de2ce-67e4-47a0-d583-27c35f419355"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[DNA([4, [0, 1, 2], 0.0, (0, 0)])]\n",
"[DNA([2, [0, 1, 2], 0.0, (0, 0)])]\n"
]
}
],
"source": [
"m = pg.evolution.mutators.Uniform(\n",
" where=lambda d: getattr(d.spec, 'name', None) == 'x',\n",
" seed=1)\n",
"\n",
"print(m([dna]))\n",
"print(m([dna]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8ENkGakWqN6G"
},
"source": [
"\n",
"\n",
"### **Swap Mutator**: Swap the position of two decisions, applicable only for `pg.manyof`\n",
"\n",
"To mutate a permutation, `Uniform` does not work, since it requires to change the value for at least two decision points. `Swap` is the mutator to help in this case, which only operates on decision points of `pg.manyof`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"executionInfo": {
"elapsed": 55,
"status": "ok",
"timestamp": 1658529828360,
"user": {
"displayName": "Daiyi Peng",
"userId": "00212084952560362045"
},
"user_tz": 420
},
"id": "U1-OTKZcC8ay",
"outputId": "1cb7cab9-a465-4a7f-eb63-f5ce6fc3bbf0"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[DNA([0, [2, 1, 0], 0.0, (0, 0)])]\n",
"[DNA([0, [1, 0, 2], 0.0, (0, 0)])]\n",
"[DNA([0, [0, 2, 1], 0.0, (0, 0)])]\n"
]
}
],
"source": [
"m = pg.evolution.mutators.Swap(seed=1)\n",
"\n",
"print(m([dna]))\n",
"print(m([dna]))\n",
"print(m([dna]))"
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [],
"last_runtime": {
"build_target": "//learning/deepmind/dm_python:dm_notebook3",
"kind": "private"
},
"name": "Evolutionary Operations",
"provenance": [
{
"file_id": "1ejdp5sxVIkrOmOK5umX5nMkVc7SV5zQs",
"timestamp": 1658529961900
}
],
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}