2019-10-22 R语言Seurat包下游分析-1

Python011

2019-10-22 R语言Seurat包下游分析-1,第1张

下游分析

cellranger count 计算的结果只能作为错略观测的结果,如果需要进一步分析聚类细胞,还需要进行下游分析,这里使用官方推荐 R 包(Seurat 3.0)

流程参考官方外周血分析标准流程( https://satijalab.org/seurat/v3.0/pbmc3k_tutorial.html )

Rstudio操作过程:

## 安装seurat

install.packages('Seurat')

## 载入seurat包

library(dplyr)

library(Seurat)

## 读入pbmc数据(文件夹路径不能包含中文,注意“/“的方向不能错误,这里读取的是10x处理的文件,也可以处理其它矩阵文件,具体怎样操作现在还不知道,文件夹中的3个文件分别是:barcodes.tsv,genes.tsv,matrix.mtx,文件的名字不能错,否则读取不到)

pbmc.data <- Read10X(data.dir = "D:/pbmc3k_filtered_gene_bc_matrices/filtered_gene_bc_matrices/hg19/")

## 查看稀疏矩阵的维度,即基因数和细胞数

dim(pbmc.data)

pbmc.data[1:10,1:6]

## 创建Seurat对象与数据过滤,除去一些质量差的细胞(这里读取的是单细胞 count 结果中的矩阵目录;在对象生成的过程中,做了初步的过滤;留下所有在>=3 个细胞中表达的基因 min.cells = 3;留下所有检测到>=200 个基因的细胞 min.genes = 200。)

pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)

pbmc

##计算每个细胞的线粒体基因转录本数的百分比(%),使用[[ ]] 操作符存放到metadata中,mit-开头的为线粒体基因

pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

##展示基因及线粒体百分比(这里将其进行标记并统计其分布频率,"nFeature_RNA"为基因数,"nCount_RNA"为细胞数,"percent.mt"为线粒体占比)

VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")

plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")

CombinePlots(plots = list(plot1, plot2))

## 过滤细胞:根据上面小提琴图中基因数"nFeature_RNA"和线粒体数"percent.mt",分别设置过滤参数,这里基因数 200-2500,线粒体百分比为小于 5%,保留gene数大于200小于2500的细胞;目的是去掉空GEMs和1个GEMs包含2个以上细胞的数据;而保留线粒体基因的转录本数低于5%的细胞,为了过滤掉死细胞等低质量的细胞数据。

pbmc <- subset(pbmc, subset = nFeature_RNA >200 &nFeature_RNA <2500 &percent.mt <5)

## 表达量数据标准化,LogNormalize的算法:A = log( 1 + ( UMIA ÷ UMITotal ) × 10000

pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)

#pbmc <- NormalizeData(pbmc) 或者用默认的

## 鉴定表达高变基因(2000个),用于下游分析,如PCA;

pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

## 提取表达量变化最高的10个基因;

top10 <- head(VariableFeatures(pbmc), 10)

top10

plot1 <- VariableFeaturePlot(pbmc)

plot2 <- LabelPoints(plot = plot1, points = top10)

CombinePlots(plots = list(plot1, plot2))

plot1<-VariableFeaturePlot(object=pbmc)

plot2<-LabelPoints(plot=plot1,points=top10,repel=TRUE)

CombinePlots(plots=list(plot1,plot2))

## PCA分析:

# PCA分析数据准备,使用ScaleData()进行数据归一化;默认只是标准化高变基因(2000个),速度更快,不影响PCA和分群,但影响热图的绘制。

#pbmc <- ScaleData(pbmc,vars.to.regress ="percent.mt")

## 而对所有基因进行标准化的方法如下:

all.genes <- rownames(pbmc)

pbmc <- ScaleData(pbmc, features = all.genes)

pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")

## 线性降维(PCA),默认用高变基因集,但也可通过features参数自己指定;

pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))

## 展示 pca 结果(最简单的方法)

DimPlot(object=pbmc,reduction="pca")

## 检查PCA分群结果, 这里只展示前5个PC,每个PC只显示5个基因;

print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)

##PC_ 1 

##Positive:  RPS27, MALAT1, RPS6, RPS12, RPL13 

##Negative:  CSTA, FCN1, CST3, LYZ, LGALS2 

##PC_ 2 

