Documentation
Search…
Import & Export Data
Best practices and common use cases for our public API to export data and update existing runs
Use the Public API to export or update data that you have saved to W&B. Before using this API, you'll want to log data from your script — check the Quickstart for more details.
Use Cases for the Public API
    Export Data: Pull down a dataframe for custom analysis in a Jupyter Notebook. Once you have explored the data, you can sync your findings by creating a new analysis run and logging results, for example: wandb.init(job_type="analysis")
    Update Existing Runs: You can update the data logged in association with a W&B run. For example, you might want to update the config of a set of runs to include additional information, like the architecture or a hyperparameter that wasn't originally logged.
See the Generated Reference Docs for details on available functions.

Authentication

Authenticate your machine with your API key in one of two ways:
    1.
    Run wandb login on the command line and paste in your API key.
    2.
    Set the WANDB_API_KEY environment variable to your API key.

Find the run path

To use the Public API, you'll often need the run path which is <entity>/<project>/<run_id>. In the app UI, open a run page and click the Overview tab to get the run path.

Export Run Data

Download data from a finished or active run. Common usage includes downloading a dataframe for custom analysis in a Jupyter notebook, or using custom logic in an automated environment.
1
import wandb
2
api = wandb.Api()
3
run = api.run("<entity>/<project>/<run_id>")
Copied!
The most commonly used attributes of a run object are:
Attribute
Meaning
run.config
A dictionary of the run's configuration information, such as the hyperparameters for a training run or the preprocessing methods for a run that creates a dataset Artifact. Think of these as the run's "inputs".
run.history()
A list of dictionaries meant to store values that change while the model is training such as loss. The command wandb.log() appends to this object.
run.summary
A dictionary of information that summarizes the run's results. This can be scalars like accuracy and loss, or large files. By default, wandb.log() sets the summary to the final value of a logged timeseries. The contents of the summary can also be set directly. Think of the summary as the run's "outputs".
You can also modify or update the data of past runs. By default a single instance of an api object will cache all network requests. If your use case requires real time information in a running script, call api.flush() to get updated values.

Sampling

The default history method samples the metrics to a fixed number of samples (the default is 500, you can change this with the samples argument). If you want to export all of the data on a large run, you can use the run.scan_history() method. For more details see the API Reference.

Querying Multiple Runs

Dataframes and CSVs
MongoDB Style
This example script finds a project and outputs a CSV of runs with name, configs and summary stats.
1
import pandas as pd
2
import wandb
3
4
api = wandb.Api()
5
entity, project = "<entity>", "<project>" # set to your entity and project
6
runs = api.runs(entity + "/" + project)
7
8
summary_list, config_list, name_list = [], [], []
9
for run in runs:
10
# .summary contains the output keys/values for metrics like accuracy.
11
# We call ._json_dict to omit large files
12
summary_list.append(run.summary._json_dict)
13
14
# .config contains the hyperparameters.
15
# We remove special values that start with _.
16
config_list.append(
17
{k: v for k,v in run.config.items()
18
if not k.startswith('_')})
19
20
# .name is the human-readable name of the run.
21
name_list.append(run.name)
22
23
runs_df = pd.DataFrame({
24
"summary": summary_list,
25
"config": config_list,
26
"name": name_list
27
})
28
29
runs_df.to_csv("project.csv")
Copied!
The W&B API also provides a way for you to query across runs in a project with api.runs(). The most common use case is exporting runs data for custom analysis. The query interface is the same as the one MongoDB uses.
1
runs = api.runs("username/project",
2
{"$or": [
3
{"config.experiment_name": "foo"},
4
{"config.experiment_name": "bar"}]
5
})
6
print(f"Found {}len(runs) runs")
Copied!
Calling api.runs returns a Runs object that is iterable and acts like a list. By default the object loads 50 runs at a time in sequence as required, but you can change the number loaded per page with the per_page keyword argument.
api.runs also accepts an order keyword argument. The default order is -created_at, specify +created_at to get results in ascending order. You can also sort by config or summary values e.g. summary.val_acc or config.experiment_name

