-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobal_model.py
160 lines (123 loc) · 5.86 KB
/
global_model.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
# -*- coding: utf-8 -*-
"""global_model.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1MHMdb6CHlhol1Qd2Q62Qm8ff97zOe1d_
"""
import torch
import numpy as np
# from tqdm import tqdm
from tqdm.notebook import tqdm_notebook as tqdm
import torch.nn.functional as F
import torch.nn as nn
import random
import math
import pandas as pd
from models.sleep_model import simple_model
from models.nmf_embed import pad_NMF, sleep_NMF, find_opt_num_feat
from models.early_stopping import EarlyStopping
from models.find_threshold import find_optimal_threshold
from models.model_training import model_training
from data.loader import Dataset
from data.missing_distribution_param_est import params_estimate
def global_model_handle(dataset_file, mode='handle', param_choice='tune'):
assert mode in ['evaluate', 'handle'], 'mode should be either evaluate or handle only'
assert param_choice in ['tune', 'default'], 'param_choice should be either tune or default'
if param_choice == 'tune':
alpha, beta = params_estimate('data/' + dataset_file)
elif param_choice == 'default':
alpha = 1.11
beta = 31.09
Data = pd.read_csv('data/' + dataset_file)
# the dataset_file should have SleepStatus and actigraphy in its columns
assert 'SleepStatus' in Data.columns, 'The file should have SleepStatus column'
assert 'actigraphy' in Data.columns, 'The file should have actigraphy column'
Data['Label'] = Data['SleepStatus'].apply(lambda x: 0 if x == 'Sleep' else 1.)
Data['denote'] = Data['actigraphy'].apply(lambda x: 0. if np.isnan(x) else 1.)
fillmisscol = np.full((Data.shape[0]), 0)
i = 0
while i < Data.shape[0]:
if Data['denote'][i] == 0:
counter = 1
while i + counter < Data.shape[0] and Data['denote'][i + counter] == 0:
counter += 1
fillmisscol[i:i+counter] = counter
i = i + counter
else:
i += 1
Data['type'] = fillmisscol // 30 + 1
Data.loc[ fillmisscol==0 , 'type'] = 0
# Create additional missing masks if developers want to do training with their own data
Data['denote_true'] = Data['denote']
if mode == 'evaluate':
for i in range(50):
getrandom = random.randint(0, Data.shape[0])
xd = np.random.gamma(alpha, beta, 1)[0]
Data.loc[getrandom: min(getrandom+xd, Data.shape[0]), 'denote'] = 0
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
Data.loc[Data['denote'] == 0, 'actigraphy'] = np.nan
thresh = np.quantile(Data[~Data['actigraphy'].isnull()]['actigraphy'], 0.9)
Data.loc[:, 'actigraphy'] = Data['actigraphy'].apply(lambda x: 1 if x > thresh else x/thresh)
# NMF
slp_data = pad_NMF(Data)
NMF_info = sleep_NMF(slp_data, Data)
Data['NMF'] = NMF_info.reshape(-1)[:Data.shape[0]]
# Add the denotations
Data['known_label'] = Data['Label']
Data.loc[Data['denote'] == 0, 'known_label'] = 0
Data.loc[Data['denote'] == 0, 'actigraphy'] = -1
traindata = Data[Data['denote_true'] == 1]
testdata = Data[Data['denote_true'] == 0]
X_train = traindata[['actigraphy', 'denote', 'NMF', 'known_label']].to_numpy()
y_train = traindata['Label']
thresh = int(X_train.shape[0]*0.8)
X_valid = X_train[thresh:, :]
y_valid = y_train[thresh:]
X_train = X_train[:thresh, :]
y_train = y_train[:thresh]
X_test = testdata[['actigraphy', 'denote', 'NMF', 'known_label']].to_numpy()
y_test = testdata['Label']
X_train = torch.tensor(X_train)#.to(device)
X_test = torch.tensor(X_test)#.to(device)
X_valid = torch.tensor(X_valid)
y_train = torch.tensor(y_train.values)#.to(device)
y_test = torch.tensor(y_test.values)#.to(device)
y_valid = torch.tensor(y_valid.values)#.to(device)
sleep_weight = y_train.shape[0]/ (2* y_train[y_train == 0].shape[0])
wake_weight = y_train.shape[0]/ (2* y_train[y_train == 1].shape[0])
params = {'batch_size': 64,
'shuffle': True,
'num_workers': 2}
training_set = Dataset(X_train, y_train)
training_generator = torch.utils.data.DataLoader(training_set, **params)
valid_set = Dataset(X_valid, y_valid)
valid_generator = torch.utils.data.DataLoader(valid_set, **params)
if mode == 'evaluate':
model = model_training(training_generator, valid_generator, device, sleep_weight, wake_weight, pretrain=True)
if mode == 'handle':
model = torch.load('models/pretrain_global_model/global_model.pt').to(device)
result = model(torch.Tensor(Data[['actigraphy', 'denote', 'NMF', 'known_label']].to_numpy()).float().to(device))[:, 1]
dfvalid = pd.DataFrame()
dfvalid['prob'] = result.detach().cpu().numpy()
dfvalid['ground'] = Data['Label'].values
dfvalid['type'] = Data['type']
threshold = find_optimal_threshold(dfvalid[dfvalid['type'] == 0 ]['ground'], dfvalid[dfvalid['type'] == 0 ]['prob'])
dfvalid['pred'] = dfvalid['prob'].apply(lambda x: 1 if x>=threshold else 0)
dfvalid['acti'] = Data['actigraphy'].values
dfvalid['NMF'] = Data['NMF'].values
dfvalid['denote'] = Data['denote_true']
if mode == 'evaluate':
for i in [[1,2], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]:
print('------------------------------------')
all0 = dfvalid[(dfvalid['ground'] == 0) & (dfvalid['type'].isin(i)) & (Data['denote_true'] == 0)].shape[0]
all1 = dfvalid[(dfvalid['ground'] == 1) & (dfvalid['type'].isin(i)) & (Data['denote_true'] == 0)].shape[0]
tp = dfvalid[(dfvalid['ground'] == 0) & (dfvalid['type'].isin(i)) & (dfvalid['pred'] == 0) & (Data['denote_true'] == 0)].shape[0]
tn = dfvalid[(dfvalid['ground'] == 1) & (dfvalid['type'].isin(i)) & (dfvalid['pred'] == 1) & (Data['denote_true'] == 0)].shape[0]
print('Type ', [[1,2], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]].index(i) + 1)
print('Total_sleep: ', all0)
if all0 > 0:
print('AccSleep: ', tp/all0)
print('Total_wake: ', all1)
if all1 > 0:
print('AccWake: ', tn/all1)
return dfvalid