##Positive:  NKG7, GZMA, CST7, KLRD1, CCL5 

##Negative:  RPL34, RPL32, RPL13, RPL39, LTB 

##PC_ 3 

##Positive:  MS4A1, CD79A, BANK1, IGHD, CD79B 

##Negative:  IL7R, RPL34, S100A12, VCAN, AIF1 

##PC_ 4 

##Positive:  RPS18, RPL39, RPS27, MALAT1, RPS8 

##Negative:  PPBP, PF4, GNG11, SDPR, TUBB1 

##PC_ 5 

##Positive:  PLD4, FCER1A, LILRA4, SERPINF1, LRRC26 

##Negative:  MS4A1, CD79A, LINC00926, IGHD, FCER2 

## 展示主成分基因分值

VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")

## 绘制pca散点图

DimPlot(pbmc, reduction = "pca")

## 画第1个或15个主成分的热图;

DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)

DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)

## 确定数据集的分群个数

# 鉴定数据集的可用维度,方法1:Jackstraw置换检验算法;重复取样(原数据的1%),重跑PCA,鉴定p-value较小的PC;计算‘null distribution’(即零假设成立时)时的基因scores。虚线以上的为可用维度,也可以调整 dims 参数,画出所有 pca 查看。

#pbmc <- JackStraw(pbmc, num.replicate = 100)

#pbmc <- ScoreJackStraw(pbmc, dims = 1:20)

#JackStrawPlot(pbmc, dims = 1:15)

# 方法2:肘部图(碎石图),基于每个主成分对方差解释率的排名。

ElbowPlot(pbmc)

## 细胞聚类:分群个数这里选择10,建议尝试选择多个主成分个数做下游分析,对整体影响不大;在选择此参数时,建议选择偏高的数字(为了获取更多的稀有分群,“宁滥勿缺”);有些亚群很罕见,如果没有先验知识,很难将这种大小的数据集与背景噪声区分开来。

## 非线性降维(UMAP/tSNE)基于PCA空间中的欧氏距离计算nearest neighbor graph,优化任意两个细胞间的距离权重(输入上一步得到的PC维数) 。

pbmc <- FindNeighbors(pbmc, dims = 1:10)

## 接着优化模型,resolution参数决定下游聚类分析得到的分群数,对于3K左右的细胞,设为0.4-1.2 能得到较好的结果(官方说明);如果数据量增大,该参数也应该适当增大。

pbmc <- FindClusters(pbmc, resolution = 0.5)

## 使用Idents()函数可查看不同细胞的分群;

head(Idents(pbmc), 5)

## 结果:AAACCTGAGGTGCTAG    AAACCTGCAGGTCCAC    AAACCTGCATGGAATA AAACCTGCATGGTAGG      AAACCTGCATTGGCGC 

               1                3                0               10                2 

Levels: 0 1 2 3 4 5 6 7 8 9 10 11

## Seurat提供了几种非线性降维的方法进行数据可视化(在低维空间把相似的细胞聚在一起),比如UMAP和t-SNE,运行UMAP需要先安装'umap-learn'包,这里不做介绍,两种方法都可以使用,但不要混用,如果混用,后面的结算结果会将先前的聚类覆盖掉,只能保留一个。

## 这里采用基于TSNE的聚类方法。

pbmc <- RunTSNE(pbmc, dims = 1:10)

## 用DimPlot()函数绘制散点图,reduction = "tsne",指定绘制类型;如果不指定,默认先从搜索 umap,然后 tsne, 再然后 pca;也可以直接使用这3个函数PCAPlot()、TSNEPlot()、UMAPPlot(); cols,pt.size分别调整分组颜色和点的大小;

DimPlot(pbmc,reduction = "tsne",label = TRUE,pt.size = 1.5)

## 这里采用基于图论的聚类方法

pbmc<-RunUMAP(object=pbmc,dims=1:10)

DimPlot(object=pbmc,reduction="umap")

## 细胞周期归类

pbmc<- CellCycleScoring(object = pbmc, g2m.features = cc.genes$g2m.genes, s.features = cc.genes$s.genes)

head(x = [email protected])

DimPlot(pbmc,reduction = "tsne",label = TRUE,group.by="Phase",pt.size = 1.5)

## 存储结果

saveRDS(pbmc, file = "D:/pbmc_tutorial.rds")

