Code
import drnb.embed.pipeline as plA stochastic metric multi-dimensional scaling algorithm. Metric MDS is the version of MDS which tries to directly reproduce input distances in the output distances (i.e. no rescaling allowed). Effectively this is about reducing the stress:
\[ \mathrm{STRESS} = \sum_{i \lt j} \left(r_{ij} - d_{ij}\right)^2 \]
where \(r_{ij}\) is the input distance between item \(i\) and \(j\) and \(d_{ij}\) is the equivalent output distance. The sum is over all pairs \(\left(i, j\right)\) so this doesn’t scale very well.
This package implements a stochastic version of MMDS by the simple expedient of not sampling all pairs. Instead you set n_samples: for each item in the dataset, its distance to n_samples other items chosen randomly is measured and only those pairs are used to define the gradient. Some form of optimization which can be used with noisy stochastic gradients is then used to refine the coordinates. The default is to use Adam.
This approach is inspired by Stochastic Proximity Embedding (SPE) and SQuadMDS. The SQuadMDS github repo does not have a package available or even a license, so I can’t use it directly in drnb.
This notebook assumes you have run the tasic2018 and airfoil notebooks in the notebooks/data-pipeline folder.
sklearn offers the MDS class to carry out metric MDS. It is wrapped as the"mmds" method in drnb. Be aware that this class runs the embedding n_init times (by default 4) and keeps the best result, so you should factor that into its expected run-time. The airfoil dataset is small enough to handle this way. In the pipeline I have added an extra metric: "exact-stress". This calculates the stress for all pairs of items in the data although it reports the value as the square root of the mean, so it’s effectively the RMS of the disparity in distances. You should most definitely not use it for large or high-dimensional datasets. As a result, I have given this a slightly difficult-to-remember name so you can’t accidentally ask for it. Here we’ll use it with the Z-scaled airfoil dataset (as used in the SQuadMDS paper).

[EvalResult(eval_type='RTE', label='rte-5-euclidean', value=np.float64(0.8713240186294078), info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='RPC', label='rpc-5-euclidean', value=0.9116114377975464, info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='NNP', label='nnp-15-noself-euclidean', value=np.float64(0.5322687957418496), info={'metric': 'euclidean', 'n_neighbors': 15}),
EvalResult(eval_type='NNP', label='nnp-50-noself-euclidean', value=np.float64(0.49684630738522956), info={'metric': 'euclidean', 'n_neighbors': 50}),
EvalResult(eval_type='NNP', label='nnp-150-noself-euclidean', value=np.float64(0.6137103570636504), info={'metric': 'euclidean', 'n_neighbors': 150}),
EvalResult(eval_type='Stress', label='stress-euclidean', value=17.29172784235377, info={'metric': 'euclidean'})]
Now let’s see how well stochastic MMDS does. In addtion to exact-stress, I have also added "astress". This is an approximate version of the stress (with the same root-mean scaling), using the same stochastic sampling as used by the SMMDS method. This uses 3 random samples per item by default. I also provide a version using n_samples=10 (mainly so I don’t forget how to add parameters to the evaluation metric myself).

[EvalResult(eval_type='RTE', label='rte-5-euclidean', value=np.float64(0.8729208250166334), info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='RPC', label='rpc-5-euclidean', value=0.9149597883224487, info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='NNP', label='nnp-15-noself-euclidean', value=np.float64(0.477799955644267), info={'metric': 'euclidean', 'n_neighbors': 15}),
EvalResult(eval_type='NNP', label='nnp-50-noself-euclidean', value=np.float64(0.48902195608782434), info={'metric': 'euclidean', 'n_neighbors': 50}),
EvalResult(eval_type='NNP', label='nnp-150-noself-euclidean', value=np.float64(0.5996895098691506), info={'metric': 'euclidean', 'n_neighbors': 150}),
EvalResult(eval_type='Stress', label='stress-euclidean', value=17.22634250270604, info={'metric': 'euclidean'}),
EvalResult(eval_type='ApproxStress', label='astress-euclidean-3', value=1.0812180604106723, info={'metric': 'euclidean', 'n_samples': 3}),
EvalResult(eval_type='ApproxStress', label='astress-euclidean-10', value=2.003360660282076, info={'metric': 'euclidean', 'n_samples': 10})]
The result looks a bit rougher than the official MMDS version, but it’s probably good enough for most purposes, and the stress value is within 1% of. Visually, it also looks reasonably close to the SQuadMDS result shown in the bottom left image of Figure 4 of the SQuadMDS paper. Note that I have rotated these images a bit so they line up better with the MMDS result so the result in the SQuadMDS paper is flipped along the x-axis compared to the images in this notebook.
Here’s the PCA result (which SMMDS initialized from by default), just to prove that:

