-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyeast_onlygene_emb2.py
174 lines (146 loc) · 6.92 KB
/
yeast_onlygene_emb2.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
# -*- coding: utf-8 -*-
"""yeast_onlygene_emb2.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1tVGdiOF2CSWgiR6SP513vCUojqgqblH-
"""
from sklearn.model_selection import train_test_split
import pandas as pd
import torch
from torch import nn, cat as tcat, tensor, optim, flatten
from util import read_gene_batch, get_all_gene
import matplotlib.pyplot as plt
from numpy import mean
import numpy as np
from scipy.stats import spearmanr
# only gene
class Fit_model(nn.Module):
def __init__(self):
super(Fit_model, self).__init__()
# 2**4 embedding dim
self.emb_dim = 2
self.gene_1_emb = nn.Embedding(4000, self.emb_dim )
self.gene_2_emb = nn.Embedding(4000, self.emb_dim )
self.fit_pred = nn.Sequential(
nn.Linear(2* self.emb_dim, 2**6),
nn.ReLU(),
nn.Linear(2**6, 2**5),
nn.ReLU(),
nn.Linear(2**5, 1)
)
def forward(self, gid_1, gid_2):
emb_1, emb_2 = self.gene_1_emb(gid_1).squeeze(1), self.gene_2_emb(gid_2).squeeze(1)
emb = tcat((emb_1, emb_2), dim=1)
fit = self.fit_pred(emb)
return fit
def train():
model = Fit_model()
lr_t = 1e-3
wd = 1e-3
optimizer = optim.Adam(model.parameters(), lr=lr_t, weight_decay= wd)
bsize = 1000
# the interaction database
gene_interaciton = path_train
test_interaction = path_test
gene_interaciton_full = data_file
gene_interaciton = data_file
gen_1_all, gen_2_all = get_all_gene(gene_interaciton_full)
train_loss_epoc_l = []
val_loss_epoc_l = []
min_valid_loss = np.inf
max_epoch = 40
for epoch in range(max_epoch):
loss_l = []
train_pred_fit = []
train_fit = []
test_pred_fit = []
test_fit = []
for gene_data, tmp_real_fit in read_gene_batch(gene_interaciton, gen_1_all, gen_2_all, bsize):
optimizer.zero_grad()
pred_fit = model(gene_data[:,0].view(-1,1),gene_data[:,1].view(-1,1))
# MSE loss
loss = ((pred_fit - tmp_real_fit.view(-1, 1))**2).sum()**.5
loss_l += [loss.item()]
loss.backward()
optimizer.step()
train_pred_fit += list(pred_fit.detach().numpy())
train_fit += list(tmp_real_fit.detach().numpy())
if max_epoch > 100:
if epoch%100 == 0:
print(f'epoch = {epoch}, train loss: {mean(loss_l)}')
else:
print(f'epoch = {epoch}, train loss: {mean(loss_l)}')
train_loss_epoc_l += [mean(loss_l)]
model.eval() # Optional when not using Model Specific layer
with torch.no_grad():
val_loss_l = []
for gene_data, tmp_val_fit in read_gene_batch(test_interaction, gen_1_all, gen_2_all, bsize):
pred_fit = model(gene_data[:,0].view(-1,1),gene_data[:,1].view(-1,1))
valid_loss = ((pred_fit - tmp_val_fit.detach().view(-1, 1))**2).sum()**.5
val_loss_l += [valid_loss.item()]
test_pred_fit += list(pred_fit.detach().numpy())
test_fit += list(tmp_val_fit.detach().numpy())
if max_epoch > 100:
if epoch%100 == 0:
print(f'epoch = {epoch}, validation loss: {mean(val_loss_l)}')
else:
print(f'epoch = {epoch}, validation loss: {mean(val_loss_l)}')
val_loss_epoc_l += [mean(val_loss_l)]
model.eval()
train_loss = mean(loss_l)
# a, b = np.polyfit(train_fit, train_pred_fit, 1)
a, b = 1, 0
fig, axs = plt.subplots(2,2, figsize=(25, 25))
axs[0,0].scatter(np.array(train_fit), np.array(train_pred_fit))
axs[0,0].plot(np.array(train_fit), a*np.array(train_fit)+b, 'r-')
axs[0,0].title.set_text('train')
min_x = np.min((np.array(train_fit).min(), np.array(train_pred_fit).min()))
max_x = np.max((np.array(train_fit).max(), np.array(train_pred_fit).max()))
axs[0,0].set_xlim([min_x, max_x])
axs[0,0].set_ylim([min_x, max_x])
axs[0,0].set_aspect('equal', adjustable='box')
val_loss = mean(val_loss_l)
# a, b = np.polyfit(test_fit, test_pred_fit, 1)
min_x = np.min((np.array(test_fit).min(), np.array(test_pred_fit).min()))
max_x = np.max((np.array(test_fit).max(), np.array(test_pred_fit).max()))
axs[0,1].scatter(np.array(test_fit), np.array(test_pred_fit))
axs[0,1].plot(np.array(test_fit), a*np.array(test_fit)+b, 'r-')
axs[0,1].set_xlim([min_x, max_x])
axs[0,1].set_ylim([min_x, max_x])
axs[0,1].set_aspect('equal', adjustable='box')
axs[0,1].title.set_text('val')
axs[1,0].plot(range(len(train_loss_epoc_l)), train_loss_epoc_l)
axs[1,0].title.set_text('train loss')
axs[1,1].plot(range(len(val_loss_epoc_l)), val_loss_epoc_l)
axs[1,1].title.set_text('val loss')
plt.savefig(path_data + 'go_and_gene_lr_' + str(lr_t)+'_wd_'+ str(wd) + '.png')
# calculation
corr_train = np.corrcoef(np.array(train_pred_fit).reshape(1,-1), np.array(train_fit).reshape(1,-1))
corr_val = np.corrcoef(np.array(test_pred_fit).reshape(1,-1), np.array(test_fit).reshape(1,-1))
coef_train, train_p = spearmanr(np.array(train_pred_fit).reshape(-1,1), np.array(train_fit).reshape(-1,1))
coef_val, val_p = spearmanr(np.array(test_pred_fit).reshape(-1,1), np.array(test_fit).reshape(-1,1))
print(f'Peason correlation for train: {corr_train[0,1]} and validation: {corr_val[0,1]}')
print(f'Spearman correlation for train: {coef_train} and validation: {coef_val}')
print(f'Epoch {epoch+1} \t\t Training Loss: {train_loss} \t\t Validation Loss: {val_loss }')
if min_valid_loss > val_loss:
print(f'Validation Loss Decreased({min_valid_loss} and {val_loss}) \t Saving The Model')
min_valid_loss = val_loss
# Saving State Dict
torch.save(model.state_dict(), path_data + 'gene_model_emb_' + str(model.emb_dim) +'.pth')
return model, train_pred_fit, train_fit, test_pred_fit, test_fit, train_loss_epoc_l, val_loss_epoc_l
def main():
model, train_pred_fit, train_fit, test_pred_fit, test_fit, train_loss_epoc_l, val_loss_epoc_l = train()
return model, train_pred_fit, train_fit, test_pred_fit, test_fit, train_loss_epoc_l, val_loss_epoc_l
if __name__ == '__main__':
# only gene
path_data = r"/Users/wangshuhui/Downloads/dataset_dooc/"
# data_file = 'test_data_gene.txt'
data_file = path_data + 'data/full_data_gene.txt'
path_train = path_data +"train_data_full_gene.csv"
path_test = path_data +"test_data_full_gene.csv"
#if not os.path.exists(path_train):
df = pd.read_table(data_file, delimiter=" ", header=None)
df_train, df_test = train_test_split(df, test_size=0.3, random_state=42)
df_train.to_csv(path_train , sep=' ', index=False, header=False)
df_test.to_csv(path_test, sep=' ', index=False, header=False)
model, train_pred_fit, train_fit, test_pred_fit, test_fit, train_loss_epoc_l, val_loss_epoc_l = main()