Error Handling

If errors occur while talking to W&B servers a wandb.CommError will be raised. The original exception can be introspected via the exc attribute.

Get the latest git commit through the API

In the UI, click on a run and then click the Overview tab on the run page to see the latest git commit. It's also in the file wandb-metadata.json . Using the public API, you can get the git hash with run.commit.

Frequently Asked Questions

How do I export data to visualize in matplotlib or seaborn?

Check out our API examples for some common export patterns. You can also click the download button on a custom plot or on the expanded runs table to download a CSV from your browser.

How do I get a run's name and ID during a run?

After calling wandb.init() you can access the random run ID or the human readable run name from your script like this:
    Unique run ID (8 character hash): wandb.run.id
    Random run name (human readable): wandb.run.name
If you're thinking about ways to set useful identifiers for your runs, here's what we recommend:
    Run ID: leave it as the generated hash. This needs to be unique across runs in your project.
    Run name: This should be something short, readable, and preferably unique so that you can tell the difference between different lines on your charts.
    Run notes: This is a great place to put a quick description of what you're doing in your run. You can set this with wandb.init(notes="your notes here")
    Run tags: Track things dynamically in run tags, and use filters in the UI to filter your table down to just the runs you care about. You can set tags from your script and then edit them in the UI, both in the runs table and the overview tab of the run page. See the detailed instructions here.

Public API Examples

Read metrics from a run

This example outputs timestamp and accuracy saved with wandb.log({"accuracy": acc}) for a run saved to "<entity>/<project>/<run_id>".
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
if run.state == "finished":
6
for i, row in run.history().iterrows():
7
print(row["_timestamp"], row["accuracy"])
Copied!

Read specific metrics from a run

To pull specific metrics from a run, use the keys argument. The default number of samples when using run.history() is 500. Logged steps that do not include a specific metric will appear in the output dataframe as NaN. The keys argument will cause the API to sample steps that include the listed metric keys more frequently.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
if run.state == "finished":
6
for i, row in run.history(keys=["accuracy"]).iterrows():
7
print(row["_timestamp"], row["accuracy"])
Copied!

Compare two runs

This will output the config parameters that are different between run1 and run2.
1
import pandas as pd
2
import wandb
3
api = wandb.Api()
4
5
# replace with your <entity>, <project>, and <run_id>
6
run1 = api.run("<entity>/<project>/<run_id>")
7
run2 = api.run("<entity>/<project>/<run_id>")
8
9
10
df = pd.DataFrame([run1.config, run2.config]).transpose()
11
12
df.columns = [run1.name, run2.name]
13
print(df[df[run1.name] != df[run2.name]])
Copied!
Outputs:
1
c_10_sgd_0.025_0.01_long_switch base_adam_4_conv_2fc
2
batch_size 32 16
3
n_conv_layers 5 4
4
optimizer rmsprop adam
Copied!

Update metrics for a run, after the run has finished

This example sets the accuracy of a previous run to 0.9. It also modifies the accuracy histogram of a previous run to be the histogram of numpy_array.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
run.summary["accuracy"] = 0.9
6
run.summary["accuracy_histogram"] = wandb.Histogram(numpy_array)
7
run.summary.update()
Copied!

Rename a metric in a run, after the run has finished

This example renames a summary column in your tables.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
run.summary['new_name'] = run.summary['old_name']
6
del run.summary['old_name']
7
run.summary.update()
Copied!
Renaming a column only applies to tables. Charts will still refer to metrics by their original names.

Update config for an existing run

This examples updates one of your configuration settings.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
run.config["key"] = updated_value
6
run.update()
Copied!

Export metrics from a single run to a CSV file

This snippet finds all the metrics saved for a single run and saves them to a CSV.
1
import wandb
2
api = wandb.Api()
3
4
# run is specified by <entity>/<project>/<run id>
5
run = api.run("<entity>/<project>/<run_id>")
6
7
# save the metrics for the run to a csv file
8
metrics_dataframe = run.history()
9
metrics_dataframe.to_csv("metrics.csv")
Copied!