[EvalResult(eval_type='RTE', label='rte-5-euclidean', value=np.float64(0.8530938123752494), info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='RPC', label='rpc-5-euclidean', value=0.8842371702194214, info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='NNP', label='nnp-15-noself-euclidean', value=np.float64(0.37285429141716575), info={'metric': 'euclidean', 'n_neighbors': 15}),
EvalResult(eval_type='NNP', label='nnp-50-noself-euclidean', value=np.float64(0.4141450432468397), info={'metric': 'euclidean', 'n_neighbors': 50}),
EvalResult(eval_type='NNP', label='nnp-150-noself-euclidean', value=np.float64(0.5576668884453315), info={'metric': 'euclidean', 'n_neighbors': 150}),
EvalResult(eval_type='Stress', label='stress-euclidean', value=24.959196300183695, info={'metric': 'euclidean'}),
EvalResult(eval_type='ApproxStress', label='astress-euclidean-3', value=1.581445419184665, info={'metric': 'euclidean', 'n_samples': 3}),
EvalResult(eval_type='ApproxStress', label='astress-euclidean-10', value=2.8769868758744157, info={'metric': 'euclidean', 'n_samples': 10})]
n_samples=3: the number of samples to use generate the gradient for each item. The default is n_samples=3 which creates a quartet of points. This is similar to how SQuadMDS works.n_epochs=200: the number of optimization iterations. The default is set arbitrarily to n_epochs=200. I don’t have good advice for this: from the SQuadMDS paper, n_epochs=5000 might be a good setting, but bear in mind that can lead to quite long run times for larger datasets. However it’s probably best to assume that this value should scale with the size of the dataset.init="pca": the initialization method. By default, PCA is used without any other scaling. You may also set init="rand" to use the UMAP-style random initialization, which is less compact than e.g. the t-SNE initialization. Alternatively, you can pass a numpy 2D array of your own devising.learning_rate=None: the learning rate in the optimization method. This seems to be very sensitive to the dataset unfortunately. I recommend initially trying a value between 0.01 to 10. The default will use the default value from the optimizer via the opt argument, unless you override it with optargs (see below). The default optimizer is Adam, which uses a learning rate of 1e-3.metric: the distance metric appropriate for the input data. It should be the name of one of the distance functions in the pynndescent.distances module, although bear in mind that distances that take extra parameters are not supported. The output distance metric is always "euclidean", and that is also the default choice for the input metric.random_state=42. Seed for random number generation.eps=1e-10. A value to avoid division by zero in the gradient. No reason to touch this as far as I have discerned. I use the same value as mentioned in the description of the SPE algorithm.opt="adam". The optimizer to use. Adam seems a robust choice. You may also use "steepd" for stochastic gradient descent, and "mom" for stochastic gradient descent with momentum. Seems like no-one would want to do this except me for experimenting.optargs=None. A dict of Parameters to set on the optimizer. If you really want to do this, look in the drnb.optim module and the arguments passed to the constructors of the optimizer classes. Apart from nobs and ndim, you can override them with values here.SQuadMDS doesn’t actually attempt to minimize the raw distances like metric MDS does. Instead, for each quartet, it normalizes the input and output distances. This is somewhat similar to what the stochastic neighbor embedding methods do, although they transform the distances to similarities and normalize over all items in the dataset. The reason for doing so is not explicitly stated in the SQuadMDS paper, but presumably it’s to get the gradient to be somewhat close in scale to that of t-SNE so it can be used in the hybrid MDS/t-SNE method described in the paper. It might have other advantages though, such as less of a sensitivity to the learning rate, although I have yet to prove that to myself. The gradient for a normalized MDS looks like:
\[ \frac{\partial{C_{\mathrm{NMDS}}}}{\partial{\mathbf{y_i}}} =\frac{2}{\sum_k d_{ik}} \sum_j \frac{1}{d_{ij}} \left[ \left(q_{ij} - p_{ij}\right) + \sum_k q_{ik} \left(p_{ik} - q_{ik}\right) \right] \left(\mathbf{y_i} - \mathbf{y_j}\right) \]
Here \(p_{ij} = r_{ij} / \sum_k r_{ik}\) and \(q_{ij} = d_{ij} / \sum_k d_{ik}\) are the normalized distances. For a “real” normalized version of MMDS the sums over \(j\) and \(k\) are the \(N\) other items in the dataset. For a stochastic version, it’s over the n_sample other items in the dataset.
To use the normalized version, the method is snmds with the same parameters as smmds. Here is an example with airfoil (I had to reduce the learning rate for the normalized version):

[EvalResult(eval_type='RTE', label='rte-5-euclidean', value=np.float64(0.8706586826347305), info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='RPC', label='rpc-5-euclidean', value=0.9078036546707153, info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='NNP', label='nnp-15-noself-euclidean', value=np.float64(0.580439121756487), info={'metric': 'euclidean', 'n_neighbors': 15}),
EvalResult(eval_type='NNP', label='nnp-50-noself-euclidean', value=np.float64(0.5669727212242183), info={'metric': 'euclidean', 'n_neighbors': 50}),
EvalResult(eval_type='NNP', label='nnp-150-noself-euclidean', value=np.float64(0.6600177422931914), info={'metric': 'euclidean', 'n_neighbors': 150}),
EvalResult(eval_type='Stress', label='stress-euclidean', value=24.547036393141884, info={'metric': 'euclidean'}),
EvalResult(eval_type='ApproxStress', label='astress-euclidean-3', value=1.5669274213754223, info={'metric': 'euclidean', 'n_samples': 3})]
Here’s a further comparison of the normalized and non-normalized stochastic MMDS using the mouse cell retina dataset, which appears in down-sampled form in the third column of Figure 4. Note that both of these results take a few minutes to run. Metric first (which should look most like the SMACOF version show at the top right):

