|
6 | 6 | get_var_type, |
7 | 7 | get_transform, |
8 | 8 | ) |
| 9 | +import torch |
| 10 | +from spotPython.light.csvdataset import CSVDataset |
| 11 | +from torch.utils.data import DataLoader |
| 12 | +import matplotlib.pyplot as plt |
| 13 | +import math |
| 14 | +import seaborn as sns |
9 | 15 |
|
10 | 16 |
|
11 | 17 | def get_stars(input_list) -> list: |
@@ -110,3 +116,58 @@ def generate_config_id(config): |
110 | 116 | for key in config: |
111 | 117 | config_id += str(config[key]) + "_" |
112 | 118 | return config_id[:-1] |
| 119 | + |
| 120 | + |
| 121 | +def visualize_activations(net, device="cpu", color="C0"): |
| 122 | + """Visualizes the activations of a neural network. |
| 123 | + Code is based on: |
| 124 | + PyTorch Lightning TUTORIAL 2: ACTIVATION FUNCTIONS, |
| 125 | + Author: Phillip Lippe, |
| 126 | + License: CC BY-SA. |
| 127 | +
|
| 128 | + Args: |
| 129 | + net (object): A neural network. |
| 130 | + device (str, optional): The device to use. Defaults to "cpu". |
| 131 | + color (str, optional): The color to use. Defaults to "C0". |
| 132 | + Example: |
| 133 | + >>> from spotPython.hyperparameters.values import get_one_config_from_X |
| 134 | + >>> X = spot_tuner.to_all_dim(spot_tuner.min_X.reshape(1,-1)) |
| 135 | + >>> config = get_one_config_from_X(X, fun_control) |
| 136 | + >>> model = fun_control["core_model"](**config, _L_in=64, _L_out=11) |
| 137 | + >>> visualize_activations(model, device="cpu", color=f"C{0}") |
| 138 | + """ |
| 139 | + activations = {} |
| 140 | + net.eval() |
| 141 | + # Create an instance of CSVDataset |
| 142 | + dataset = CSVDataset(csv_file="./data/VBDP/train.csv", train=True) |
| 143 | + # Set batch size for DataLoader |
| 144 | + batch_size = 128 |
| 145 | + # Create DataLoader |
| 146 | + dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True) |
| 147 | + # for batch in dataloader: |
| 148 | + # inputs, targets = batch |
| 149 | + # small_loader = data.DataLoader(train_set, batch_size=1024) |
| 150 | + inputs, _ = next(iter(dataloader)) |
| 151 | + with torch.no_grad(): |
| 152 | + layer_index = 0 |
| 153 | + inputs = inputs.to(device) |
| 154 | + inputs = inputs.view(inputs.size(0), -1) |
| 155 | + # We need to manually loop through the layers to save all activations |
| 156 | + for layer_index, layer in enumerate(net.layers[:-1]): |
| 157 | + inputs = layer(inputs) |
| 158 | + activations[layer_index] = inputs.view(-1).cpu().numpy() |
| 159 | + |
| 160 | + # Plotting |
| 161 | + columns = 4 |
| 162 | + rows = math.ceil(len(activations) / columns) |
| 163 | + fig, ax = plt.subplots(rows, columns, figsize=(columns * 2.7, rows * 2.5)) |
| 164 | + fig_index = 0 |
| 165 | + for key in activations: |
| 166 | + key_ax = ax[fig_index // columns][fig_index % columns] |
| 167 | + sns.histplot(data=activations[key], bins=50, ax=key_ax, color=color, kde=True, stat="density") |
| 168 | + key_ax.set_title(f"Layer {key} - {net.layers[key].__class__.__name__}") |
| 169 | + fig_index += 1 |
| 170 | + fig.suptitle(f"Activation distribution for activation function {net.act_fn}", fontsize=14) |
| 171 | + fig.subplots_adjust(hspace=0.4, wspace=0.4) |
| 172 | + plt.show() |
| 173 | + plt.close() |
0 commit comments