Skip to content

Leiden restrict_to parameter - #586

Merged
ivirshup merged 12 commits into
scverse:masterfrom
fbrundu:leiden_restrict
Apr 8, 2019
Merged

ivirshup merged 12 commits into
scverse:masterfrom
fbrundu:leiden_restrict

Conversation

@fbrundu

@fbrundu fbrundu commented Apr 2, 2019 •

Copy link
Copy Markdown
Contributor

Added restrict_to parameter to leiden by using louvain code as template.
Tests are not yet provided.

A simple example of execution and checks:

# First split on cluster 4
sc.tl.leiden(adata, restrict_to=('leiden_res0.4', ['4']), resolution=0.6,
    key_added='leiden_res0.4_4_sub')

# Additional split
sc.tl.leiden(adata, restrict_to=('leiden_res0.4_4_sub', ['1', '2', '3', '4,4']),
    resolution=0.6, key_added='leiden_res0.4_4_add_sub')

# All partitions together
sc.pl.tsne(adata, color=['leiden_res0.4', 'leiden_res0.4_4_sub',
    'leiden_res0.4_4_add_sub'])

# Partition size check
## Original size of clusters
adata.obs['leiden_res0.4'].value_counts()
0    932
1    853
3    676
2    676
4    338
5     57
Name: leiden_res0.4, dtype: int64

# Check if first split is correct (can be iterated for subsequent splits)
## Assignment of samples in original clusters to subsplit clusters
adata.obs.loc[(adata.obs['leiden_res0.4'].isin(['4'])),
    'leiden_res0.4_4_sub'].value_counts()
4,0    103
4,1     68
4,2     66
4,3     57
4,4     44
5        0
3        0
2        0
1        0
0        0
Name: leiden_res0.4_4_sub, dtype: int64
## Assignment of samples not in original clusters to subsplit clusters
adata.obs.loc[~(adata.obs['leiden_res0.4'].isin(['4'])),
    'leiden_res0.4_4_sub'].value_counts()
0      932
1      853
3      676
2      676
5       57
4,4      0
4,3      0
4,2      0
4,1      0
4,0      0
Name: leiden_res0.4_4_sub, dtype: int64

...

Image

@ivirshup

ivirshup commented Apr 3, 2019

Copy link
Copy Markdown
Member

Would you mind adding a test?

@flying-sheep

Copy link
Copy Markdown
Member

Great! Please create helper functions abstracting away identical code blocks in the two functions. E.g. those lines are completely identical to the ones in louvain:

https://github.com/theislab/scanpy/blob/4760cbdf264c88ab48e17efaab5b559ab064be49/scanpy/tools/_leiden.py#L108-L120

And the same might apply to the other code block.

@fbrundu

fbrundu commented Apr 3, 2019 •

Copy link
Copy Markdown
Contributor Author

I added helper functions. I am working on the tests.
Apparently there's a test https://github.com/theislab/scanpy/blob/fc24dfc62c049a0d0c9cc491d4647d03b52bfb10/scanpy/tests/test_rank_genes_groups_logreg.py#L22
that fails locally in my machine.
It is because after rank_genes_groups categories are naturally sorted. I don't think this is due to my changes, but let me know how can I help.

I am unsure why it is failing on Travis.

@fbrundu

fbrundu commented Apr 3, 2019

Copy link
Copy Markdown
Contributor Author

I added tests for both louvain and leiden with restrict parameter. Please review the test code to be sure it is clear and working.

@flying-sheep flying-sheep left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking great! The test seems effective. There are some minor stylistic changes, but no content ones.

Comment thread scanpy/tests/test_clustering.py Resolved
Comment thread scanpy/tests/test_clustering.py Resolved
Comment thread scanpy/tests/test_clustering.py Resolved
Comment thread scanpy/tests/test_clustering.py Resolved

@ivirshup ivirshup left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a few pointers on tests

