In [26]:
from kubernetes.client import V1ObjectMeta
import kubeflow.katib as kc
from kubeflow.katib import constants
from kubeflow.katib import utils
from kubeflow.katib import V1alpha3AlgorithmSetting
from kubeflow.katib import V1alpha3AlgorithmSetting
from kubeflow.katib import V1alpha3AlgorithmSpec
from kubeflow.katib import V1alpha3CollectorSpec
from kubeflow.katib import V1alpha3EarlyStoppingSetting
from kubeflow.katib import V1alpha3EarlyStoppingSpecs
from kubeflow.katib import V1alpha3Experiment
from kubeflow.katib import V1alpha3ExperimentCondition
from kubeflow.katib import V1alpha3ExperimentList
from kubeflow.katib import V1alpha3ExperimentSpec
from kubeflow.katib import V1alpha3ExperimentStatus
from kubeflow.katib import V1alpha3FeasibleSpace
from kubeflow.katib import V1alpha3FileSystemPath
from kubeflow.katib import V1alpha3FilterSpec
from kubeflow.katib import V1alpha3GoTemplate
from kubeflow.katib import V1alpha3GraphConfig
from kubeflow.katib import V1alpha3Metric
from kubeflow.katib import V1alpha3MetricsCollectorSpec
from kubeflow.katib import V1alpha3NasConfig
from kubeflow.katib import V1alpha3ObjectiveSpec
from kubeflow.katib import V1alpha3Observation
from kubeflow.katib import V1alpha3Operation
from kubeflow.katib import V1alpha3OptimalTrial
from kubeflow.katib import V1alpha3ParameterAssignment
from kubeflow.katib import V1alpha3ParameterSpec
from kubeflow.katib import V1alpha3SourceSpec
from kubeflow.katib import V1alpha3Suggestion
from kubeflow.katib import V1alpha3SuggestionCondition
from kubeflow.katib import V1alpha3SuggestionList
from kubeflow.katib import V1alpha3SuggestionSpec
from kubeflow.katib import V1alpha3SuggestionStatus
from kubeflow.katib import V1alpha3TemplateSpec
from kubeflow.katib import V1alpha3Trial
from kubeflow.katib import V1alpha3TrialAssignment
from kubeflow.katib import V1alpha3TrialCondition
from kubeflow.katib import V1alpha3TrialList
from kubeflow.katib import V1alpha3TrialSpec
from kubeflow.katib import V1alpha3TrialStatus
from kubeflow.katib import V1alpha3TrialTemplate

In [28]:
algorithmsettings = V1alpha3AlgorithmSetting(
    name= "random_state",
    value = "10"
    )
algorithm = V1alpha3AlgorithmSpec(
    algorithm_name = "bayesianoptimization",
    algorithm_settings = [algorithmsettings]
  )

# Objective
objective = V1alpha3ObjectiveSpec(
    goal = 0.9999,
    objective_metric_name = "Validation-accuracy",
    type = "maximize")

# Parameters

feasible_space_optimizer = V1alpha3FeasibleSpace(list = ["sgd", "adam", "ftrl"])
feasible_space_lr = V1alpha3FeasibleSpace(min = "0.01", max = "0.03")
feasible_space_layers = V1alpha3FeasibleSpace(min = "2", max = "5")

parameters = [V1alpha3ParameterSpec(
    feasible_space = feasible_space_optimizer, 
    name = "--optimizer",
    parameter_type = "categorical"
    ),
    V1alpha3ParameterSpec(
    feasible_space = feasible_space_lr, 
    name = "--lr",
    parameter_type ="double"
    ),
    V1alpha3ParameterSpec(
    feasible_space = feasible_space_layers, 
    name = "--num-layers",
    parameter_type = "int"
    )]

# Trialtemplate
go_template = V1alpha3GoTemplate(
    raw_template =   "apiVersion: \"batch/v1\"\nkind: Job\nmetadata:\n  name: {{.Trial}}\n  namespace: {{.NameSpace}}\nspec:\n  template:\n    spec:\n      containers:\n      - name: {{.Trial}}\n        image: docker.io/kubeflowkatib/mxnet-mnist\n        command:\n        - \"python3\"\n        - \"/opt/mxnet-mnist/mnist.py\"\n        - \"--batch-size=64\"\n        {{- with .HyperParameters}}\n        {{- range .}}\n        - \"{{.Name}}={{.Value}}\"\n        {{- end}}\n        {{- end}}\n      restartPolicy: Never"
    )


trial_template= V1alpha3TrialTemplate(go_template=go_template)


# Experiment
experiment = V1alpha3Experiment(
    api_version="kubeflow.org/v1alpha3",
    kind="Experiment",
    metadata=V1ObjectMeta(name="bayesianoptimization",namespace="anonymous"),

    spec=V1alpha3ExperimentSpec(
         algorithm = algorithm,
         max_failed_trial_count=3,
         max_trial_count=5,
         objective = objective,
         parallel_trial_count=5,
         parameters = parameters ,
         trial_template = trial_template
    )
)