save(pbmc,file="D:/res0.5.Robj")

## 寻找cluster 1的marker

cluster1.markers <- FindMarkers(pbmc, ident.1 = 1, min.pct = 0.25)

head(cluster1.markers, n = 5)

## 结果:      p_val             avg_logFC        pct.1       pct.2        p_val_adj

MT-CO1  0.000000e+00    -0.6977083      0.985       0.996       0.000000e+00

RPS27  2.182766e-282     0.3076454       1.000       0.999        3.480202e-278

MT-CO3 2.146399e-274    -0.4866429      0.995       0.997       3.422218e-270

DUSP1  2.080878e-247    -1.7621662       0.376       0.745       3.317752e-243

RPL34  8.647733e-244     0.3367755        1.000       0.997       1.378795e-239

##寻找每一cluster的marker

pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE, min.pct = 0.25, logfc.threshold = 0.25)

pbmc.markers %>% group_by(cluster) %>% top_n(n = 2, wt = avg_logFC)

# A tibble: 24 x 7

# Groups:   cluster [12]

       p_val avg_logFC pct.1 pct.2 p_val_adj cluster gene 

       <dbl>     <dbl><dbl><dbl>     <dbl><fct>   <chr>

 1 2.29e-123     0.636 0.344 0.097 3.65e-119 0       CD8B 

 2 7.62e-113     0.487 0.632 0.305 1.22e-108 0       LEF1 

 3 2.04e- 74     0.483 0.562 0.328 3.25e- 70 1       LEF1 

 4 1.39e- 61     0.462 0.598 0.39  2.22e- 57 1       ITM2A

 5 0.            2.69  0.972 0.483 0.        2       GNLY 

 6 0.            2.40  0.964 0.164 0.        2       GZMB 

 7 1.31e-121     0.768 0.913 0.671 2.09e-117 3       JUNB 

 8 2.06e- 94     0.946 0.426 0.155 3.28e- 90 3       RGS1 

 9 2.05e-255     1.57  0.586 0.09  3.27e-251 4       GZMK 

10 2.94e-140     1.57  0.69  0.253 4.68e-136 4       KLRB1

# ... with 14 more rows

## 存储marker

write.table(pbmc.markers,file="D:/allmarker.txt")

## 各种绘图

## 绘制Marker 基因的tsne图

FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP", "CD8A"),cols = c("gray", "red"))

## 绘制Marker 基因的小提琴图

VlnPlot(pbmc, features = c("MS4A1", "CD79A"))

VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)

## 绘制分cluster的热图

top10 <- pbmc.markers %>% group_by(cluster) %>% top_n(n = 10, wt = avg_logFC)

DoHeatmap(pbmc, features = top10$gene) + NoLegend()

剩下的便是寻找基因 marker 并对细胞类型进行注释(见下回分解)

R语言中的Cairo

什么是Cairo?

官方说法:Cairo is a vector graphics library with cross-device output support

翻译过来就是:Cairo是一个跨平台的开放源代码的矢量图形函数库,可以提供高质量的显示和打印输出。简单来说就是Cairo是一种绘制图形的工具库,它可以提供多种设备的输出。比如:png、pdf、ps、svg等。

今天就在R中简单展示一下利用Cairo进行高质量图形的渲染!

Cairo图形架构最主要的应用场合就是Linux的Gnome桌面环境,如果电脑系统是linux版本,首先可以安装Cairo的基本库libcairo2-dev和libxt-dev。方法如下:

sudo apt-get install libcairo2-dev

sudo apt-get install libxt-dev

随后在Rstudio中安装Cairo包:

install.packages("Cairo")

library(Cairo)

#检查Cairo包在自己的电脑系统下支持的图片格式

Cairo.capabilities()

可以看到,支持png、jpeg、pdf、svg、ps、raster格式的输出,接下来我们拿png作为示例进行展示。

library(ggplot2)

png(filename = "1.png",width = 400,height = 400)

ggplot(data = iris,aes(Sepal.Length,Sepal.Width,colour = Species)) + geom_point()

dev.off()

CairoPNG(filename = "2.png",width = 400,height = 400)

ggplot(data = iris,aes(Sepal.Length,Sepal.Width,colour = Species)) + geom_point()

dev.off()