print('Common categories')
print(common_cat)
## Only new categories
assert len(common_cat) == 0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An example of pytest printing values when assert fails. If this assertion fails pytest should print common_cat on it's own, so there's no need for the print statements above it.

Comment thread scanpy/tests/test_clustering.py Outdated

# Old category should not be present
categories = new_partition.unique()
assert c not in categories

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this case covered by the assert len(common_cat) == 0 statement?

Comment thread scanpy/tests/test_clustering.py Resolved
@falexwolf

Copy link
Copy Markdown
Member

@flying-sheep @ivirshup As you looked through this in detail already, one of you should merge this when ready, ok?

@falexwolf

Copy link
Copy Markdown
Member

Only one thing that I would ask for: please don't put things in utils when it's not absolutely necessary.

Here, it would be very natural to add a _utils_clustering.py in scanpy/tools.py. scanpy/utils.py is way too overloaded with all kinds of things... And I will need to clean it up at some point.

Thank you for moving the helper functions there. Or, foreseeing that leiden might surpass louvain in the future, you could just add the helper functions to _leiden and import into _louvain from there.

@fbrundu

fbrundu commented Apr 5, 2019

Copy link
Copy Markdown
Contributor Author

@falexwolf I added _utils_clustering.py since I think it's the more maintainable way to do it (e.g. if in the future, new clustering methods are added).

@flying-sheep

flying-sheep commented Apr 5, 2019 •

Copy link
Copy Markdown
Member

My comments are addressed, idk if all of @ivirshup’s are. Thank you for your patience @fbrundu

@ivirshup

ivirshup commented Apr 7, 2019

Copy link
Copy Markdown
Member

I've got one minor comment left (one last redundant print statement), but otherwise I'm good.

@ivirshup

ivirshup commented Apr 8, 2019

Copy link
Copy Markdown
Member

Looks good to me! Thanks @fbrundu.

@ivirshup
ivirshup merged commit 533254d into scverse:master Apr 8, 2019
@fidelram

Copy link
Copy Markdown
Collaborator

we should update the tutorials and notebooks to use leiden instead of louvain.

@fbrundu
fbrundu deleted the leiden_restrict branch April 11, 2019 14:35
@falexwolf

Copy link
Copy Markdown
Member

Yes, we should as soon as many people report seemless installation of the leiden package. I'm still using louvain as I never had any problems with it, but I agree that we should migrate when leiden is stable, mature and easily-installable.

@LuckyMD

LuckyMD commented Apr 15, 2019

Copy link
Copy Markdown
Contributor

Has anyone compared the two for speed? I guess Leiden has an extra step and therefore might be a bit slower. If they both scale well to >1 million cells, then I agree... otherwise the issues of louvain shouldn't be as bad for KNN-graphs as for more graphs with more heavy tailed degree distributions.

@ivirshup

Copy link
Copy Markdown
Member

I looked at it a while ago (for one test dataset, probably), and got the impression that louvain was faster. That said, they're both very fast. I would note that solutions from either can be pretty unstable, frequently depending on size of the community.

@LuckyMD When you say heavy tailed, are you thinking of the unweighted KNN graph case or both?

@LuckyMD

LuckyMD commented Apr 15, 2019

Copy link
Copy Markdown
Contributor

They'll both be affected by the resolution limit, which might be what you're referring to. This is a well-described problem for Modularity with the configuration null model that it only optimally detects communities within a certain size range relative to the size of the network.

For me heavy-tailed networks are PPIs.. KNNs are a lot more regular than that. I'm not sure what a weighted KNN graph would be... are you talking about the PhenoGraph approach?

@ivirshup

Copy link
Copy Markdown
Member

Yeah, I was pretty much talking about the resolution limit.

PhenoGraph would be an example of a weighted KNN, but so would the "connectivities" adjacency matrix we get from UMAP. This is what's used if you use sc.tl.leiden(..., use_weights=True), which is the default.

@LuckyMD

LuckyMD commented Apr 17, 2019

