API reference for development package labproject
Here all functions will be documented that are part of the public API of the labproject package.
Metrics
Best practices for developing metrics:
- Please do everything in torch, and if that is not possible, cast the output to torch.Tensor.
- The function should be well-documented, including type hints.
- The function should be tested with a simple example.
- Add an assert at the beginning for shape checking (N,D), see examples.
- Register the function by importing
labrpoject.metrics.utils.regiter_metric
and give your function a meaningful name.
Gaussian KL divergence
gaussian_kl_divergence(real_samples, fake_samples)
Compute the KL divergence between Gaussian approximations of real and fake samples. Dimensionality of the samples must be the same and >=2 (for covariance calculation).
In detail, for each set of samples, we calculate the mean and covariance matrix.
Then we calculate the KL divergence between the two Gaussian approximations:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
real_samples |
Tensor
|
A tensor representing the real samples. |
required |
fake_samples |
Tensor
|
A tensor representing the fake samples. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: The KL divergence between the two Gaussian approximations. |
Examples:
>>> real_samples = torch.randn(100, 2) # 100 samples, 2-dimensional
>>> fake_samples = torch.randn(100, 2) # 100 samples, 2-dimensional
>>> kl_div = gaussian_kl_divergence(real_samples, fake_samples)
>>> print(kl_div)
Source code in labproject/metrics/gaussian_kl.py
Gaussian Wasserstein
gaussian_squared_w2_distance(real_samples, fake_samples, real_mu=None, real_cov=None)
Compute the squared Wasserstein distance between Gaussian approximations of real and fake samples. Dimensionality of the samples must be the same and >=2 (for covariance calculation).
In detail, for each set of samples, we calculate the mean and covariance matrix.
Then we calculate the squared Wasserstein distance between the two Gaussian approximations:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
real_samples |
Tensor
|
A tensor representing the real samples. |
required |
fake_samples |
Tensor
|
A tensor representing the fake samples. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: The KL divergence between the two Gaussian approximations. |
References
[1] https://en.wikipedia.org/wiki/Wasserstein_metric [2] https://arxiv.org/pdf/1706.08500.pdf
Examples:
>>> real_samples = torch.randn(100, 2) # 100 samples, 2-dimensional
>>> fake_samples = torch.randn(100, 2) # 100 samples, 2-dimensional
>>> w2 = gaussian_squared_w2_distance(real_samples, fake_samples)
>>> print(w2)
Source code in labproject/metrics/gaussian_squared_wasserstein.py
Sliced Wasserstein
rand_projections(embedding_dim, num_samples)
This function generates num_samples random samples from the latent space's unti sphere.r
Parameters:
Name | Type | Description | Default |
---|---|---|---|
embedding_dim |
int
|
dimention of the embedding |
required |
sum_samples |
int
|
number of samples |
required |
Return
torch.tensor: tensor of size (num_samples, embedding_dim)
Source code in labproject/metrics/sliced_wasserstein.py
sliced_wasserstein_distance(encoded_samples, distribution_samples, num_projections=50, p=2, device='cpu')
Sliced Wasserstein distance between encoded samples and distribution samples. Note that the SWD does not converge to the true Wasserstein distance, but rather it is a different proper distance metric.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoded_samples |
Tensor
|
tensor of encoded training samples |
required |
distribution_samples |
Tensor
|
tensor drawn from the prior distribution |
required |
num_projection |
int
|
number of projections to approximate sliced wasserstein distance |
required |
p |
int
|
power of distance metric |
2
|
device |
device
|
torch device 'cpu' or 'cuda' gpu |
'cpu'
|
Return
torch.Tensor: Tensor of wasserstein distances of size (num_projections, 1)
Source code in labproject/metrics/sliced_wasserstein.py
Main Modules
Data
download_file(remote_path, local_path)
Downloads a file from the Hetzner Storage Box.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
remote_path |
str
|
The path to the remote file to be downloaded. |
required |
local_path |
str
|
The path where the file should be saved locally. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
True if the download is successful, False otherwise. |
Example
if download_file('path/to/remote/file.txt', 'path/to/save/file.txt'): print("Download successful") else: print("Download failed")
Source code in labproject/data.py
get_dataset(name)
Get a dataset by name
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
Name of the dataset |
required |
n |
int
|
Number of samples |
required |
d |
int
|
Dimensionality of the samples |
required |
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: Dataset |
Source code in labproject/data.py
get_distribution(name)
Get a distribution by name
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
Name of the distribution |
required |
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: Distribution |
Source code in labproject/data.py
imagenet_conditional_model(n, d=2048, label=None, device='cpu', permute_if_no_label=True, save_path='data')
Get the conditional model embeddings for ImageNet
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n |
int
|
Number of samples |
required |
d |
int
|
Dimensionality of the embeddings. Defaults to 2048. |
2048
|
label |
int
|
Label, if None it takes random samples. Defaults to None. |
None
|
device |
str
|
Device. Defaults to "cpu". |
'cpu'
|
Returns:
Type | Description |
---|---|
torch.Tensor: ImageNet embeddings |
Source code in labproject/data.py
imagenet_test_embedding(n, d=2048, device='cpu', save_path='data')
Get the test embeddings for ImageNet
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n |
int
|
Number of samples |
required |
d |
int
|
Dimensionality of the embeddings. Defaults to 2048. |
2048
|
device |
str
|
Device. Defaults to "cpu". |
'cpu'
|
Returns:
Type | Description |
---|---|
torch.Tensor: ImageNet embeddings |
Source code in labproject/data.py
imagenet_unconditional_model_embedding(n, d=2048, device='cpu', save_path='data')
Get the unconditional model embeddings for ImageNet
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n |
int
|
Number of samples |
required |
d |
int
|
Dimensionality of the embeddings. Defaults to 2048. |
2048
|
device |
str
|
Device. Defaults to "cpu". |
'cpu'
|
Returns:
Type | Description |
---|---|
torch.Tensor: ImageNet embeddings |
Source code in labproject/data.py
imagenet_validation_embedding(n, d=2048, device='cpu', save_path='data')
Get the validation embeddings for ImageNet
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n |
int
|
Number of samples |
required |
d |
int
|
Dimensionality of the embeddings. Defaults to 2048. |
2048
|
device |
str
|
Device. Defaults to "cpu". |
'cpu'
|
Returns:
Type | Description |
---|---|
torch.Tensor: ImageNet embeddings |
Source code in labproject/data.py
load_cifar10(n, save_path='data', train=True, batch_size=100, shuffle=False, num_workers=1, device='cpu', return_labels=False)
Load a subset of cifar10
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n |
int
|
Number of samples to load |
required |
save_path |
str
|
Path to save files. Defaults to "data". |
'data'
|
train |
bool
|
Train or test. Defaults to True. |
True
|
batch_size |
int
|
Batch size. Defaults to 100. |
100
|
shuffle |
bool
|
Shuffle. Defaults to False. |
False
|
num_workers |
int
|
Parallel workers. Defaults to 1. |
1
|
device |
str
|
Device. Defaults to "cpu". |
'cpu'
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: Cifar10 embeddings |
Source code in labproject/data.py
register_dataset(name)
This decorator wrapps a function that should return a dataset and ensures that the dataset is a PyTorch tensor, with the correct shape.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func |
callable
|
Dataset generator function |
required |
Returns:
Name | Type | Description |
---|---|---|
callable |
callable
|
Dataset generator function wrapper |
Example
@register_dataset("random") def random_dataset(n=1000, d=10): return torch.randn(n, d)
Source code in labproject/data.py
register_distribution(name)
This decorator wrapps a function that should return a dataset and ensures that the dataset is a PyTorch tensor, with the correct shape.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func |
callable
|
Dataset generator function |
required |
Returns:
Name | Type | Description |
---|---|---|
callable |
callable
|
Dataset generator function wrapper |
Example
@register_dataset("random") def random_dataset(n=1000, d=10): return torch.randn(n, d)
Source code in labproject/data.py
upload_file(local_path, remote_path)
Uploads a file to the Hetzner Storage Box.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
local_path |
str
|
The path to the local file to be uploaded. |
required |
remote_path |
str
|
The path where the file should be uploaded on the remote server. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
True if the upload is successful, False otherwise. |
Example
if upload_file('path/to/your/local/file.txt', 'path/to/remote/file.txt'): print("Upload successful") else: print("Upload failed")
Source code in labproject/data.py
Embeddings
This contains embedding nets, and auxilliary functions for extracting (N,D) embeddings from respective data and models.
Experiments
ScaleDim
Bases: Experiment
Source code in labproject/experiments.py
ScaleHyperparameter
Bases: Experiment
Source code in labproject/experiments.py
ScaleSampleSize
Bases: Experiment
Source code in labproject/experiments.py
log_results(results, log_path)
run_experiment(dataset1, dataset2, nb_runs=5, sample_sizes=None, **kwargs)
Computes for each subset 5 different random subsets and averages performance across the subsets.
Source code in labproject/experiments.py
Plotting
place_boxplot(ax, x, y, body_face_color='#8189c9', body_edge_color='k', body_lw=0.25, body_alpha=1.0, body_zorder=0, whisker_color='k', whisker_alpha=1.0, whisker_lw=1, whisker_zorder=1, cap_color='k', cap_lw=0.25, cap_zorder=1, median_color='k', median_alpha=1.0, median_lw=1.5, median_bar_length=1.0, median_zorder=10, width=0.5, scatter_face_color='k', scatter_edge_color='none', scatter_radius=5, scatter_lw=0.25, scatter_alpha=0.35, scatter_width=0.5, scatter=True, scatter_zorder=3, fill_box=True, showcaps=False, showfliers=False, whis=(0, 100), vert=True)
Example
X = [1, 2] Y = [np.random.normal(0.75, 0.12, size=50), np.random.normal(0.8, 0.20, size=25)] fig, ax = plt.subplots(figsize=[1, 1]) for (x, y) in zip(X, Y): place_boxplot(ax, x, y)
Source code in labproject/plotting.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
|
place_violin(ax, x, y, body_face_color='#8189c9', body_edge_color='k', body_lw=0.25, body_alpha=1.0, body_zorder=0, whisker_color='k', whisker_alpha=1.0, whisker_lw=1, whisker_zorder=1, cap_color='k', cap_lw=0.25, cap_zorder=1, median_color='k', median_alpha=1.0, median_lw=1.5, median_bar_length=1.0, median_zorder=10, width=0.5, scatter_face_color='k', scatter_edge_color='none', scatter_radius=5, scatter_lw=0.25, scatter_alpha=0.35, scatter_width=0.5, scatter=True, scatter_zorder=3, showextrema=True, showmedians=True, showmeans=False, vert=True)
Example
X = [1, 2] Y = [np.random.normal(0.75, 0.12, size=50), np.random.normal(0.8, 0.20, size=25)] fig, ax = plt.subplots(figsize=[1, 1]) for (x, y) in zip(X, Y): place_violin(ax, x, y)
Source code in labproject/plotting.py
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 |
|
plot_scaling_metric_dimensionality(dim_sizes, distances, errors, metric_name, dataset_name, ax=None, label=None, **kwargs)
Plot the scaling of a metric with increasing dimensionality.
Source code in labproject/plotting.py
plot_scaling_metric_sample_size(sample_size, distances, errors, metric_name, dataset_name, ax=None, label=None, **kwargs)
Plot the behavior of a metric with number of samples.
Source code in labproject/plotting.py
Utils
get_cfg()
This function returns the configuration file for the current experiment run.
The configuration file is expected to be located at ../configs/conf_{name}.yaml, where name will match the name of the run_{name}.py file.
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the configuration file is not found |
Returns:
Name | Type | Description |
---|---|---|
OmegaConf |
OmegaConf
|
Dictionary with the configuration parameters |
Source code in labproject/utils.py
get_cfg_from_file(name)
This function returns the configuration file for the current experiment run.
The configuration file is expected to be located at ../configs/{name}.yaml .
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the configuration file is not found |
Returns:
Name | Type | Description |
---|---|---|
OmegaConf |
OmegaConf
|
Dictionary with the configuration parameters |
Source code in labproject/utils.py
get_log_path(cfg, tag='', timestamp=True)
Get the log path for the current experiment run. This log path is then used to save the numerical results of the experiment. Import this function in the run_{name}.py file and call it to get the log path.
Source code in labproject/utils.py
load_experiments(cfg, tag='', now='')
load the experiments to run
Source code in labproject/utils.py
set_seed(seed)
Set seed for reproducibility
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seed |
int
|
Integer seed |
required |