This repository contains the source code and data for reproducing results of Deep Continuous Clustering paper

Overview

Deep Continuous Clustering

Introduction

This is a Pytorch implementation of the DCC algorithms presented in the following paper (paper):

Sohil Atul Shah and Vladlen Koltun. Deep Continuous Clustering.

If you use this code in your research, please cite our paper.

@article{shah2018DCC,
	author    = {Sohil Atul Shah and Vladlen Koltun},
	title     = {Deep Continuous Clustering},
	journal   = {arXiv:1803.01449},
	year      = {2018},
}

The source code and dataset are published under the MIT license. See LICENSE for details. In general, you can use the code for any purpose with proper attribution. If you do something interesting with the code, we'll be happy to know. Feel free to contact us.

Requirement

Pretraining SDAE

Note: Please find required files and checkpoints for MNIST dataset shared here.

Please create new folder for each dataset under the data folder. Please follow the structure of mnist dataset. The training and the validation data for each dataset must be placed under their respective folder.

We have already provided train and test data files for MNIST dataset. For example, one can start pretraining of SDAE from console as follows:

$ python pretraining.py --data mnist --tensorboard --id 1 --niter 50000 --lr 10 --step 20000

Different settings for total iterations, learning rate and stepsize may be required for other datasets. Please find the details under the comment section inside the pretraining file.

Extracting Pretrained Features

The features from the pretrained SDAE network are extracted as follows:

$ python extract_feature.py --data mnist --net checkpoint_4.pth.tar --features pretrained

By default, the model checkpoint for pretrained SDAE NW is stored under results.

Copying mkNN graph

The copyGraph program is used to merge the preprocessed mkNN graph (using the code provided by RCC) and the extracted pretrained features. Note the mkNN graph is built on the original and not on the SDAE features.

$ python copyGraph.py --data mnist --graph pretrained.mat --features pretrained.pkl --out pretrained

The above command assumes that the graph is stored in the pretrained.mat file and the merged file is stored back to pretrained.mat file.

DCC searches for the file with name pretrained.mat. Hence please retain the name.

Running Deep Continuous Clustering

Once the features are extracted and graph details merged, one can start training DCC algorithm.

For sanity check, we have also provided a pretrained.mat and SDAE model files for the MNIST dataset located under the data folder. For example, one can run DCC on MNIST from console as follows:

$ python DCC.py --data mnist --net checkpoint_4.pth.tar --tensorboard --id 1

The other preprocessed graph files can be found in gdrive folder as provided by the RCC.

Evaluation

Towards the end of run of DCC algorithm, i.e., once the stopping criterion is met, DCC starts evaluating the cluster assignment for the total dataset. The evaluation output is logged into tensorboard logger. The penultimate evaluated output is reported in the paper.

Like RCC, the AMI definition followed here differs slightly from the default definition found in the sklearn package. To match the results listed in the paper, please modify it accordingly.

The tensorboard logs for both pretraining and DCC will be stored in the "runs/DCC" folder under results. The final embedded features 'U' and cluster assignment for each sample is saved in 'features.mat' file under results.

Creating input

The input file for SDAE pretraining, traindata.mat and testdata.mat, stores the features of the 'N' data samples in a matrix format N x D. We followed 4:1 ratio to split train and validation data. The provided make_data.py can be used to build training and validation data. The distinction of training and validation set is used only for the pretraining stage. For end-to-end training, there is no such distinction in unsupervised learning and hence all data has been used.

To construct mkNN edge set and to create preprocessed input file, pretrained.mat, from the raw feature file, use edgeConstruction.py released by RCC. Please follow the instruction therein. Note that mkNN graph is built on the complete dataset. For simplicity, code (post pretraining phase) follows the data ordering of [trainset, testset] to arrange the data. This should be consistent even with mkNN construction.

Understanding Steps Through Visual Example

Generate 2D clustered data with

python make_data.py --data easy

This creates 3 clusters where the centers are colinear to each other. We would then expect to only need 1 dimensional latent space (either x or y) to uniquely project the data onto the line passing through the center of the clusters.

generated ground truth

Construct mKNN graph with

python edgeConstruction.py --dataset easy --samples 600

Pretrain SDAE with