上下两幅图形有丁点轻微的区别,感觉第二副图形更柔和一些(不知道是不是心理作用)。

n <- 10000

x1 <- matrix(rnorm(n), ncol = 2)

x2 <- matrix(rnorm(n, mean = 3, sd = 1.5), ncol = 2)

x <- rbind(x1, x2)

png(filename = "3.png",width = 500,height = 500)

Lab.palette <- colorRampPalette(c("blue", "orange", "red"), space = "Lab")

smoothScatter(x, colramp = Lab.palette,nrpoints = 250, ret.selection=TRUE,

xlab="",ylab="",axes=F)

dev.off()

CairoPNG(filename = "4.png",width = 500,height = 500)

Lab.palette <- colorRampPalette(c("blue", "orange", "red"), space = "Lab")

smoothScatter(x, colramp = Lab.palette,nrpoints = 250, ret.selection=TRUE,

xlab="",ylab="",axes=F)

dev.off()

上述两幅图形就有了明显的区别,第二幅图形更明亮,渲染的更好看一些。其实,你可以把Cairo看做一个图像处理软件,比如Photoshop?调整图形的颜色、字体等,甚至也可以用这个软件去画出任何图形。

1、K最近邻(k-NearestNeighbor,KNN)分类算法,是一个理论上比较成熟的方法,也是最简单的机器学习算法之一。该方法的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。

2、KNN算法中,所选择的邻居都是已经正确分类的对象。该方法在定类决策上只依据最邻近的一个或者几个样本的类别来决定待分样本所属的类别。 KNN方法虽然从原理上也依赖于极限定理,但在类别决策时,只与极少量的相邻样本有关。由于KNN方法主要靠周围有限的邻近的样本,而不是靠判别类域的方法来确定所属类别的,因此对于类域的交叉或重叠较多的待分样本集来说,KNN方法较其他方法更为适合。

3、KNN算法不仅可以用于分类,还可以用于回归。通过找出一个样本的k个最近邻居,将这些邻居的属性的平均值赋给该样本,就可以得到该样本的属性。更有用的方法是将不同距离的邻居对该样本产生的影响给予不同的权值(weight),如权值与距离成正比。

简言之,就是将未标记的案例归类为与它们最近相似的、带有标记的案例所在的类 。

原理及举例

工作原理:我们知道样本集中每一个数据与所属分类的对应关系,输入没有标签的新数据后,将新数据与训练集的数据对应特征进行比较,找出“距离”最近的k(通常k<20)数据,选择这k个数据中出现最多的分类作为新数据的分类。

算法描述

1、计算已知数据集中的点与当前点的距离

2、按距离递增次序排序

3、选取与当前数据点距离最近的K个点

4、确定前K个点所在类别出现的频率

5、返回频率最高的类别作为当前类别的预测

距离计算方法有"euclidean"(欧氏距离),”minkowski”(明科夫斯基距离), "maximum"(切比雪夫距离), "manhattan"(绝对值距离),"canberra"(兰式距离), 或 "minkowski"(马氏距离)等

Usage

knn(train, test, cl, k = 1, l = 0, prob =FALSE, use.all = TRUE)

Arguments

train

matrix or data frame of training set cases.

test

matrix or data frame of test set cases. A vector will  be interpreted as a row vector for a single case.

cl

factor of true classifications of training set

k

number of neighbours considered.

l

minimum vote for definite decision, otherwisedoubt. (More precisely, less thank-ldissenting votes are allowed, even

ifkis  increased by ties.)

prob

If this is true, the proportion of the votes for the

winning class are returned as attributeprob.

use.all

controls handling of ties. If true, all distances equal

to thekth largest are

included. If false, a random selection of distances equal to thekth is chosen to use exactlykneighbours.

kknn(formula = formula(train), train, test, na.action = na.omit(), k = 7, distance = 2, kernel = "optimal", ykernel = NULL, scale=TRUE, contrasts = c('unordered' = "contr.dummy", ordered = "contr.ordinal"))

参数:

formula                            A formula object.

train                                 Matrix or data frame of training set cases.

test                                   Matrix or data frame of test set cases.

na.action                         A function which indicates what should happen when the data contain ’NA’s.

k                                       Number of neighbors considered.

distance                          Parameter of Minkowski distance.

