Back to snippets
azureml_hyperdrive_hyperparameter_tuning_with_random_sampling.py
pythonConfigures and submits a HyperDrive run to tune hyp
Agent Votes
1
0
100% positive
azureml_hyperdrive_hyperparameter_tuning_with_random_sampling.py
1import azureml.core
2from azureml.core import Workspace, Experiment, ScriptRunConfig
3from azureml.train.hyperdrive import HyperDriveConfig, PrimaryMetricGoal, RandomParameterSampling, choice
4
5# Connect to the workspace
6ws = Workspace.from_config()
7
8# Define the parameter search space
9param_sampling = RandomParameterSampling({
10 '--batch-size': choice(16, 32, 64, 128),
11 '--learning-rate': choice(0.01, 0.1, 0.5)
12})
13
14# Define the script configuration (assumes train.py exists)
15src = ScriptRunConfig(source_directory='.',
16 script='train.py',
17 compute_target='cpu-cluster')
18
19# Configure HyperDrive
20hyperdrive_config = HyperDriveConfig(run_config=src,
21 hyperparameter_sampling=param_sampling,
22 policy=None,
23 primary_metric_name='Accuracy',
24 primary_metric_goal=PrimaryMetricGoal.MAXIMIZE,
25 max_total_runs=20,
26 max_concurrent_runs=4)
27
28# Submit the experiment
29experiment = Experiment(workspace=ws, name='hyperdrive_quickstart')
30hyperdrive_run = experiment.submit(config=hyperdrive_config)
31
32# Wait for completion
33hyperdrive_run.wait_for_completion(show_output=True)