python pretraining.py --data easy --tensorboard --id 1 --niter 500 --dim 1 --lr 0.0001 --step 300

You can debug the pretraining losses using tensorboard (needs tensorflow) with

tensorboard --logdir data/easy/results/runs/pretraining/1/

Then navigate to the http link that is logged in console.

Extract pretrained features

python extract_feature.py --data easy --net checkpoint_2.pth.tar --features pretrained --dim 1

Merge preprocessed mkNN graph and the pretrained features with

python copyGraph.py --data easy --graph pretrained.mat --features pretrained.pkl --out pretrained

Run DCC with

python DCC.py --data easy --net checkpoint_2.pth.tar --tensorboard --id 1 --dim 1

Debug and show how the representatives shift over epochs with

tensorboard --logdir data/easy/results/runs/DCC/1/ --samples_per_plugin images=100

Pretraining and DCC together in one script

See easy_example.py for the previous easy to visualize example all steps done in one script. Execute the script to perform the previous section all together. You can visualize the results, such as how the representatives drift over iterations with the tensorboard command above and navigating to the Images tab.

With an autoencoder, the representatives shift over epochs like: shift with autoencoder

Comments
  • Problem to open MNIST data

    Problem to open MNIST data

    Hi, I am trying to repeat the result. When I am trying to open the data of MNIST provided, the error raised:

    >>> data = sio.loadmat('testdata.mat', mat_dtype=True)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/xsede/users/xs-ttgump/.local/lib/python3.6/site-packages/scipy/io/matlab/mio.py", line 141, in loadmat
        MR, file_opened = mat_reader_factory(file_name, appendmat, **kwargs)
      File "/home/xsede/users/xs-ttgump/.local/lib/python3.6/site-packages/scipy/io/matlab/mio.py", line 65, in mat_reader_factory
        mjv, mnv = get_matfile_version(byte_stream)
      File "/home/xsede/users/xs-ttgump/.local/lib/python3.6/site-packages/scipy/io/matlab/miobase.py", line 241, in get_matfile_version
        raise ValueError('Unknown mat file type, version %s, %s' % ret)
    ValueError: Unknown mat file type, version 54, 50
    

    It seems like the mat format provided by authors are not correct. Thanks.

    opened by ttgump 8
  • Simple visual example dataset processed end-to-end

    Simple visual example dataset processed end-to-end

    It would be good to have a really simple and small data set that could be easily visualized (2D clusters like below) to train end-to-end. This would be helpful to me because it would clarify where pre-training and creating the mkNN graph comes in. I'm planning to create and work with such a data set then submit a pull request; are there any gotcha's I should be aware of?

    image

    opened by LemonPi 7
  • a question about mknn

    a question about mknn

    Hi @shahsohil , the work is very interesting! I have a question about the construction of mKNN graph. In the project, I find that you use the original data to measure the similarity and construct the mkNN graph. Is there a particular reason here? Why not use the latent representation feature of the pretrained AE for the graph? If I have a large image patch, e.g. 256x256 with multiple input bands, it will be a large computation cost for the creation of graph in the original image space.

    Thank you.

    opened by jiankang1991 5
  • Empty data folder on clone or download as zip

    Empty data folder on clone or download as zip

    The MNIST data after cloning or downloading holds empty files - each file is only around 130 bytes and their content is actual text with something like:

    version https://git-lfs.github.com/spec/v1
    oid sha256:e60446c5fac6df3e3f37769ca5b51669a2da7d6a3a6abc9fc9a8cc2b4244a18d
    size 26650347
    

    So it's actually the file descriptor instead of the actual file. It would be best to provide an alternative source for the whole MNIST data set including the checkpoints in addition to the .mat files that already exist.

    For any future searches that encounters an error like

        magic_number = pickle_module.load(f)
    _pickle.UnpicklingError: invalid load key, 'v'.
    

    This is because the checkpoint is actually empty...

    opened by LemonPi 3
  • Clarification of 'Z' and 'U'

    Clarification of 'Z' and 'U'

    Just to clarify, is 'Z' the representations after SDAE but before fine tuning with DCC and 'U' is after fine tuning with DCC? Got a little confused because in the paper it appears that 'Y' is the representations after SDAE and 'Z' are the representations after fine-tuning...

    opened by scottfleming 3
  • Ambiguity surrounding pretrained.mat

    Ambiguity surrounding pretrained.mat

    It's unclear to me from the documentation how pretrained.mat is supposed to be generated. pretraining.py takes in data/mydataset/traindata.mat and data/mydataset/testdata.mat and spits out data/mydataset/results/checkpoint_4.pth.tar such that when extract_feature.py takes in checkpoint_4.pth.tar it spits out a matrix of n_train + n_test. But are we then supposed to run RCC's edgeConstruction module on traindata.mat or testdata.mat or a combination of the two in order to produce pretrained.mat? If we do it on just one of them and then feed the resulting graph into copyGraph.py it'll throw a shape mismatch error...

    opened by scottfleming 3
  • download error

    download error

    $ git clone https://github.com/shahsohil/DCC.git Cloning into 'DCC'... remote: Enumerating objects: 76, done. remote: Total 76 (delta 0), reused 0 (delta 0), pack-reused 76 Unpacking objects: 100% (76/76), done. Downloading data/mnist/pretrained.mat (227 MB) Error downloading object: data/mnist/pretrained.mat (bb0b757): Smudge error: Error downloading data/mnist/pretrained.mat (bb0b757ef4918b0f218c0e8b7d530c613ca60d5d1d0a81c1c1c33a34642fa057): batch response: This repository is over its data quota. Purchase more data packs to restore access.

    Errors logged to R:\GitHub\DCC.git\lfs\logs\20190225T132833.506642.log Use git lfs logs last to view the log. error: external filter 'git-lfs filter-process' failed fatal: data/mnist/pretrained.mat: smudge filter lfs failed warning: Clone succeeded, but checkout failed. You can inspect what was checked out with 'git status' and retry the checkout with 'git checkout -f HEAD'

    Who knows how to solve this question?

    opened by huweibo 3
  • Clustering result problem

    Clustering result problem

    Hi, thank you for your work. I applied this algorithm to my own data, but most of the data are divided into the first cluster. What is the cause of it, please? What kind of improvement do I need to do?

    opened by weishao6hao 3
  • IndexError in easy_example.py

    IndexError in easy_example.py

    Running easy_example.py without any changes results in an IndexError at line 74 in DCCComputation.py (error below). This seems to arise because the largest epsilon is greater than NOISE_THRESHOLD but smaller than DIM*NOISE_THRESHOLD.

    https://github.com/shahsohil/DCC/blob/d918a89be020eb87d5893ff3591e08daa84422c4/pytorch/DCCComputation.py#L66

    pytorch version: 1.3.0.dev20190819 numpy version: 1.16.4 scipy version: 1.2.1

    Loaded `easy` dataset for finetuning
    /home/sxie22/miniconda3/envs/sisso/lib/python3.7/site-packages/numpy/lib/function_base.py:392: RuntimeWarning: Mean of empty slice.
      avg = a.mean(axis)
    /home/sxie22/miniconda3/envs/sisso/lib/python3.7/site-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in true_divide
      ret = ret.dtype.type(ret / rcount)
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    ~/PycharmProjects/vanDuin/DCC/pytorch/easy_example.py in <module>
         86 args.M = 20
         87 args.lr = 0.001
    ---> 88 out = DCC.main(args, net=net)
    
    ~/PycharmProjects/vanDuin/DCC/pytorch/DCC.py in main(args, net)
        108 
        109     # computing and initializing the hyperparams
    --> 110     _sigma1, _sigma2, _lambda, _delta, _delta1, _delta2, lmdb, lmdb_data = computeHyperParams(pairs, Z)
        111     oldassignment = np.zeros(len(pairs))
        112     stopping_threshold = int(math.ceil(cfg.STOPPING_CRITERION * float(len(pairs))))
    
    ~/PycharmProjects/vanDuin/DCC/pytorch/DCCComputation.py in computeHyperParams(pairs, Z)
         72     robsamp = min(cfg.RCC.MAX_NUM_SAMPLES_DELTA, robsamp)
         73     _delta2 = float(np.average(epsilon[:robsamp]) / 2)
    ---> 74     _sigma2 = float(3 * (epsilon[-1] ** 2))
         75 
         76     _delta1 = float(np.average(np.linalg.norm(Z - np.average(Z, axis=0)[np.newaxis, :], axis=1) ** 2))
    
    IndexError: index -1 is out of bounds for axis 0 with size 0
    
    In [2]: debug                                                                                        
    > /home/sxie22/PycharmProjects/vanDuin/DCC/pytorch/DCCComputation.py(74)computeHyperParams()
         72     robsamp = min(cfg.RCC.MAX_NUM_SAMPLES_DELTA, robsamp)
         73     _delta2 = float(np.average(epsilon[:robsamp]) / 2)
    ---> 74     _sigma2 = float(3 * (epsilon[-1] ** 2))
         75 
         76     _delta1 = float(np.average(np.linalg.norm(Z - np.average(Z, axis=0)[np.newaxis, :], axis=1) ** 2))
    
    ipdb> epsilon = np.linalg.norm(Z[pairs[:, 0].astype(int)] - Z[pairs[:, 1].astype(int)], axis=1)      
    ipdb> epsilon = np.sort(epsilon)                                                                     
    ipdb> epsilon[-1]                                                                                    
    0.011799936
    ipdb> np.sqrt(cfg.DIM)                                                                               
    3.1622776601683795
    ipdb> cfg.DIM                                                                                        
    10
    
    opened by sxie22 2
  • Visual end-to-end example and python3 compatibility

    Visual end-to-end example and python3 compatibility

    This pull request adds a step by step guide on an artificial data set that's easy to visualize. An end-to-end training script is in easy_example.py.

    It also brings python3 compatibility, centralizing where problem specific network architecture is defined, and bug fixes.

    Addresses #14 and #13

    opened by LemonPi 2
  • Stopping threshold bug?

    Stopping threshold bug?

    The paper says we stop when change in assignment is below the stopping threshold, but the code implements this as:

                if change_in_assign > stopping_threshold:
                    flag += 1
                if flag == 4:
                    break
    

    This is a bug right? It should be if change_in_assign < stopping_threshold: I'll fix this in my pull request if so.

    opened by LemonPi 2
  • Would it be possible to

    Would it be possible to "classify" new images after training DCC on a dataset?

    So if I have a data set A, and train DCC on A, is it theoretically possible to introduce a small data set B (around 1 image or so) to the clustering with only minimal effort/a few extra iterations of DCC training?

    opened by Detzy 0
  • Hyperparams and resulting numbers

    Hyperparams and resulting numbers

    Hi, thank you so much for your contribution and sharing your project! This is a great paper :) I would highly appreciate your help with running the training process as I am not sure how to run certain parts of it in order to reproduce your results from the paper.

    1. How should we run the edgeConstruction script? Which hyperparams should we choose?
    2. Do you have available configurations for more datasets?
    3. Using the following commands I got fairly good numbers on MNIST, but lower than the reported ones. Can you perhaps guide me how to get closer to the reported numbers?

    Script lines: python pretraining.py --data mnist --id 1 --niter 50000 --lr 10 --step 20000 python extract_feature.py --data mnist --net checkpoint_4.pth.tar --features pretrained python edgeConstruction.py --dataset mnist --format mat --samples 70000 --prep 'minmax' --k 10 --algo 'mknn' python copyGraph.py --data mnist --graph pretrained.mat --features pretrained.pkl --out pretrained python DCC.py --data mnist --net checkpoint_4.pth.tar --id 1 The results I got: ARI: 0.830861826385 AMI: 0.7969629161498257 NMI: 0.8647221174121507 ACC: 0.8187 K: 173

    Thank you so much in advance!!

    opened by meitarronen 0
  • ERROR not create file checkpoint_2.pth.tar  in          easy/results/runs/         only created file checkpoint_0.pth.tar and checkpoint_1.pth.tar     in          easy/results/runs/

    ERROR not create file checkpoint_2.pth.tar in easy/results/runs/ only created file checkpoint_0.pth.tar and checkpoint_1.pth.tar in easy/results/runs/

    Untitled 1- !python2 make_data.py --data easy 2- !python2 edgeConstruction.py --dataset easy --samples 600 3- !python2 pretraining.py --data easy --tensorboard --id 1 --niter 500 --dim 1 --lr 0.0001 --step 300 4- !python2 extract_feature.py --data easy --net checkpoint_2.pth.tar --features pretrained --dim 1

    Loaded easy dataset for finetuning The endpoints are Delta1: 0.000, Delta2: 0.005 ==> no checkpoint found at '/data/easy/results/checkpoint_2.pth.tar' Traceback (most recent call last): File "DCC.py", line 336, in main(args) File "DCC.py", line 120, in main load_weights(args, outputdir, net) File "DCC.py", line 221, in load_weights raise ValueError ValueError

    opened by MahdiCmtr 1
  • Clustering problems

    Clustering problems

    Hello, thank you very much for sharing your project!

    I'm trying to apply this algorithm on a set of RGB images (cartoons), in particular I have 2344 samples with dimension [227,227,3] composed by 7 classes. The algorithm is not able to correctly cluster the images, at the end I have ~ 0.2 ACC with 1220 clusters. I read carefully all the issues solved in this repository but I cannot solve my problem so I list each step that I did to have a feedback about a possibile mistake:

    1. I made my dataset using the file "make_data.py" using normalization [-1,1]. At the end I have testdata.mat and traindata.mat. Each row in this matrices is composed by the concatenation of the three channels, so I have [R,G,B] -> [51529,51529,51529] (51529=227x227). Considering together testdata.mat and traindata.mat I have a matrix 2344x154587.

    2. Next I run the "pretraining.py" file using --batch_size=256, --niter=1831 (in order to have 200 epochs as suggested), --step=733 (to have 80 epochs as suggested) --lr=0.01 (since the dimension of the data samples is higher than the other datasets used with this framework I though that this could be a good choice for mine), --dim=10.

    3. With the file checkpoint_4.pth.tar obtained after 2 I extract the features of the dataset obtaining "pretrained.pkl".

    4. I construct the graph with the original data using "edge_construction.py" with --algo knn, --k 10, --samples 2344 and I get "pretrained.mat" file.

    5. After I launch "copyGraph.py" to the final "pretrained.mat" file.

    6. Finally I use "DCC.py" leaving all the default values.

    I tried also to use an higher k (k=20) and mknn instead of knn but the things seems not change. Do you have any idea about the reason why the algorithm not work properly with my data?

    opened by silvia1993 2
  • two quetions

    two quetions

    Hi I have couple of questions: 1-in config.py

    Fraction of "change in label assignment of pairs" to be considered for stopping criterion - 1% of pairs __C.STOPPING_CRITERION = 0.001

    isn't should be 0.01?

    2-the lambda parameter is the λ coefficient in the paper?

    Thank you

    opened by mz3220 0