In [29]:
namespace = kc.utils.get_default_target_namespace()
#experiment

In [30]:
kclient = kc.KatibClient()

Create Experiment


In [31]:
kclient.create_experiment(experiment, namespace=namespace)


Katib Experiment link here
Out[31]:
{'apiVersion': 'kubeflow.org/v1alpha3',
 'kind': 'Experiment',
 'metadata': {'creationTimestamp': '2020-03-04T10:46:49Z',
  'generation': 1,
  'name': 'bayesianoptimization',
  'namespace': 'anonymous',
  'resourceVersion': '7034916',
  'selfLink': '/apis/kubeflow.org/v1alpha3/namespaces/anonymous/experiments/bayesianoptimization',
  'uid': '7360157b-5e05-11ea-8d71-42010aa00012'},
 'spec': {'algorithm': {'algorithmName': 'bayesianoptimization',
   'algorithmSettings': [{'name': 'random_state', 'value': '10'}]},
  'maxFailedTrialCount': 3,
  'maxTrialCount': 5,
  'metricsCollectorSpec': {'collector': {'kind': 'StdOut'}},
  'objective': {'goal': 0.9999,
   'objectiveMetricName': 'Validation-accuracy',
   'type': 'maximize'},
  'parallelTrialCount': 5,
  'parameters': [{'feasibleSpace': {'list': ['sgd', 'adam', 'ftrl']},
    'name': '--optimizer',
    'parameterType': 'categorical'},
   {'feasibleSpace': {'max': '0.03', 'min': '0.01'},
    'name': '--lr',
    'parameterType': 'double'},
   {'feasibleSpace': {'max': '5', 'min': '2'},
    'name': '--num-layers',
    'parameterType': 'int'}],
  'trialTemplate': {'goTemplate': {'rawTemplate': 'apiVersion: "batch/v1"\nkind: Job\nmetadata:\n  name: {{.Trial}}\n  namespace: {{.NameSpace}}\nspec:\n  template:\n    spec:\n      containers:\n      - name: {{.Trial}}\n        image: docker.io/kubeflowkatib/mxnet-mnist\n        command:\n        - "python3"\n        - "/opt/mxnet-mnist/mnist.py"\n        - "--batch-size=64"\n        {{- with .HyperParameters}}\n        {{- range .}}\n        - "{{.Name}}={{.Value}}"\n        {{- end}}\n        {{- end}}\n      restartPolicy: Never'}}}}

Get Single Experiment


In [32]:
kclient.get_experiment(name="bayesianoptimization", namespace=namespace)


Out[32]:
{'apiVersion': 'kubeflow.org/v1alpha3',
 'kind': 'Experiment',
 'metadata': {'creationTimestamp': '2020-03-04T10:46:49Z',
  'finalizers': ['update-prometheus-metrics'],
  'generation': 1,
  'name': 'bayesianoptimization',
  'namespace': 'anonymous',
  'resourceVersion': '7034918',
  'selfLink': '/apis/kubeflow.org/v1alpha3/namespaces/anonymous/experiments/bayesianoptimization',
  'uid': '7360157b-5e05-11ea-8d71-42010aa00012'},
 'spec': {'algorithm': {'algorithmName': 'bayesianoptimization',
   'algorithmSettings': [{'name': 'random_state', 'value': '10'}]},
  'maxFailedTrialCount': 3,
  'maxTrialCount': 5,
  'metricsCollectorSpec': {'collector': {'kind': 'StdOut'}},
  'objective': {'goal': 0.9999,
   'objectiveMetricName': 'Validation-accuracy',
   'type': 'maximize'},
  'parallelTrialCount': 5,
  'parameters': [{'feasibleSpace': {'list': ['sgd', 'adam', 'ftrl']},
    'name': '--optimizer',
    'parameterType': 'categorical'},
   {'feasibleSpace': {'max': '0.03', 'min': '0.01'},
    'name': '--lr',
    'parameterType': 'double'},
   {'feasibleSpace': {'max': '5', 'min': '2'},
    'name': '--num-layers',
    'parameterType': 'int'}],
  'trialTemplate': {'goTemplate': {'rawTemplate': 'apiVersion: "batch/v1"\nkind: Job\nmetadata:\n  name: {{.Trial}}\n  namespace: {{.NameSpace}}\nspec:\n  template:\n    spec:\n      containers:\n      - name: {{.Trial}}\n        image: docker.io/kubeflowkatib/mxnet-mnist\n        command:\n        - "python3"\n        - "/opt/mxnet-mnist/mnist.py"\n        - "--batch-size=64"\n        {{- with .HyperParameters}}\n        {{- range .}}\n        - "{{.Name}}={{.Value}}"\n        {{- end}}\n        {{- end}}\n      restartPolicy: Never'}}},
 'status': {'completionTime': None,
  'conditions': [{'lastTransitionTime': '2020-03-04T10:46:49Z',
    'lastUpdateTime': '2020-03-04T10:46:49Z',
    'message': 'Experiment is created',
    'reason': 'ExperimentCreated',
    'status': 'True',
    'type': 'Created'}],
  'currentOptimalTrial': {'bestTrialName': '',
   'observation': {'metrics': None},
   'parameterAssignments': None},
  'startTime': '2020-03-04T10:46:49Z'}}

