NBIS系列單細胞轉錄組數據分析實戰(四):細胞聚類分析

第四節:細胞聚類分析

在本節教程中,我們將基于批次矯正后的整合數據集進行細胞聚類分析,我們使用PCA線性降維的結果分別執行k-最近鄰圖聚類,層次聚類和k-均值聚類。

加載所需的R包和數據集

if (!require(clustree)) {
    install.packages("clustree", dependencies = FALSE)
}
## Loading required package: clustree
## Loading required package: ggraph

suppressPackageStartupMessages({
    library(Seurat)
    library(cowplot)
    library(ggplot2)
    library(pheatmap)
    library(rafalib)
    library(clustree)
})

alldata <- readRDS("data/results/covid_qc_dr_int.rds")

執行k-最近鄰圖聚類

在執行圖聚類的過程中主要包括以下3個步驟:

  • Build a kNN graph from the data
  • Prune spurious connections from kNN graph (optional step). This is a SNN graph.
  • Find groups of cells that maximizes the connections within the group compared other groups.

構建kNN/SNN圖

執行圖聚類的第一步是構建一個kNN圖,我們使用PCA降維的前N個PC用于計算。

我們可以使用Seurat包中的FindNeighbors函數計算構建KNN和SNN圖。

# check that CCA is still the active assay
alldata@active.assay
## [1] "CCA"

# 使用FindNeighbors函數構建SNN圖
alldata <- FindNeighbors(alldata, dims = 1:30, k.param = 60, prune.SNN = 1/15)
## Computing nearest neighbor graph
## Computing SNN

# check the names for graphs in the object.
names(alldata@graphs)
## [1] "CCA_nn"  "CCA_snn"

我們可以看一下kNN圖,它是一個連接矩陣,其中不同細胞之間的每個連接都表示為1個s,這稱之為未加權圖(Seurat中的默認值)。但是,某些細胞之間的連接可能比其他細胞的更重要,在這種情況下,圖的尺度會從0到最大距離。通常,距離越小,兩點越接近,它們之間的連接也越牢固,這稱之為加權圖。加權圖和未加權圖均適用于圖聚類,但是對于大型數據集(>100k細胞),使用非加權圖在聚類上的速度會更快。

pheatmap(alldata@graphs$CCA_nn[1:200, 1:200], 
                 col = c("white", "black"), border_color = "grey90", 
                 legend = F, cluster_rows = F, cluster_cols = F, fontsize = 2)
image.png

基于SNN圖進行細胞聚類

在構建好SNN圖后,我們可以基于其執行圖聚類。選用不同的分辨率(resolution)進行細胞聚類,分辨率越大,聚類出來的細胞簇數越多。

在Seurat中,我們使用FindClusters函數進行細胞聚類,默認情況下(algorithm = 1),該函數將使用“ Louvain”算法進行基于圖的聚類。要使用leiden算法,我們需要將其設置為algorithm = 4

# Clustering with louvain (algorithm 1)
for (res in c(0.1, 0.25, 0.5, 1, 1.5, 2)) {
    alldata <- FindClusters(alldata, graph.name = "CCA_snn", resolution = res, algorithm = 1)
}

# each time you run clustering, the data is stored in meta data columns:
# seurat_clusters - lastest results only CCA_snn_res.XX - for each different
# resolution you test.

plot_grid(ncol = 3, DimPlot(alldata, reduction = "umap", group.by = "CCA_snn_res.0.5") + ggtitle("louvain_0.5"), 
                    DimPlot(alldata, reduction = "umap", group.by = "CCA_snn_res.1") + ggtitle("louvain_1"), 
                    DimPlot(alldata, reduction = "umap", group.by = "CCA_snn_res.2") + ggtitle("louvain_2"))
image.png

現在,我們可以使用clustree包來可視化不同分辨率下細胞在聚類群之間的分配。

# install.packages('clustree')
suppressPackageStartupMessages(library(clustree))

clustree(alldata@meta.data, prefix = "CCA_snn_res.")
image.png

K均值聚類

K-means是一種常用的聚類算法,已在許多應用領域中使用。在R中,可以通過kmeans函數進行調用。通常,它應用于表達數據的降維表示(由于低維距離的可解釋性,因此通常用于PCA)。

我們需要預先設定聚類群的數量。由于聚類的結果取決于群集中心的初始化,因此通常建議使用多個啟動配置(通過nstart參數)運行K-means。

for (k in c(5, 7, 10, 12, 15, 17, 20)) {
    alldata@meta.data[, paste0("kmeans_", k)] <- kmeans(x = alldata@reductions[["pca"]]@cell.embeddings,  centers = k, nstart = 100)$cluster
}

plot_grid(ncol = 3, DimPlot(alldata, reduction = "umap", group.by = "kmeans_5") +  ggtitle("kmeans_5"), 
                    DimPlot(alldata, reduction = "umap", group.by = "kmeans_10") +  ggtitle("kmeans_10"), 
                    DimPlot(alldata, reduction = "umap", group.by = "kmeans_15") +  ggtitle("kmeans_15"))
image.png