Owner
Sohil Shah
Research Scientist
Sohil Shah
Awesome Deep Graph Clustering is a collection of SOTA, novel deep graph clustering methods

ADGC: Awesome Deep Graph Clustering ADGC is a collection of state-of-the-art (SOTA), novel deep graph clustering methods (papers, codes and datasets).

yueliu1999 297 Dec 27, 2022
This repository contains the code and models necessary to replicate the results of paper: How to Robustify Black-Box ML Models? A Zeroth-Order Optimization Perspective

Black-Box-Defense This repository contains the code and models necessary to replicate the results of our recent paper: How to Robustify Black-Box ML M

OPTML Group 2 Oct 5, 2022
This repository contains the code and models necessary to replicate the results of paper: How to Robustify Black-Box ML Models? A Zeroth-Order Optimization Perspective

Black-Box-Defense This repository contains the code and models necessary to replicate the results of our recent paper: How to Robustify Black-Box ML M

OPTML Group 2 Oct 5, 2022
Repository for reproducing `Model-Based Robust Deep Learning`

Model-Based Robust Deep Learning (MBRDL) In this repository, we include the code necessary for reproducing the code used in Model-Based Robust Deep Le

Alex Robey 16 Sep 19, 2022
Code for: Gradient-based Hierarchical Clustering using Continuous Representations of Trees in Hyperbolic Space. Nicholas Monath, Manzil Zaheer, Daniel Silva, Andrew McCallum, Amr Ahmed. KDD 2019.