Get all Experiments


In [33]:
kclient.get_experiment()


Out[33]:
{'apiVersion': 'kubeflow.org/v1alpha3',
 'items': [{'apiVersion': 'kubeflow.org/v1alpha3',
   'kind': 'Experiment',
   'metadata': {'creationTimestamp': '2020-03-04T10:46:49Z',
    'finalizers': ['update-prometheus-metrics'],
    'generation': 1,
    'name': 'bayesianoptimization',
    'namespace': 'anonymous',
    'resourceVersion': '7034918',
    'selfLink': '/apis/kubeflow.org/v1alpha3/namespaces/anonymous/experiments/bayesianoptimization',
    'uid': '7360157b-5e05-11ea-8d71-42010aa00012'},
   'spec': {'algorithm': {'algorithmName': 'bayesianoptimization',
     'algorithmSettings': [{'name': 'random_state', 'value': '10'}]},
    'maxFailedTrialCount': 3,
    'maxTrialCount': 5,
    'metricsCollectorSpec': {'collector': {'kind': 'StdOut'}},
    'objective': {'goal': 0.9999,
     'objectiveMetricName': 'Validation-accuracy',
     'type': 'maximize'},
    'parallelTrialCount': 5,
    'parameters': [{'feasibleSpace': {'list': ['sgd', 'adam', 'ftrl']},
      'name': '--optimizer',
      'parameterType': 'categorical'},
     {'feasibleSpace': {'max': '0.03', 'min': '0.01'},
      'name': '--lr',
      'parameterType': 'double'},
     {'feasibleSpace': {'max': '5', 'min': '2'},
      'name': '--num-layers',
      'parameterType': 'int'}],
    'trialTemplate': {'goTemplate': {'rawTemplate': 'apiVersion: "batch/v1"\nkind: Job\nmetadata:\n  name: {{.Trial}}\n  namespace: {{.NameSpace}}\nspec:\n  template:\n    spec:\n      containers:\n      - name: {{.Trial}}\n        image: docker.io/kubeflowkatib/mxnet-mnist\n        command:\n        - "python3"\n        - "/opt/mxnet-mnist/mnist.py"\n        - "--batch-size=64"\n        {{- with .HyperParameters}}\n        {{- range .}}\n        - "{{.Name}}={{.Value}}"\n        {{- end}}\n        {{- end}}\n      restartPolicy: Never'}}},
   'status': {'completionTime': None,
    'conditions': [{'lastTransitionTime': '2020-03-04T10:46:49Z',
      'lastUpdateTime': '2020-03-04T10:46:49Z',
      'message': 'Experiment is created',
      'reason': 'ExperimentCreated',
      'status': 'True',
      'type': 'Created'}],
    'currentOptimalTrial': {'bestTrialName': '',
     'observation': {'metrics': None},
     'parameterAssignments': None},
    'startTime': '2020-03-04T10:46:49Z'}}],
 'kind': 'ExperimentList',
 'metadata': {'continue': '',
  'resourceVersion': '7035035',
  'selfLink': '/apis/kubeflow.org/v1alpha3/namespaces/anonymous/experiments'}}

Get experiment status


In [34]:
kclient.get_experiment_status(name="bayesianoptimization", namespace=namespace)


Out[34]:
'Running'

Is experiment succeeded


In [35]:
kclient.is_experiment_succeeded(name="bayesianoptimization", namespace=namespace)


Out[35]:
False

List Trials of an experiment


In [37]:
kclient.list_trials(name="bayesianoptimization", namespace=namespace)


Out[37]:
[{'name': 'bayesianoptimization-52tsscjq', 'status': 'Running'},
 {'name': 'bayesianoptimization-65fnsn5t', 'status': 'Running'},
 {'name': 'bayesianoptimization-d5blztvn', 'status': 'Running'},
 {'name': 'bayesianoptimization-gs7b6g25', 'status': 'Running'},
 {'name': 'bayesianoptimization-s8qwszvr', 'status': 'Running'}]

List all experiments


In [38]:
kclient.list_experiments(namespace=namespace)


Out[38]:
[{'name': 'bayesianoptimization', 'status': 'Running'}]

Get Optimal Hyperparameter


In [25]:
kclient.get_optimal_hyperparmeters(name="bayesianoptimization", namespace=namespace)


Out[25]:
{'status': 'Succeeded',
 'currentOptimalTrial': {'bestTrialName': 'bayesianoptimization-nkj9hd9z',
  'observation': {'metrics': [{'name': 'Validation-accuracy',
     'value': 0.980195}]},
  'parameterAssignments': [{'name': '--optimizer', 'value': 'sgd'},
   {'name': '--lr', 'value': '0.01721786775240965'},
   {'name': '--num-layers', 'value': '3'}]}}

Delete experiment


In [36]:
kclient.delete_experiment(name="bayesianoptimization", namespace=namespace)