Package: loss-landscape-anim
Animating the Optimization Trajectory of Neural Netsloss-landscape-animlets you create animated optimization path in a 2D slice of the loss landscape of your neural networks. It is based onPyTorch Lightning, please follow its suggested style if you want to add your own model.Check out my articleVisualizing Optimization Trajectory of Neural Netsfor more examples and some intuitive explanations.0. InstallationFrom PyPI:pipinstallloss-landscape-animFrom source, you needPoetry. Once you cloned this repo, run the command below to install the dependencies.poetryinstall1. Basic ExamplesWith the providedspirals datasetand the default multilayer perceptronMLPmodel, you can directly callloss_landscape_animto get a sample animated GIF like this:# Use default MLP model and sample spirals datasetloss_landscape_anim(n_epochs=300)Note: if you are using it in a notebook, don't forget to include the following at the top:%matplotlibnotebookHere's another example – the LeNet5 convolutional network on the MNIST dataset. There are many levers you can tune: learning rate, batch size, epochs, frames per second of the GIF output, a seed for reproducible results, whether to load from a trained model, etc. Check out the function signature for more details.bs=16lr=1e-3datamodule=MNISTDataModule(batch_size=bs,n_examples=3000)model=LeNet(learning_rate=lr)optim_path,loss_steps,accu_steps=loss_landscape_anim(n_epochs=10,model=model,datamodule=datamodule,optimizer="adam",giffps=15,seed=SEED,load_model=False,output_to_file=True,return_data=True,# Optional return values if you need themgpus=1# Enable GPU training if available)GPU training is supported. Just passgpusintoloss_landscape_animif they are available.The output of LeNet5 on the MNIST dataset looks like this:2. Why PCA?To create a 2D visualization, the first thing to do is to pick the 2 directions that define the plane. In the paperVisualizing the Loss Landscape of Neural Nets, the authors argued why 2 random directions don't work and why PCA is much better. In summary,2 random vectors in high dimensional space have a high probability of being orthogonal, and they can hardly capture any variation for the optimization path. The path’s projection onto the plane spanned by the 2 vectors will just look like random walk.If we pick one direction to be the vector pointing from the initial parameters to the final trained parameters, and another direction at random, the visualization will look like a straight line because the second direction doesn’t capture much variance compared to the first.If we use principal component analysis (PCA) on the optimization path and get the top 2 components, we can visualize the loss over the 2 orthogonal directions with the most variance.For showingthe most motion in 2D, PCA is preferred. If you need a quick recap on PCA, here's aminimal exampleyou can go over under 3 minutes.3. Random and Custom DirectionsAlthough PCA is a good approach for picking the directions, if you need more control, the code also allows you to set any 2 fixed directions, either generated at random or handpicked.For 2 random directions, setreduction_methodto"random", e.g.loss_landscape_anim(n_epochs=300,load_model=False,reduction_method="random")For 2 fixed directions of your choosing, setreduction_methodto"custom", e.g.importnumpyasnpn_params=...# number of parameters your model hasu_gen=np.random.normal(size=n_params)u=u_gen/np.linalg.norm(u_gen)v_gen=np.random.normal(size=n_params)v=v_gen/np.linalg.norm(v_gen)loss_landscape_anim(n_epochs=300,load_model=False,reduction_method="custom",custom_directions=(u,v))Here is an sample GIF produced by two random directions:By default,reduction_method="pca".4. Custom Dataset and ModelPrepare yourDataModule. Refer todatamodule.pyfor examples.Define your custom model that inheritsmodel.GenericModel. Refer tomodel.pyfor examples.Once you correctly setup your customDataModuleandmodel, call the function as shown below to train the model and plot the loss landscape animation.bs=...lr=...datamodule=YourDataModule(batch_size=bs)model=YourModel(learning_rate=lr)loss_landscape_anim(n_epochs=10,model=model,datamodule=datamodule,optimizer="adam",seed=SEED,load_model=False,output_to_file=True)5. Comparing Different OptimizersAs mentioned in section 2, the optimization path usually falls into a very low-dimensional space, and its projection in other directions may look like random walk. On the other hand, different optimizers can take very different paths in the high dimensional space. As a result, it is difficult to pick 2 directions to effectively compare different optimizers.In this example, I haveadam, sgd, adagrad, rmspropinitialized with the same parameters. The two figures below share the same 2 random directions but are centered around different local minima. The first figure centers around the one Adam finds, the second centers around the one RMSprop finds. Essentially, the planes are 2 parallel slices of the loss landscape.The first figure shows that when centering on the end of Adam's path, it looks like RMSprop is going somewhere with larger loss value. Butthat is an illusion. If you inspect the loss values of RMSprop, it actually finds a local optimum that has a lower loss than Adam's.Same 2 directions centering on Adam's path:Same 2 directions centering on RMSprop's path:This is a good reminder that the contours are just a 2D slice out of a very high-dimensional loss landscape, and the projections can't reflect the actual path.However, we can see that the contours are convex no matter where it centers around in these 2 special cases. It more or less reflects that the optimizers shouldn't have a hard time finding a relatively good local minimum. To measure convexity more rigorously, the paper[1]mentioned a better method – usingprincipal curvature, i.e. the eigenvalues of the Hessian. Check out the end of section 6 in the paper for more details.Reference[1]Visualizing the Loss Landscape of Neural Nets