forked from physionetchallenges/python-example-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
team_code.py
218 lines (167 loc) · 7.52 KB
/
team_code.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
#!/usr/bin/env python
# Edit this script to add your team's code. Some functions are *required*, but you can edit most parts of the required functions,
# change or remove non-required functions, and add your own functions.
################################################################################
#
# Optional libraries, functions, and variables. You can change or remove them.
#
################################################################################
import joblib
import numpy as np
import os
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
import sys
from helper_code import *
################################################################################
#
# Required functions. Edit these functions to add your code, but do not change the arguments of the functions.
#
################################################################################
# Train your digitization model.
def train_digitization_model(data_folder, model_folder, verbose):
# Find data files.
if verbose:
print('Training the digitization model...')
print('Finding the Challenge data...')
records = find_records(data_folder)
num_records = len(records)
if num_records == 0:
raise FileNotFoundError('No data was provided.')
# Create a folder for the model if it does not already exist.
os.makedirs(model_folder, exist_ok=True)
# Extract the features and labels.
if verbose:
print('Extracting features and labels from the data...')
features = list()
for i in range(num_records):
if verbose:
width = len(str(num_records))
print(f'- {i+1:>{width}}/{num_records}: {records[i]}...')
record = os.path.join(data_folder, records[i])
# Extract the features from the image...
current_features = extract_features(record)
features.append(current_features)
# Train the model.
if verbose:
print('Training the model on the data...')
# This overly simple model uses the mean of these overly simple features as a seed for a random number generator.
model = np.mean(features)
# Save the model.
save_digitization_model(model_folder, model)
if verbose:
print('Done.')
print()
# Train your dx model.
def train_dx_model(data_folder, model_folder, verbose):
# Find data files.
if verbose:
print('Training the dx classification model...')
print('Finding the Challenge data...')
records = find_records(data_folder)
num_records = len(records)
if num_records == 0:
raise FileNotFoundError('No data was provided.')
# Create a folder for the model if it does not already exist.
os.makedirs(model_folder, exist_ok=True)
# Extract the features and labels.
if verbose:
print('Extracting features and labels from the data...')
features = list()
dxs = list()
for i in range(num_records):
if verbose:
width = len(str(num_records))
print(f'- {i+1:>{width}}/{num_records}: {records[i]}...')
record = os.path.join(data_folder, records[i])
# Extract the features from the image, but only if the image has one or more dx classes.
dx = load_dx(record)
if dx:
current_features = extract_features(record)
features.append(current_features)
dxs.append(dx)
if not dxs:
raise Exception('There are no labels for the data.')
features = np.vstack(features)
classes = sorted(set.union(*map(set, dxs)))
dxs = compute_one_hot_encoding(dxs, classes)
# Train the model.
if verbose:
print('Training the model on the data...')
# Define parameters for random forest classifier and regressor.
n_estimators = 12 # Number of trees in the forest.
max_leaf_nodes = 34 # Maximum number of leaf nodes in each tree.
random_state = 56 # Random state; set for reproducibility.
# Fit the model.
model = RandomForestClassifier(
n_estimators=n_estimators, max_leaf_nodes=max_leaf_nodes, random_state=random_state).fit(features, dxs)
# Save the model.
save_dx_model(model_folder, model, classes)
if verbose:
print('Done.')
print()
# Load your trained digitization model. This function is *required*. You should edit this function to add your code, but do *not*
# change the arguments of this function. If you do not train a digitization model, then you can return None.
def load_digitization_model(model_folder, verbose):
filename = os.path.join(model_folder, 'digitization_model.sav')
return joblib.load(filename)
# Load your trained dx classification model. This function is *required*. You should edit this function to add your code, but do
# *not* change the arguments of this function. If you do not train a dx classification model, then you can return None.
def load_dx_model(model_folder, verbose):
filename = os.path.join(model_folder, 'dx_model.sav')
return joblib.load(filename)
# Run your trained digitization model. This function is *required*. You should edit this function to add your code, but do *not*
# change the arguments of this function.
def run_digitization_model(digitization_model, record, verbose):
model = digitization_model['model']
# Extract features.
features = extract_features(record)
# Load the dimensions of the signal.
header_file = get_header_file(record)
header = load_text(header_file)
num_samples = get_num_samples(header)
num_signals = get_num_signals(header)
# For a overly simply minimal working example, generate "random" waveforms.
seed = int(round(model + np.mean(features)))
signal = np.random.default_rng(seed=seed).uniform(low=-1000, high=1000, size=(num_samples, num_signals))
signal = np.asarray(signal, dtype=np.int16)
return signal
# Run your trained dx classification model. This function is *required*. You should edit this function to add your code, but do
# *not* change the arguments of this function.
def run_dx_model(dx_model, record, signal, verbose):
model = dx_model['model']
classes = dx_model['classes']
# Extract features.
features = extract_features(record)
features = features.reshape(1, -1)
# Get model probabilities.
probabilities = model.predict_proba(features)
probabilities = np.asarray(probabilities, dtype=np.float32)[:, 0, 1]
# Choose the class(es) with the highest probability as the label(s).
max_probability = np.nanmax(probabilities)
labels = [classes[i] for i, probability in enumerate(probabilities) if probability == max_probability]
return labels
################################################################################
#
# Optional functions. You can change or remove these functions and/or add new functions.
#
################################################################################
# Extract features.
def extract_features(record):
images = load_image(record)
mean = 0.0
std = 0.0
for image in images:
image = np.asarray(image)
mean += np.mean(image)
std += np.std(image)
return np.array([mean, std])
# Save your trained digitization model.
def save_digitization_model(model_folder, model):
d = {'model': model}
filename = os.path.join(model_folder, 'digitization_model.sav')
joblib.dump(d, filename, protocol=0)
# Save your trained dx classification model.
def save_dx_model(model_folder, model, classes):
d = {'model': model, 'classes': classes}
filename = os.path.join(model_folder, 'dx_model.sav')
joblib.dump(d, filename, protocol=0)