This is an implementation of Noise Contrastive Estimation (NCE) in PyTorch on 2D dataset.
NCE is a method to estimate energy based models (EBM)
where
is the normalizing constant that is hard to compute. In NCE, the normalizing constant is treated as a trainable parameter
There are three requirements for the noise distribution
(1) log density can be evaluated on any input;
(2) samples can be obtained from the distribution;
(3)
Here we use Multivariate Gaussian as the noise distribution.
The objective is to maximize the posterior log-likelihood of the classification
This objective is implemented in the file util.py as the value
function (we minimize $-V(\theta)$). We use Adam as the optimizer.
Clone the repository to your local machine with
git clone https://github.com/lifeitech/nce.git
In your python environment, cd
to the repository, and
pip install -r requirements.txt
To train the model, do
python trian.py
For MacOS users, since currently PyTorch only has limited support for mps
, make sure to run the script with PYTORCH_ENABLE_MPS_FALLBACK=1
. You can add
export PYTORCH_ENABLE_MPS_FALLBACK=1
to your .zshrc
file.
Available datasets:
8gaussians
(default)2spirals
checkerboard
rings
pinwheel
A density plot is saved in the folder images
after every epoch. After training, you can obtain gif images like below by executing the python script in the folder:
cd images
python create_gif.py
Some visualizations of the learned energy densities are listed below.
8gaussians
dataset
pinwheel
dataset
2spirals
dataset