gHHC Code for: Gradient-based Hierarchical Clustering using Continuous Representations of Trees in Hyperbolic Space. Nicholas Monath, Manzil Zaheer, D

Nicholas Monath 35 Nov 16, 2022
PyTorch framework, for reproducing experiments from the paper Implicit Regularization in Hierarchical Tensor Factorization and Deep Convolutional Neural Networks

Implicit Regularization in Hierarchical Tensor Factorization and Deep Convolutional Neural Networks. Code, based on the PyTorch framework, for reprodu

Asaf 3 Dec 27, 2022
MLOps will help you to understand how to build a Continuous Integration and Continuous Delivery pipeline for an ML/AI project.

page_type languages products description sample python azure azure-machine-learning-service azure-devops Code which demonstrates how to set up and ope

null 1 Nov 1, 2021
Code for reproducing our analysis in the paper titled: Image Cropping on Twitter: Fairness Metrics, their Limitations, and the Importance of Representation, Design, and Agency

Image Crop Analysis This is a repo for the code used for reproducing our Image Crop Analysis paper as shared on our blog post. If you plan to use this

Twitter Research 239 Jan 2, 2023
This repository holds the code for the paper "Deep Conditional Gaussian Mixture Model forConstrained Clustering".

Deep Conditional Gaussian Mixture Model for Constrained Clustering. This repository holds the code for the paper Deep Conditional Gaussian Mixture Mod