[EvalResult(eval_type='RTE', label='rte-5-euclidean', value=np.float64(0.8483250776593065), info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='RPC', label='rpc-5-euclidean', value=0.9002163410186768, info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='NNP', label='nnp-15-noself-euclidean', value=np.float64(0.0514062631181261), info={'metric': 'euclidean', 'n_neighbors': 15}),
EvalResult(eval_type='NNP', label='nnp-50-noself-euclidean', value=np.float64(0.11867265552850308), info={'metric': 'euclidean', 'n_neighbors': 50}),
EvalResult(eval_type='NNP', label='nnp-150-noself-euclidean', value=np.float64(0.22165421319228726), info={'metric': 'euclidean', 'n_neighbors': 150})]
And now the normalized version (which hopefully more closely resembled the SQuadMDS) result:

[EvalResult(eval_type='RTE', label='rte-5-euclidean', value=np.float64(0.814499202417933), info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='RPC', label='rpc-5-euclidean', value=0.8574582934379578, info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='NNP', label='nnp-15-noself-euclidean', value=np.float64(0.06677021240869783), info={'metric': 'euclidean', 'n_neighbors': 15}),
EvalResult(eval_type='NNP', label='nnp-50-noself-euclidean', value=np.float64(0.15338510620434895), info={'metric': 'euclidean', 'n_neighbors': 50}),
EvalResult(eval_type='NNP', label='nnp-150-noself-euclidean', value=np.float64(0.2843318501105421), info={'metric': 'euclidean', 'n_neighbors': 150})]
This doesn’t look exactly like what it’s in the paper, but I ran SQuadMDS itself on the full dataset and here is the result:
while the differences between the normalized and stochastic metric MDS are already fairly small, the SQuadMDS results do resemble the normalized version more closely.
However, it should be noted that SQuaDMDS runs faster than SMMDS. Probably this is because the latter only uses 3 other points and hence can manually unroll the gradient calculation loops. Other places where SQuadMDS may be more efficient is in the partitioning of the data due to effectively sampling without replacement and less use of a random number generator. But I haven’t done any profiling.
One of the features of SQuadMDS is a hybrid mode with t-SNE, where the gradients are combined as a way to preserve some of the global properties of MMDS with the better local preservation of t-SNE. As an alternative, I propose initializing with SMMDS, then running t-SNE with a lower-than-usual learning rate to avoid disturbing the global structure too much. Getting this right involves setting the t-SNE learning rate and the initial scale of the coordinates appropriately, so I don’t claim that this is an exact science.
The example below uses one of the same datasets as in the SQuadMDS paper (mouse retina single-cell RNA sequence data reduced to 50 components) and may take a couple of minutes to complete. openTSNE will warn about the high standard deviation risking poor convergence, but in this case we have used rescale to create a larger initial spread on purpose, so it’s not a real problem.
[09:32:39] WARNING Using k_neighbors (no self) = 90 with perplexity 30.00 external.py:352
[09:32:40] WARNING Running openTSNE.TSNE with params={'learning_rate': 1.0} external.py:352
WARNING Standard deviation of embedding is greater than 0.0001. Initial external.py:352 embeddings with high variance may have display poor convergence.

[EvalResult(eval_type='RTE', label='rte-5-euclidean', value=np.float64(0.7952900680043657), info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='RPC', label='rpc-5-euclidean', value=0.7971316576004028, info={'metric': 'euclidean', 'ntpp': 5}),
EvalResult(eval_type='NNP', label='nnp-15-noself-euclidean', value=np.float64(0.2267819662496852), info={'metric': 'euclidean', 'n_neighbors': 15}),
EvalResult(eval_type='NNP', label='nnp-50-noself-euclidean', value=np.float64(0.35773066912937623), info={'metric': 'euclidean', 'n_neighbors': 50}),
EvalResult(eval_type='NNP', label='nnp-150-noself-euclidean', value=np.float64(0.49036380936389334), info={'metric': 'euclidean', 'n_neighbors': 150})]
Compared to the output of the hybrid version of SQuadMDS (top right of Figure 6 of the paper), this shows a tolerable resemblance.
If you are capable of installing drnb but don’t want to deal with all this pipeline nonsense:

To liberate SMMDS further, the algorithm is in drnb.embed.smmds, and the optimizers in drnb.optim. There is some initialization, random number generation and distance calculation code dependent on pynndescent and umap but these can all be easily replaced if you only want Euclidean distances and PCA-based initialization.