-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
137 lines (121 loc) · 5.01 KB
/
main.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
import wfdb
from sklearn.model_selection import train_test_split
import tensorflow as tf
import numpy as np
from timeit import default_timer as timer
import preprocessing
import pickle
import scipy
import signalFeatures
from imblearn.over_sampling import SMOTE
import tensorFlowTesting as tft
import csv
FEATURES = ['parity', 'maternal age', 'previous abortions', 'weight', 'hypertension', 'diabetes','smoker','bleeding first trimester', 'bleeding second trimester', 'funneling', 'placental position','Root mean square', 'median frequency', 'peak frequency', 'sample entropy','gestation period']
# 13 minutes op
def get_records():
"""
get all 300 records from the database
:return: a list of all 300 records
"""
file_name = "RECORDS.txt"
records = []
with open(file_name, "r") as f:
for line in f:
record_name = line[:-1]
record = wfdb.rdrecord(record_name,pb_dir='tpehgdb/tpehgdb')
records.append(record)
return records
def print_10(arr):
for i in range(10):
print(arr[i])
if __name__ == "__main__":
# print option: 3 digits
np.set_printoptions(precision=3,floatmode='fixed')
# records = get_records()
# # stores the records
# with open('records.pkl', 'wb') as f:
# pickle.dump(records,f)
"""records.pkl is too large to push to Git (~1Gb)"""
# # gets the records
# with open('records.pkl', 'rb') as f:
# records = pickle.load(f)
# # print(len(records))
# # get features
# medFeatures, labels, canceled_index = preprocessing.get_features(records)
# fvlFile = "tpehgdb_features__filter_0.08_Hz-4.0_Hz.fvl"
# fourFeatures = signalFeatures.rdFVL(fvlFile, canceled_index, 1)
# # combine features
# combined_features = np.append(medFeatures, fourFeatures, axis=1)
# # stores the features
# with open('features_labels.pkl', 'wb') as f:
# pickle.dump([combined_features, labels],f)
# gets the features and outputs (labels = gestation periods)
with open('features_labels.pkl', 'rb') as f:
features, labels = pickle.load(f)
with open('project_features_labels.csv', 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',')
csv_writer.writerow([feature for feature in FEATURES])
for row in range(len(features)):
print(features[row])
# print(features.shape)
cout = 0
for feature in features:
cout+=1
print(cout)
# # preterm = 1
# # term = 0
# # formatting the labels
# for x in np.nditer(labels, op_flags=['readwrite']):
# if x < 37:
# x[...] = 1
# else:
# x[...] = 0
# # label is converted to int and falttened
# labels = labels.astype(int)
# labels = labels.flatten()
# print(labels.shape)
# print(features[:5])
# print(labels[:5])
# # # gets the features and outputs (labels = gestation periods)
# # with open('actual_features_labels.pkl', 'wb') as f:
# # pickle.dump([features, labels], f)
# # SMOTE
# sm = SMOTE()
# SMOTE_features, SMOTE_labels = sm.fit_resample(features, labels)
# with open('SMOTE_features_labels.pkl', 'wb') as f:
# pickle.dump([SMOTE_features, SMOTE_labels],f)
# print_10(SMOTE_features)
# print_10(SMOTE_labels)
# # get SMOTE data
# with open('SMOTE_features_labels.pkl', 'rb') as f:
# features, labels = pickle.load(f)
# # reshape data
# features = np.reshape(features, (300, 15,1) )
# labels = np.reshape(labels, (300,) )
# # trials
# # splitting the data
# acc = []
# sen = []
# spe = []
# # load the model
# model = tf.keras.models.load_model('6.model')
# # gets the sensitivity, accuracy, specificity of each trial
# for i in range(30):
# x_train, x_test, y_train, y_test = train_test_split(features, labels, test_size=.2, random_state=i)
# # model.fit(x_train, y_train, epochs=300)
# loss, ac = model.evaluate(x_test, y_test)
# predictions = model.predict(x_test)
# sens, spec = tft.sensitivity_and_specificity(predictions, y_test)
# acc.append(ac)
# sen.append(sens)
# spe.append(spec)
# # write sen and spe to csv file
# with open('sensitivity_specificity.csv', mode='w') as employee_file:
# employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
# employee_writer.writerow(['sensitivity', 'specificity'])
# for index, _ in enumerate(spe):
# employee_writer.writerow([sen[index], spe[index]])
# # print all stats
# print("avg acc: {}".format(sum(acc)/len(acc))) # avg: 0.6811111082633337
# print("avg sensitivity: {}".format(sum(sen)/len(sen))) # avg: 0.7544749259299052
# print("avg specificity: {}".format(sum(spe)/len(spe))) # avg: 0.6658020327534167