null 17 Oct 30, 2022
An official source code for paper Deep Graph Clustering via Dual Correlation Reduction, accepted by AAAI 2022

Dual Correlation Reduction Network An official source code for paper Deep Graph Clustering via Dual Correlation Reduction, accepted by AAAI 2022. Any

yueliu1999 109 Dec 23, 2022
Graph Regularized Residual Subspace Clustering Network for hyperspectral image clustering

Graph Regularized Residual Subspace Clustering Network for hyperspectral image clustering

Yaoming Cai 5 Jul 18, 2022
This repository contains a set of codes to run (i.e., train, perform inference with, evaluate) a diarization method called EEND-vector-clustering.

EEND-vector clustering The EEND-vector clustering (End-to-End-Neural-Diarization-vector clustering) is a speaker diarization framework that integrates

null 45 Dec 26, 2022
The LaTeX and Python code for generating the paper, experiments' results and visualizations reported in each paper is available (whenever possible) in the paper's directory

This repository contains the software implementation of most algorithms used or developed in my research. The LaTeX and Python code for generating the

João Fonseca 3 Jan 3, 2023
Reproducing code of hair style replacement method from Barbershorp.

Barbershorp Reproducing code of hair style replacement method from Barbershorp. Also reproduces II2S, an improved version of Image2StyleGAN. Requireme

