The content for this site available on GitHub. If you want to launch the notebooks interactively click on the binder stamp below. Binder

< Experiment Decision Tree Classifier on iris dataset without pruning | Contents | Experiment KNN on iris dataset >

Genetic Algorithm on Knapsack Problem

In [ ]:
from helpers.base_imports import export_cell

from azureml.core import (
    Workspace,
    Experiment,
    ScriptRunConfig,
    Environment,
    ComputeTarget,
    Environment,
)
from azureml.core.compute import AmlCompute
from azureml.core.compute_target import ComputeTargetException
In [ ]:
# Connect to workspace
ws = Workspace.from_config()  # uses config.json in root
print(ws.name, ws.resource_group, ws.location)
In [ ]:
# Create or attach to a compute cluster
cluster_name = "cpu-cluster"

try:
    compute_target = ComputeTarget(workspace=ws, name=cluster_name)
except ComputeTargetException:
    compute_config = AmlCompute.provisioning_configuration(
        vm_size="STANDARD_DS11_V2", max_nodes=2
    )
    compute_target = ComputeTarget.create(ws, cluster_name, compute_config)
    compute_target.wait_for_completion(show_output=True)

Write GA Script

In [ ]:
code = """
import random

def fitness(individual, weights, values, capacity):
    total_weight = sum(w*i for w, i in zip(weights, individual))
    if total_weight > capacity:
        return 0
    return sum(v*i for v, i in zip(values, individual))

def run_knapsack():
    weights = [10, 20, 30]
    values = [60, 100, 120]
    capacity = 50
    population_size = 10
    generations = 20

    population = [[random.randint(0,1) for _ in weights] for _ in range(population_size)]

    for _ in range(generations):
        scored = [(ind, fitness(ind, weights, values, capacity)) for ind in population]
        scored.sort(key=lambda x: x[1], reverse=True)
        parents = [ind for ind, _ in scored[:2]]
        children = []

        for _ in range(population_size):
            crossover = [random.choice(gene_pair) for gene_pair in zip(*parents)]
            mutation = [bit if random.random() > 0.1 else 1 - bit for bit in crossover]
            children.append(mutation)

        population = children

    best = max(population, key=lambda x: fitness(x, weights, values, capacity))
    print("Best:", best, "Value:", fitness(best, weights, values, capacity))

if __name__ == "__main__":
    run_knapsack()
"""
with open("helpers/knapsack_ga.py", "w") as f:
    f.write(code)
In [ ]:
# save previous cell to output file

Submit experiment to Azure backend

In [ ]:
env = Environment.from_conda_specification(
    name="ga-env", file_path="env.yml"
)  # or use Environment.get(workspace=ws, name="AzureML-sklearn-1.0-ubuntu20.04-py38-cpu")

src = ScriptRunConfig(
    source_directory=".",
    script="knapsack_ga.py",
    compute_target=compute_target,
    environment=env,
)

experiment = Experiment(workspace=ws, name="knapsack-experiment")
run = experiment.submit(config=src)
run.wait_for_completion(show_output=True)

Monitor Logs

In [ ]:
print(run.get_metrics())
run.get_file_names()  # list of output logs and results


< Experiment Decision Tree Classifier on iris dataset without pruning | Contents | Experiment KNN on iris dataset >