louvain聚类
import scanpy as sc
import matplotlib
import numpy as np
import pandas as pd
import seaborn as sns
%matplotlib inline
import matplotlib.pyplot as plt
# from scDML import scDMLModel
# from scDML.utils import print_dataset_information
from plotly.offline import init_notebook_mode
init_notebook_mode(connected = True)
# read data
adata=sc.read("./bct_raw.h5ad")
print(adata)
#print(adata.X[0:10,0:10].toarray())
#print_dataset_information(adata)
# View raw data,check the batch effect of this batch effect
adata_copy=adata.copy()
sc.pp.normalize_total(adata_copy,target_sum=1e4)
sc.pp.log1p(adata_copy)
sc.pp.scale(adata_copy)
sc.tl.pca(adata_copy)
sc.pp.neighbors(adata_copy)
sc.tl.louvain(adata_copy)
sc.tl.umap(adata_copy)
sc.pl.umap(adata_copy,color=["BATCH","celltype"])
结果如下
kmeans聚类
# adata_copy.obs["louvain"]
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=20, random_state=0).fit(adata_copy.obsm["X_pca"])
adata_copy.obs['init_cluster'] = kmeans.labels_.astype(str)
可以看到这两种方法的结果其实是有区别的
看下面的例子
不仅如此,还有一个问题,就是新创建一个obs,很容易出以下问题
例如一个adata,我现在新创建一个obs,可以直接赋值,但是这个结果里面的类型就不好改变了,正确的做法如下
import scanpy as sc
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from QUEST import QUEST
import os
os.system("clear")
adata_full = sc.read("/Users/xiaokangyu/Desktop/dataset/single_cell/FullPancreas/human_pancreas_norm_complexBatch.h5ad")
adata_full.obs["BATCH"]=adata_full.obs["tech"].copy()
adata_full.X=adata_full.layers["counts"].copy()
#######################################################################################
#######################################################################################
#################### create new BATCH #################################################
pre_idx=adata_full.obs["BATCH"].isin(["inDrop1","inDrop2","inDrop3","inDrop4"]).values
new_batch_values=np.array(adata_full.obs["BATCH"].values) # shou
new_batch_values[pre_idx]="predict_BATCH"
new_batch_values[~pre_idx]="train_BATCH"
adata_full.obs["BATCHNew"]=new_batch_values
adata_full.obs["BATCHNew"]=adata_full.obs["BATCHNew"].astype("category")
#######################################################################################
#######################################################################################
可以参考这个adata_full.obs["BATCHNew"]
是怎么创建的,可能更有更简单的实现方式,后面再更新结果