Get unsampled metric data

When you pull data from history, by default it's sampled to 500 points. Get all the logged data points using run.scan_history(). Here's an example downloading all the loss data points logged in history.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
history = run.scan_history()
6
losses = [row["loss"] for row in history]
Copied!

Get paginated data from history

If metrics are being fetched slowly on our backend or API requests are timing out, you can try lowering the page size in scan_history so that individual requests don't time out. The default page size is 500, so you can experiment with different sizes to see what works best:
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
run.scan_history(keys=sorted(cols), page_size=100)
Copied!

Export metrics from all runs in a project to a CSV file

This script pulls down the runs in a project and produces a dataframe and a CSV of runs including their names, configs, and summary stats.
1
import pandas as pd
2
import wandb
3
4
api = wandb.Api()
5
entity, project = "<entity>", "<project>" # set to your entity and project
6
runs = api.runs(entity + "/" + project)
7
8
summary_list, config_list, name_list = [], [], []
9
for run in runs:
10
# .summary contains the output keys/values for metrics like accuracy.
11
# We call ._json_dict to omit large files
12
summary_list.append(run.summary._json_dict)
13
14
# .config contains the hyperparameters.
15
# We remove special values that start with _.
16
config_list.append(
17
{k: v for k,v in run.config.items()
18
if not k.startswith('_')})
19
20
# .name is the human-readable name of the run.
21
name_list.append(run.name)
22
23
runs_df = pd.DataFrame({
24
"summary": summary_list,
25
"config": config_list,
26
"name": name_list
27
})
28
29
runs_df.to_csv("project.csv")
Copied!

Get the starting time for a run

This code snippet retrives the time at which the run was created.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("entity/project/run_id")
5
start_time = run.created_at
Copied!

Upload files to a finished run

The code snippet below uploads a selected file to a finished run.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("entity/project/run_id")
5
run.upload_file("file_name.extension")
Copied!

Download a file from a run

This finds the file "model-best.h5" associated with with run ID uxte44z7 in the cifar project and saves it locally.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
run.file("model-best.h5").download()
Copied!

Download all files from a run

This finds all files associated with a run and saves them locally.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
for file in run.files():
6
file.download()
Copied!

Get runs from a specific sweep

This snippet downloads all the runs associated with a particular sweep.
1
import wandb
2
api = wandb.Api()
3
4
sweep = api.sweep("<entity>/<project>/<sweep_id>")
5
sweep_runs = sweep.runs
Copied!

Download the best model file from a sweep

This snippet downloads the model file with the highest validation accuracy from a sweep with runs that saved model files to model.h5.
1
import wandb
2
api = wandb.Api()
3
4
sweep = api.sweep("<entity>/<project>/<sweep_id>")
5
runs = sorted(sweep.runs,
6
key=lambda run: run.summary.get("val_acc", 0), reverse=True)
7
val_acc = runs[0].summary.get("val_acc", 0)
8
print(f"Best run {runs[0].name} with {val_acc}% validation accuracy")
9
10
runs[0].file("model.h5").download(replace=True)
11
print("Best model saved to model-best.h5")
Copied!

Delete all files with a given extension from a run

This snippet deletes files with a given extension from a run.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
6
extension = ".png"
7
files = run.files()
8
for file in files:
9
if file.name.endswith(extension):
10
file.delete()
Copied!

Download system metrics data

This snippet produces a dataframe with all the system metrics for a run.
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
system_metrics = run.history(stream="events")
Copied!

Update summary metrics

You can pass a dictionary to update summary metrics.
1
summary.update({"key": val})
Copied!

Get the command that ran the run

Each run captures the command that launched it on the run overview page. To pull this command down from the API, you can run:
1
import wandb
2
api = wandb.Api()
3
4
run = api.run("<entity>/<project>/<run_id>")
5
6
meta = json.load(run.file("wandb-metadata.json").download())
7
program = ["python"] + [meta["program"]] + meta["args"]
Copied!
Last modified 2mo ago