使用clustree函數查看不同聚類群的結果

clustree(alldata@meta.data, prefix = "kmeans_")
image.png

層次聚類

定義細胞之間的距離

基本的Rstats包中包含一個dist函數,可以用于計算所有成對樣本之間的距離。由于我們要計算樣本之間的距離,而不是基因之間的距離,因此我們需要先對表達數據進行轉置,然后再將其應用于dist函數中。dist函數中可用的距離計算方法有:“euclidean”, “maximum”, “manhattan”, “canberra”, “binary” or “minkowski”.

d <- dist(alldata@reductions[["pca"]]@cell.embeddings, method = "euclidean")

可以看到,dist函數不能實現correlation的方法。但是,我們可以創建自己的距離并將其轉換為距離對象。我們首先可以使用cor函數計算樣本之間的相關性。如您所知,相關性的范圍是從-1到1的,其中1表示兩個樣本最接近,-1表示兩個樣本最遠,0介于兩者之間。但是,這在定義距離時會產生問題,因為距離0表示兩個樣本最接近,距離1表示兩個樣本最遠,而距離-1沒有意義。因此,我們需要將相關性轉換為正尺度(又稱adjacency):

image.png

將相關性轉換為0-1比例后,我們可以簡單地使用as.dist函數將其轉換為距離對象。

# Compute sample correlations
# 計算細胞之間的相關性
sample_cor <- cor(Matrix::t(alldata@reductions[["pca"]]@cell.embeddings))

# Transform the scale from correlations
sample_cor <- (1 - sample_cor)/2

# Convert it to a distance object
d2 <- as.dist(sample_cor)

基于細胞之間的距離進行層次聚類

在計算出所有樣本之間的距離之后,我們可以對其進行層次聚類。我們將使用hclust函數實現該功能,在該函數中,我們可以簡單地使用上面創建的距離對象來運行它。可用的方法有:“ward.D”, “ward.D2”, “single”, “complete”, “average”, “mcquitty”, “median” or “centroid”。

# euclidean
h_euclidean <- hclust(d, method = "ward.D2")

# correlation
h_correlation <- hclust(d2, method = "ward.D2")

創建好分層聚類樹后,下一步就是定義哪些樣本屬于特定簇。我們可以使用cutree函數根據特定k值切割聚類樹,以定義聚類群。我們還可以定義簇的數量或確定高度。

#euclidean distance
alldata$hc_euclidean_5 <- cutree(h_euclidean,k = 5)
alldata$hc_euclidean_10 <- cutree(h_euclidean,k = 10)
alldata$hc_euclidean_15 <- cutree(h_euclidean,k = 15)

#correlation distance
alldata$hc_corelation_5 <- cutree(h_correlation,k = 5)
alldata$hc_corelation_10 <- cutree(h_correlation,k = 10)
alldata$hc_corelation_15 <- cutree(h_correlation,k = 15)

plot_grid(ncol = 3,
  DimPlot(alldata, reduction = "umap", group.by = "hc_euclidean_5")+ggtitle("hc_euc_5"),
  DimPlot(alldata, reduction = "umap", group.by = "hc_euclidean_10")+ggtitle("hc_euc_10"),
  DimPlot(alldata, reduction = "umap", group.by = "hc_euclidean_15")+ggtitle("hc_euc_15"),

  DimPlot(alldata, reduction = "umap", group.by = "hc_corelation_5")+ggtitle("hc_cor_5"),
  DimPlot(alldata, reduction = "umap", group.by = "hc_corelation_10")+ggtitle("hc_cor_10"),
  DimPlot(alldata, reduction = "umap", group.by = "hc_corelation_15")+ggtitle("hc_cor_15")
)
image.png

保存細胞聚類的結果

