-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess.py
308 lines (254 loc) · 12.2 KB
/
preprocess.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# setup environment
import os
smoke_test = ('CI' in os.environ) # for continuous integration tests
import scanpy as sc
import torch
import torch.nn as nn
import math
import numpy as np
import anndata as ad
import torch
import random
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from torch.utils.data import Dataset,DataLoader,Sampler
from scipy.sparse import csr_matrix
def data_load(anndata, n_top_genes, batch_key = 'batch_2', condition_key = 'batch', groundtruth_key = None):
######### 该代码用于预处理scanpy的原始数据,将单细胞测序数据进行清洗和质控,并且normalized它们 ##########
datasets = anndata.copy()
if isinstance(datasets.X, csr_matrix):
# 如果是稀疏矩阵,使用toarray()方法转换为NumPy数组,然后进行四舍五入
datasets.X = np.round(datasets.X.toarray()).astype(int)
else:
# 如果是NumPy数组,直接进行四舍五入
datasets.X = np.round(datasets.X).astype(int)
datasets.obs['batch'] = datasets.obs[condition_key].astype('category')
datasets.obs['batch_2'] = datasets.obs[batch_key].astype('category')
if groundtruth_key is not None:
datasets.obs['groundtruth'] = datasets.obs[groundtruth_key].astype('category')
datasets.layers['counts'] = datasets.X.copy()
# 数据筛选
sc.pp.filter_cells(datasets, min_genes=200)
sc.pp.filter_genes(datasets, min_cells=3)
raw = datasets.copy()
# 数据标准化
sc.pp.normalize_total(datasets, target_sum=1e4)
# 进行log1p转换
sc.pp.log1p(datasets)
datasets.layers['lognorm'] = datasets.X.copy()
# 识别高变基因
sc.pp.highly_variable_genes(datasets, batch_key= None, n_top_genes=n_top_genes)
# 将高变基因存在var中
datasets.raw = datasets
# 保留高变基因
datasets = datasets[:, datasets.var.highly_variable]
# scale数据
sc.pp.scale(datasets, max_value=10)
# batch = np.unique(datasets.obs[batch_key])
# list_batch = []
# for x in batch:
# adata_iter = datasets[datasets.obs[batch_key] == x]
# sc.pp.normalize_total(adata_iter, target_sum=1e5)
# list_batch.append(adata_iter)
# datasets = ad.concat(list_batch)
# datasets = sc.pp.log1p(datasets, copy = True)
# datasets.layers['lognorm'] = datasets.X.copy()
# # 识别高变基因
# sc.pp.highly_variable_genes(datasets, n_top_genes=n_top_genes, batch_key='batch')
# # 将高变基因存在var中
# datasets.raw = datasets
# # 保留高变基因
# datasets = datasets[:, datasets.var.highly_variable]
var_names = datasets.var_names
index_names = datasets.obs_names
return datasets,raw,var_names,index_names
# class BatchDataLoader(object):
# """
# This custom DataLoader serves mini-batches that are either fully-observed (i.e. labeled)
# or partially-observed (i.e. unlabeled) but never mixed.
# """
# def __init__(self, data_x, data_y, batch_size, num_classes, missing_label=-1):
# super().__init__()
# self.data_x = data_x
# self.data_y = data_y
# self.batch_size = batch_size
# self.num_classes = num_classes
# self.unlabeled = torch.where(data_y == missing_label)[0]
# self.num_unlabeled = self.unlabeled.size(0)
# self.num_unlabeled_batches = math.ceil(self.num_unlabeled / self.batch_size)
# self.labeled = torch.where(data_y != missing_label)[0]
# self.num_labeled = self.labeled.size(0)
# self.num_labeled_batches = math.ceil(self.num_labeled / self.batch_size)
# self.classed = [torch.where(data_y == c)[0] for c in range(num_classes)]
# self.num_classed = [c.size(0) for c in self.classed]
# self.num_class_batches = [math.ceil(indices / self.batch_size) for indices in self.num_classed]
# assert self.data_x.size(0) == self.data_y.size(0)
# assert len(self) > 0
# @property
# def size(self):
# return self.data_x.size(0)
# def __len__(self):
# return self.num_unlabeled_batches + self.num_labeled_batches
# def _sample_batch_indices(self):
# batch_order = torch.randperm(len(self)).tolist()
# unlabeled_idx = self.unlabeled[torch.randperm(self.num_unlabeled)]
# labeled_idx = self.labeled[torch.randperm(self.num_labeled)]
# class_idx = [self.classed[c][torch.randperm(self.num_classed[c])] for c in range(self.num_classes)]
# # print(class_idx[0].shape,class_idx[1].shape)
# slices = []
# for i in range(self.num_unlabeled_batches):
# _slice = unlabeled_idx[i * self.batch_size : (i + 1) * self.batch_size]
# slices.append((_slice, False))
# # for i in range(self.num_labeled_batches):
# # _slice = labeled_idx[i * self.batch_size : (i + 1) * self.batch_size]
# # slices.append((_slice, True))
# for c in range(self.num_classes):
# for i in range(self.num_class_batches[c]):
# _slice = class_idx[c][i * self.batch_size : (i + 1) * self.batch_size]
# slices.append((_slice, True))
# return slices, batch_order
# def __iter__(self):
# slices, batch_order = self._sample_batch_indices()
# for i in range(len(batch_order)):
# _slice = slices[batch_order[i]]
# if _slice[1]:
# # labeled
# yield self.data_x[_slice[0]], nn.functional.one_hot(
# self.data_y[_slice[0]], num_classes=self.num_classes
# )
# else:
# # unlabeled
# yield self.data_x[_slice[0]], None
# class BatchDataLoader2(object):
# """
# This custom DataLoader serves mini-batches that are either fully-observed (i.e. labeled)
# or partially-observed (i.e. unlabeled) but never mixed.
# """
# def __init__(self, data_x, data_y, batch_size, num_classes=2, missing_label=-1):
# super().__init__()
# self.data_x = data_x
# self.data_y = data_y
# self.batch_size = batch_size
# self.num_classes = num_classes
# self.unlabeled = torch.where(data_y == missing_label)[0]
# self.num_unlabeled = self.unlabeled.size(0)
# self.num_unlabeled_batches = math.ceil(self.num_unlabeled / self.batch_size)
# self.labeled = torch.where(data_y != missing_label)[0]
# self.num_labeled = self.labeled.size(0)
# self.num_labeled_batches = math.ceil(self.num_labeled / self.batch_size)
# assert self.data_x.size(0) == self.data_y.size(0)
# assert len(self) > 0
# @property
# def size(self):
# return self.data_x.size(0)
# def __len__(self):
# return self.num_unlabeled_batches + self.num_labeled_batches
# def _sample_batch_indices(self):
# batch_order = torch.randperm(len(self)).tolist()
# unlabeled_idx = self.unlabeled[torch.randperm(self.num_unlabeled)]
# labeled_idx = self.labeled[torch.randperm(self.num_labeled)]
# slices = []
# for i in range(self.num_unlabeled_batches):
# _slice = unlabeled_idx[i * self.batch_size : (i + 1) * self.batch_size]
# slices.append((_slice, False))
# for i in range(self.num_labeled_batches):
# _slice = labeled_idx[i * self.batch_size : (i + 1) * self.batch_size]
# slices.append((_slice, True))
# return slices, batch_order
# def __iter__(self):
# slices, batch_order = self._sample_batch_indices()
# for i in range(len(batch_order)):
# _slice = slices[batch_order[i]]
# if _slice[1]:
# # labeled
# yield self.data_x[_slice[0]], nn.functional.one_hot(
# self.data_y[_slice[0]], num_classes=self.num_classes
# )
# else:
# # unlabeled
# yield self.data_x[_slice[0]], None
def transform_numpy(data, cuda):
if cuda==True:
data = torch.Tensor(data).cuda()
else:
data = torch.Tensor(data)
return data
def shuffer(adata):
idx = np.random.permutation(len(adata.obs_names))
shuffled_obs_names = adata.obs_names[idx]
adata = adata[shuffled_obs_names]
return adata
# class BatchSampler(Sampler):
# def __init__(self, adata, batch_size, label_encoder = LabelEncoder()):
# self.labels = torch.Tensor(label_encoder.fit_transform(adata.obs['batch'])).cuda()
# self.batch_size = batch_size
# self.num_labels = torch.unique(self.labels)
# self.classed = [torch.where(self.labels == c)[0] for c in range(len(self.num_labels))]
# self.counts_labels = [c.size(0) for c in self.classed]
# self.num_class_batches = [math.ceil(indices / self.batch_size) for indices in self.counts_labels]
# def __iter__(self):
# iter_labels = self.labels # 可迭代的
# indices = {} # 用于储存不同的labels对应的index
# for c in self.num_labels.tolist():
# indices[c] = [i for i, label in enumerate(self.labels) if label == c]
# while len(iter_labels) > 0:
# batch_labels = iter_labels[0].item()
# select_indices = indices[batch_labels]
# indices_iter = [i for i, label in enumerate(iter_labels) if label == batch_labels]
# if len(select_indices) >= self.batch_size:
# yield select_indices[:self.batch_size]
# indices[batch_labels] = list(set(indices[batch_labels]) - set(select_indices[:self.batch_size]))
# iter_labels = torch.Tensor([label for i, label in enumerate(iter_labels) if i not in indices_iter[:self.batch_size]])
# else:
# yield select_indices
# indices[batch_labels] = []
# iter_labels = torch.Tensor([label for i, label in enumerate(iter_labels) if i not in indices_iter])
# def __len__(self):
# return np.sum(self.num_class_batches)
class BatchSampler(Sampler):
def __init__(self, adata, batch_size, cuda, label_encoder = LabelEncoder()):
self.cuda = cuda
if cuda:
self.labels = torch.tensor(label_encoder.fit_transform(adata.obs['batch'])).cuda()
else:
self.labels = torch.tensor(label_encoder.fit_transform(adata.obs['batch'])).cpu()
self.batch_size = batch_size
self.num_labels = torch.unique(self.labels)
self.indices = {} # Precompute indices
for c in self.num_labels.tolist():
self.indices[c] = torch.where(self.labels == c)[0]
self.num_class_batches = [math.ceil(len(indices) / self.batch_size) for indices in self.indices.values()]
self.iter_labels = [torch.ones(n)*i for i,n in enumerate(self.num_class_batches)]
self.iter_labels = torch.cat(self.iter_labels).int().tolist()
def __iter__(self):
iter_indices = self.indices.copy()
for batch_labels in self.iter_labels:
select_indices = iter_indices[batch_labels]
if len(select_indices) >= self.batch_size:
yield select_indices[:self.batch_size]
iter_indices[batch_labels] = select_indices[self.batch_size:]
else:
yield select_indices
iter_indices[batch_labels] = torch.tensor([], dtype=torch.long) # Empty tensor
def __len__(self):
return np.sum(self.num_class_batches)
class scDataset(Dataset):
def __init__(self, adata, cuda, transform=None):
super().__init__()
self.batch_label = pd.get_dummies(adata.obs['batch_2']).values
self.condition_label = pd.get_dummies(adata.obs['batch']).values
self.expr = adata.X # 注意需不需要toarray()
self.transform = transform
self.cuda = cuda
def __len__(self):
return len(self.batch_label)
def __getitem__(self, index):
expr = self.expr[index,:]
batch_label = self.batch_label[index,:]
condition_label = self.condition_label[index,:]
ifcuda = self.cuda
if self.transform:
expr = transform_numpy(expr,ifcuda)
batch_label = transform_numpy(batch_label,ifcuda)
condition_label = transform_numpy(condition_label,ifcuda)
return expr,condition_label,batch_label