-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodels.py
More file actions
149 lines (103 loc) · 3.46 KB
/
Copy pathmodels.py
File metadata and controls
149 lines (103 loc) · 3.46 KB
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
""" Matrix deconvolution models.
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
__author__ = "Yifeng Tao"
def _wrap_data(mat):
""" Wrap default numpy or list data into PyTorch variables.
"""
return Variable(torch.FloatTensor(mat))
class ModelBase(nn.Module):
""" Base models for all models.
"""
def __init__(self, args):
""" Initialize the hyperparameters of model.
Parameters
----------
args: arguments for initializing the model.
"""
super(ModelBase, self).__init__()
self.epsilon = 1e-10 #1e-4
self.dim_m = args["dim_m"]
self.dim_n = args["dim_n"]
self.dim_k = args["dim_k"]
self.learning_rate = args["learning_rate"]
self.weight_decay = args["weight_decay"]
def build(self):
""" Define modules of the model.
"""
raise NotImplementedError
class NND(ModelBase):
""" NND model for deconvolution.
"""
def __init__(self, args, **kwargs):
""" Initialize the model.
Parameters
----------
args: arguments for initializing the model.
"""
super(NND, self).__init__(args, **kwargs)
def build(self):
""" Define modules of the model.
"""
self.mat_c = torch.nn.Parameter(
data=torch.Tensor(self.dim_m, self.dim_k), requires_grad=True)
self.mat_c.data.uniform_(-1, 1)
self.mat_f = torch.nn.Parameter(
data=torch.Tensor(self.dim_k, self.dim_n), requires_grad=True)
self.mat_f.data.uniform_(0, 1)
self.optimizer = optim.Adam(
self.parameters(),
lr=self.learning_rate,
weight_decay=self.weight_decay)
def forward(self):
""" Forward parameters to the output of estimated/predicted B.
"""
mat_f_abs = torch.abs(self.mat_f)
mat_f = F.normalize(mat_f_abs, p=1, dim=0)
mat_p = torch.mm(self.mat_c, mat_f)
return mat_p, mat_f
def train(self, mat_b, M_train, M_test, max_iter=None, inc=1, verbose=False):
""" Train the matrix factorization using gradient descent and monitor.
Parameters
----------
mat_b: numpy matrix
bulk data, each column a sample, each row a gene module.
M_train: numpy 0/1 mask matrix
same size of mat_b, positions of 1 mean seen data, otherwise unseen.
max_iter: int
max iterations of training.
inc: int
intervals to evaluate the training.
verbose: boolen
whether print too much itermediat results.
Returns
-------
Deconvolved matrices C, F. Traing L2 loss and test L2 loss.
"""
mat_b = _wrap_data(mat_b)
M_train = _wrap_data(M_train)
M_test = _wrap_data(M_test)
previous_error = 1e10
for iter_train in range(0, max_iter+1):
mat_p, mat_f = self.forward()
self.optimizer.zero_grad()
loss = torch.norm((mat_p-mat_b)*M_train, 2)**2 / M_train.sum()
loss.backward()
self.optimizer.step()
if iter_train % inc == 0:
l2 = 1.0*loss.data.numpy() / M_train.sum().numpy()
if verbose:
print("iter=%d, l2=%.2e"% (iter_train,l2))
if (previous_error - l2) / previous_error < self.epsilon:
break
previous_error = l2
if iter_train >= max_iter-2*inc:
print("warning: max_iter too small...")
loss = torch.norm((mat_p-mat_b)*M_test, 2)**2
l2_test = loss.data.numpy() / M_test.sum().numpy()
return np.array(self.mat_c.data.numpy(), dtype=float), np.array(mat_f.data.numpy(), dtype=float), l2, l2_test