Copy link
Copy Markdown
Contributor

I wasn't aware we use a weighted matrix for clustering as default. Are the weights in the connectivities matrix related to the euclidean distances between cells?

@ivirshup

Copy link
Copy Markdown
Member

Sort of. I believe weights are between 0 and 1, where the edge to the nearest neighbor has weight=1, and the k-th+ neighbor has weight=0. I'm not quite sure how the weights are scaled within that, but I'm pretty sure it's not rank based.

Leland Mcinnes has explained it much better than I can in his explanations of UMAP. It's discussed in the docs starting with the part on Riemannian geometry, but is also covered in his talks or the UMAP paper.

@LuckyMD

LuckyMD commented Apr 17, 2019

Copy link
Copy Markdown
Contributor

Thanks for the link. This is definitely easier to understand than the paper ;).

@LuckyMD

LuckyMD commented Apr 17, 2019

Copy link
Copy Markdown
Contributor

If we use the connectivities weights from UMAP by default for clustering... how different is that to clustering on the UMAP embedding directly? Is there a rationale for not just using a binarized KNN-graph for this?

@falexwolf

Copy link
Copy Markdown
Member

We didn't use the weights in Louvain (https://github.com/theislab/scanpy/blob/297d6246ccfbf398f771cee1bd4b81b57fc27c76/scanpy/tools/_louvain.py#L31)?