kernel                              Kernel to use. Possible choices are "rectangular" (which is standard unweighted knn), "triangular", "epanechnikov" (or beta(2,2)), "biweight" (or beta(3,3)), "triweight" (or beta(4,4)), "cos", "inv", "gaussian", "rank" and "optimal".

ykernel                            Window width of an y-kernel, especially for prediction of ordinal classes.

scale                                Logical, scale variable to have equal sd.

contrasts                         A vector containing the ’unordered’ and ’ordered’ contrasts to use

kknn的返回值如下:

fitted.values              Vector of predictions.

CL                              Matrix of classes of the k nearest neighbors.

W                                Matrix of weights of the k nearest neighbors.

D                                 Matrix of distances of the k nearest neighbors.

C                                 Matrix of indices of the k nearest neighbors.

prob                            Matrix of predicted class probabilities.

response                   Type of response variable, one of continuous, nominal or ordinal.

distance                     Parameter of Minkowski distance.

call                              The matched call.

terms                          The ’terms’ object used.

iris%>%ggvis(~Length,~Sepal.Width,fill=~Species)

library(kknn)

data(iris)

dim(iris)

m<-(dim(iris))[1]

val<-sample(1:m,size=round(m/3),replace=FALSE,prob=rep(1/m,m))

建立训练数据集

data.train<-iris[-val,]

建立测试数据集

data.test<-iris[val,]

调用kknn  之前首先定义公式

formula : Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width

iris.kknn<-kknn(Species~.,iris.train,iris.test,distance=1,kernel="triangular")

summary(iris.kknn)

# 获取fitted.values

fit <- fitted(iris.kknn)

# 建立表格检验判类准确性

table(iris.valid$Species, fit)

# 绘画散点图,k-nearest neighbor用红色高亮显示

pcol <- as.character(as.numeric(iris.valid$Species))

pairs(iris.valid[1:4], pch = pcol, col = c("green3", "red")[(iris.valid$Species != fit)+1]

二、R语言knn算法

install.packages("class")

library(class)

对于新的测试样例基于距离相似度的法则,确定其K个最近的邻居,在K个邻居中少数服从多数

确定新测试样例的类别

1、获得数据

2、理解数据

对数据进行探索性分析,散点图

如上例

3、确定问题类型,分类数据分析

4、机器学习算法knn

5、数据处理,归一化数据处理

normalize <- function(x){

num <- x - min(x)

denom <- max(x) - min(x)

return(num/denom)

}

iris_norm <-as.data.frame(lapply(iris[,1:4], normalize))

summary(iris_norm)

6、训练集与测试集选取

一般按照3:1的比例选取

方法一、set.seed(1234)

ind <- sample(2,nrow(iris), replace=TRUE, prob=c(0.67, 0.33))

iris_train <-iris[ind==1, 1:4]

iris_test <-iris[ind==2, 1:4]

train_label <-iris[ind==1, 5]

test_label <-iris[ind==2, 5]

方法二、

ind<-sample(1:150,50)

iris_train<-iris[-ind,]

iris_test<-iris[ind,1:4]

iris_train<-iris[-ind,1:4]

train_label<-iris[-ind,5]

test_label<-iris[ind,5]

7、构建KNN模型

iris_pred<-knn(train=iris_train,test=iris_test,cl=train_label,k=3)

8、模型评价

交叉列联表法

table(test_label,iris_pred)

实例二

数据集

http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data

导入数据

dir <-'http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data'wdbc.data <-read.csv(dir,header = F)

names(wdbc.data) <- c('ID','Diagnosis','radius_mean','texture_mean','perimeter_mean','area_mean','smoothness_mean','compactness_mean','concavity_mean','concave points_mean','symmetry_mean','fractal dimension_mean','radius_sd','texture_sd','perimeter_sd','area_sd','smoothness_sd','compactness_sd','concavity_sd','concave points_sd','symmetry_sd','fractal dimension_sd','radius_max_mean','texture_max_mean','perimeter_max_mean','area_max_mean','smoothness_max_mean','compactness_max_mean','concavity_max_mean','concave points_max_mean','symmetry_max_mean','fractal dimension_max_mean')

table(wdbc.data$Diagnosis)## M = malignant, B = benign

wdbc.data$Diagnosis <- factor(wdbc.data$Diagnosis,levels =c('B','M'),labels = c(B ='benign',M ='malignant'))