null 1 Dec 24, 2021
This repository contains the source code for the paper "DONeRF: Towards Real-Time Rendering of Compact Neural Radiance Fields using Depth Oracle Networks",

DONeRF: Towards Real-Time Rendering of Compact Neural Radiance Fields using Depth Oracle Networks Project Page | Video | Presentation | Paper | Data L

Facebook Research 281 Dec 22, 2022
This repository contains the code for "SBEVNet: End-to-End Deep Stereo Layout Estimation" paper by Divam Gupta, Wei Pu, Trenton Tabor, Jeff Schneider

SBEVNet: End-to-End Deep Stereo Layout Estimation This repository contains the code for "SBEVNet: End-to-End Deep Stereo Layout Estimation" paper by D

Divam Gupta 19 Dec 17, 2022
null 190 Jan 3, 2023
This repository contains the data and code for the paper "Diverse Text Generation via Variational Encoder-Decoder Models with Gaussian Process Priors" (SPNLP@ACL2022)

GP-VAE This repository provides datasets and code for preprocessing, training and testing models for the paper: Diverse Text Generation via Variationa

Wanyu Du 18 Dec 29, 2022
PySlowFast: video understanding codebase from FAIR for reproducing state-of-the-art video models.

PySlowFast PySlowFast is an open source video understanding codebase from FAIR that provides state-of-the-art video classification models with efficie

Meta Research 5.3k Jan 3, 2023