saveRDS(alldata, "data/results/covid_qc_dr_int_cl.rds")
sessionInfo()
## R version 4.0.3 (2020-10-10)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: macOS Catalina 10.15.5
## 
## Matrix products: default
## BLAS/LAPACK: /Users/paulo.czarnewski/.conda/envs/scRNAseq2021/lib/libopenblasp-r0.3.12.dylib
## 
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
##  [1] parallel  stats4    grid      stats     graphics  grDevices utils    
##  [8] datasets  methods   base     
## 
## other attached packages:
##  [1] rafalib_1.0.0               pheatmap_1.0.12            
##  [3] clustree_0.4.3              ggraph_2.0.4               
##  [5] reticulate_1.18             harmony_1.0                
##  [7] Rcpp_1.0.6                  scran_1.18.0               
##  [9] SingleCellExperiment_1.12.0 SummarizedExperiment_1.20.0
## [11] Biobase_2.50.0              GenomicRanges_1.42.0       
## [13] GenomeInfoDb_1.26.0         IRanges_2.24.0             
## [15] S4Vectors_0.28.0            BiocGenerics_0.36.0        
## [17] MatrixGenerics_1.2.0        matrixStats_0.57.0         
## [19] ggplot2_3.3.3               cowplot_1.1.1              
## [21] KernSmooth_2.23-18          fields_11.6                
## [23] spam_2.6-0                  dotCall64_1.0-0            
## [25] DoubletFinder_2.0.3         Matrix_1.3-2               
## [27] Seurat_3.2.3                RJSONIO_1.3-1.4            
## [29] optparse_1.6.6             
## 
## loaded via a namespace (and not attached):
##   [1] tidyselect_1.1.0          htmlwidgets_1.5.3        
##   [3] BiocParallel_1.24.0       Rtsne_0.15               
##   [5] munsell_0.5.0             codetools_0.2-18         
##   [7] ica_1.0-2                 statmod_1.4.35           
##   [9] future_1.21.0             miniUI_0.1.1.1           
##  [11] withr_2.4.0               colorspace_2.0-0         
##  [13] knitr_1.30                ROCR_1.0-11              
##  [15] tensor_1.5                listenv_0.8.0            
##  [17] labeling_0.4.2            GenomeInfoDbData_1.2.4   
##  [19] polyclip_1.10-0           bit64_4.0.5              
##  [21] farver_2.0.3              parallelly_1.23.0        
##  [23] vctrs_0.3.6               generics_0.1.0           
##  [25] xfun_0.20                 R6_2.5.0                 
##  [27] graphlayouts_0.7.1        rsvd_1.0.3               
##  [29] locfit_1.5-9.4            hdf5r_1.3.3              
##  [31] bitops_1.0-6              spatstat.utils_1.20-2    
##  [33] DelayedArray_0.16.0       assertthat_0.2.1         
##  [35] promises_1.1.1            scales_1.1.1             
##  [37] gtable_0.3.0              beachmat_2.6.0           
##  [39] globals_0.14.0            goftest_1.2-2            
##  [41] tidygraph_1.2.0           rlang_0.4.10             
##  [43] splines_4.0.3             lazyeval_0.2.2           
##  [45] checkmate_2.0.0           yaml_2.2.1               
##  [47] reshape2_1.4.4            abind_1.4-5              
##  [49] backports_1.2.1           httpuv_1.5.5             
##  [51] tools_4.0.3               ellipsis_0.3.1           
##  [53] RColorBrewer_1.1-2        ggridges_0.5.3           
##  [55] plyr_1.8.6                sparseMatrixStats_1.2.0  
##  [57] zlibbioc_1.36.0           purrr_0.3.4              
##  [59] RCurl_1.98-1.2            rpart_4.1-15             
##  [61] deldir_0.2-9              pbapply_1.4-3            
##  [63] viridis_0.5.1             zoo_1.8-8                
##  [65] ggrepel_0.9.1             cluster_2.1.0            
##  [67] magrittr_2.0.1            data.table_1.13.6        
##  [69] RSpectra_0.16-0           scattermore_0.7          
##  [71] lmtest_0.9-38             RANN_2.6.1               
##  [73] fitdistrplus_1.1-3        patchwork_1.1.1          
##  [75] mime_0.9                  evaluate_0.14            
##  [77] xtable_1.8-4              gridExtra_2.3            
##  [79] compiler_4.0.3            tibble_3.0.5             
##  [81] maps_3.3.0                crayon_1.3.4             
##  [83] htmltools_0.5.1           mgcv_1.8-33              
##  [85] venn_1.9                  later_1.1.0.1            
##  [87] tidyr_1.1.2               DBI_1.1.1                
##  [89] tweenr_1.0.1              formatR_1.7              
##  [91] MASS_7.3-53               getopt_1.20.3            
##  [93] igraph_1.2.6              pkgconfig_2.0.3          
##  [95] plotly_4.9.3              scuttle_1.0.0            
##  [97] admisc_0.11               dqrng_0.2.1              
##  [99] XVector_0.30.0            stringr_1.4.0            
## [101] digest_0.6.27             sctransform_0.3.2        
## [103] RcppAnnoy_0.0.18          spatstat.data_1.7-0      
## [105] rmarkdown_2.6             leiden_0.3.6             
## [107] uwot_0.1.10               edgeR_3.32.0             
## [109] DelayedMatrixStats_1.12.0 curl_4.3                 
## [111] shiny_1.5.0               lifecycle_0.2.0          
## [113] nlme_3.1-151              jsonlite_1.7.2           
## [115] BiocNeighbors_1.8.0       viridisLite_0.3.0        
## [117] limma_3.46.0              pillar_1.4.7             
## [119] lattice_0.20-41           fastmap_1.0.1            
## [121] httr_1.4.2                survival_3.2-7           
## [123] glue_1.4.2                remotes_2.2.0            
## [125] spatstat_1.64-1           png_0.1-7                
## [127] bluster_1.0.0             bit_4.0.4                
## [129] ggforce_0.3.2             stringi_1.5.3            
## [131] BiocSingular_1.6.0        dplyr_1.0.3              
## [133] irlba_2.3.3               future.apply_1.7.0

參考來源:https://nbisweden.github.io/workshop-scRNAseq/labs/compiled/seurat/seurat_04_clustering.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,345評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,494評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,283評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,953評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,714評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,410評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,940評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,776評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,210評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,654評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容