Why did you decide to change the default in Leiden
(https://github.com/theislab/scanpy/blob/297d6246ccfbf398f771cee1bd4b81b57fc27c76/scanpy/tools/_leiden.py#L31)? I'm fine with it, but a brief discussion would have been appropriate. 😉

@LuckyMD

how different is that to clustering on the UMAP embedding directly?
It's very different. The choice of weights will likely not have a dramatic effect, you're always clustering a graph that proxies neighborhoods in high-dimensional space. If you embed this structure in 2 or 3 d, even if you use the fantastic UMAP for it, you'll make errors (https://twitter.com/falexwolf/status/1108284982001315840). Also, the most computationally intense part is the embedding optimization, not the graph construction.

@LuckyMD

LuckyMD commented Apr 18, 2019 •

Copy link
Copy Markdown
Contributor

@falexwolf I recall that image in the figure, thanks! I wasn't aware that the embedding was the difficult part.

I would also like to know what the benefit of clustering the weighted graph is in practice.... It definitely makes the clustering procedure more difficult to explain in one sentence in the methods section of a paper...

@ivirshup

Copy link
Copy Markdown
Member

I was also investigating how leiden got use_weights=True by default, and noticed the lack of discussion. Seems like it just sorta happened when leiden got added #361?

I think it'd be pretty different from clustering on the embedding, because the embedding has constraints based on things like minimum distance two points can be from each other, and the number of dimensions it's embedded in.

On the binarized KNN-graph, I think we've actually talked about this before (#240). I personally think using a weighted graph makes more sense. For example, say you have a cell type of which occurs 15 times in your dataset, but you've set k to 30. With a binarized graph there will be a less clear signal that this is a distinct cell-type.

From a slightly more empirical/ anecdotal perspective, on a couple datasets I tested, total degree of the generated graph was sub-linear (looked log-ish) w.r.t. k for the weighted umap graph. Here's using one of the bone marrow donors from the hca immune census (y-axis is log scaled so you can still see the total weighted degree increase):

image

To me, this suggested a stable representation of the dataset was being found. As a connected point, in my experience clustering results seems fairly robust to k for weighted graphs above a low threshold (I think dataset dependent, but 30-60 range). Using an unweighted graph, there is a much stronger dependence on k and some smaller clusters seem less stable (show up in a smaller proportion of clustering solutions from a parameter space).

@LuckyMD

LuckyMD commented Apr 23, 2019

Copy link
Copy Markdown
Contributor

I'm not sure I agree with your interpretation of your total degree plot. To me, increasing k is meant to have the effect of densifying the network, and thus obtaining a lower resolution view of the manifold. It is somewhat analogous to choosing a lower resolution value for leiden or louvain clustering. What you see is that in the weighted case, the overall degree does not really increase (thus possibly neither does the overall density), so that increasing k may have little effect on clustering at all. This is the most I can get from this plot... as density is really about local changes and not the global degree increase. But I would still ask whether it is a good thing that increasing k has little effect? Does increasing k then change the clustering results (in the weighed case?).

I wonder if the observation that you find smaller clusters better in the weighted case is robust. That would suggest that weights can counteract resolution limit issues, which would be very interesting...

@ivirshup

ivirshup commented Apr 29, 2019 •

Copy link
Copy Markdown
Member

Sorry about the delay, I've been working on some writing about this stuff (though from a different perspective).

I'm not sure k is "meant" to have any particular effect, since these methods weren't designed for KNN graphs. I'd also argue if the parameters are analogous, there's an advantage of simplicity to just choosing one of them.

I've got some plots for the effect of resolution and number of neighbors on the size of clusters which are found. This is for the 10x example dataset with 10k pbmcs using the v3 chemistry. What I've done is build the networks at 5 different values of k, four times each (different random seeds). For each of those networks, I ran clustering at 50 different resolutions (np.geomspace(0.05, 20, 50)). Here are the maximum cluster sizes found for each combination of k and resolution for the unweighted and weighted graph (color bar is logscale, from 1 to 6000, but I couldn't get useful ticks to work):

image
image

Overall, pretty similar. Now, the minimum cluster sizes (color scales are different, but you'll see why):

image
image

This looks to me like using the weighted graph allows identifying small clusters even at low resolutions. The cluster of 25 cells looks like megakaryocytes, and are being detected at pretty much every clustering (996 out of 1000) using the weighted graph.

@LuckyMD

LuckyMD commented Apr 29, 2019

Copy link
Copy Markdown
Contributor

This looks a lot more convincing... It's a bit hard to read the second last plot though... The black parts are also clusters around size 2-10, no? Or am I misreading the scale? Do you have a version with a few more annotations on the colour bar? How often are megakaryocytes detected as a separate cluster in the unweighted case? It looks like unweighted case is definitely worse for higher resolutions with >10 neighbours though.

And coming back to the k discussion.. From my perspective, If you treat the clustering and knn graph generation as two separate steps, you may want k to have an effect. If you treat it as the same process, then I follow your argumentation that having a single parameter to affects the scale of the clustering suffices.

@ivirshup

ivirshup commented May 1, 2019

Copy link
Copy Markdown
Member

I took about 20 minutes on it, but couldn't figure out how to add more annotations. I've got interactive versions with hover over, but log scale is bugged in those libraries... I believe the bins that are the darkest shade in the minimum cluster size for the unweighted graph actually correspond to a minimum cluster size of 1 cell.

Megakaryocytes were detected as a distinct cluster every time that k was 10 in the unweighted case, but no other times.

I think that when we make a call on "this is a kind of cell" from unsupervised clustering, those results should be robust. That is, if there's strong signal in the data and your clustering algorithm can pick up that signal, good clusters shouldn't change much if you vary the parameters a little. If you can pick any parameters from a wide range and get results that are pretty consistent, that seems like good data and a good method to me.

@LuckyMD

LuckyMD commented May 2, 2019

Copy link
Copy Markdown
Contributor

I follow your argumentation on "good clusters". However, I also like the concept that putting k=35 means you make it harder to detect clusters of size < 35, as you 'over-connect' those clusters in a way. The weighted case is less interpretable in that way. However, here it clearly outperforms the unweighted case. I am still a little on the fence (due to interpretability), but I'd be okay with weighting I think.

awnimo pushed a commit to dpeerlab/scanpy that referenced this pull request Dec 17, 2019
@ivirshup ivirshup mentioned this pull request Jan 18, 2021
1 of 3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants