|
a |
|
b/RNN_ECG.py |
|
|
1 |
import numpy |
|
|
2 |
import matplotlib.pyplot as plt |
|
|
3 |
import pandas |
|
|
4 |
import math |
|
|
5 |
from keras.models import Sequential |
|
|
6 |
from keras.layers import Dense, LSTM, Dropout |
|
|
7 |
from sklearn.preprocessing import MinMaxScaler |
|
|
8 |
from sklearn.metrics import mean_squared_error |
|
|
9 |
import pandas as pd |
|
|
10 |
import scipy.io as sio |
|
|
11 |
from os import listdir |
|
|
12 |
from os.path import isfile, join |
|
|
13 |
import numpy as np |
|
|
14 |
import keras |
|
|
15 |
from sklearn.metrics import accuracy_score |
|
|
16 |
|
|
|
17 |
number_of_classes = 4 |
|
|
18 |
|
|
|
19 |
def change(x): #Для получения чисел от 0 до 3 |
|
|
20 |
answer = np.zeros((np.shape(x)[0])) |
|
|
21 |
for i in range(np.shape(x)[0]): |
|
|
22 |
max_value = max(x[i, :]) |
|
|
23 |
max_index = list(x[i, :]).index(max_value) |
|
|
24 |
answer[i] = max_index |
|
|
25 |
return answer.astype(np.int) |
|
|
26 |
|
|
|
27 |
mypath = 'training2017/' |
|
|
28 |
onlyfiles = [f for f in listdir(mypath) if (isfile(join(mypath, f)) and f[0] == 'A')] |
|
|
29 |
bats = [f for f in onlyfiles if f[7] == 'm'] |
|
|
30 |
mats = [f for f in bats if (np.shape(sio.loadmat(mypath + f)['val'])[1] >= 9000)] |
|
|
31 |
check = np.shape(sio.loadmat(mypath + mats[0])['val'])[1] |
|
|
32 |
X = np.zeros((len(mats), check)) |
|
|
33 |
for i in range(len(mats)): |
|
|
34 |
X[i, :] = sio.loadmat(mypath + mats[i])['val'][0, :9000] |
|
|
35 |
|
|
|
36 |
target_train = np.zeros((len(mats), 1)) |
|
|
37 |
Train_data = pd.read_csv(mypath + 'REFERENCE.csv', sep=',', header=None, names=None) |
|
|
38 |
for i in range(len(mats)): |
|
|
39 |
if Train_data.loc[Train_data[0] == mats[i][:6], 1].values == 'N': |
|
|
40 |
target_train[i] = 0 |
|
|
41 |
elif Train_data.loc[Train_data[0] == mats[i][:6], 1].values == 'A': |
|
|
42 |
target_train[i] = 1 |
|
|
43 |
elif Train_data.loc[Train_data[0] == mats[i][:6], 1].values == 'O': |
|
|
44 |
target_train[i] = 2 |
|
|
45 |
else: |
|
|
46 |
target_train[i] = 3 |
|
|
47 |
|
|
|
48 |
Label_set = np.zeros((len(mats), number_of_classes)) |
|
|
49 |
for i in range(np.shape(target_train)[0]): |
|
|
50 |
dummy = np.zeros((number_of_classes)) |
|
|
51 |
dummy[int(target_train[i])] = 1 |
|
|
52 |
Label_set[i, :] = dummy |
|
|
53 |
|
|
|
54 |
# scaler = MinMaxScaler(feature_range=(0, 1)) |
|
|
55 |
# X = scaler.fit_transform(X) |
|
|
56 |
|
|
|
57 |
train_len = 0.9 |
|
|
58 |
X_train = X[:int(train_len*len(mats)), :] |
|
|
59 |
Y_train = Label_set[:int(train_len*len(mats)), :] |
|
|
60 |
X_val = X[int(train_len*len(mats)):, :] |
|
|
61 |
Y_val = Label_set[int(train_len*len(mats)):, :] |
|
|
62 |
|
|
|
63 |
# reshape input to be [samples, time steps, features] |
|
|
64 |
X_train = numpy.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1])) |
|
|
65 |
X_val = numpy.reshape(X_val, (X_val.shape[0], 1, X_val.shape[1])) |
|
|
66 |
|
|
|
67 |
# create and fit the LSTM network |
|
|
68 |
batch_size = 64 |
|
|
69 |
model = Sequential() |
|
|
70 |
model.add(LSTM(512, return_sequences=True, input_shape=(1, check))) |
|
|
71 |
#model.add(Dropout(0.25)) |
|
|
72 |
model.add(LSTM(256, return_sequences=True)) |
|
|
73 |
#model.add(Dropout(0.25)) |
|
|
74 |
model.add(LSTM(128, return_sequences=True)) |
|
|
75 |
#model.add(Dropout(0.25)) |
|
|
76 |
model.add(LSTM(64, return_sequences=True)) |
|
|
77 |
#model.add(Dropout(0.25)) |
|
|
78 |
model.add(LSTM(32)) |
|
|
79 |
model.add(Dense(number_of_classes, activation='softmax')) |
|
|
80 |
early_stopping = keras.callbacks.EarlyStopping(monitor='val_acc', min_delta=0, patience=50, verbose=1, mode='auto') |
|
|
81 |
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) |
|
|
82 |
model.fit(X_train, Y_train, epochs=250, batch_size=batch_size, validation_data=(X_val, Y_val), verbose=2, shuffle=False, callbacks=[early_stopping]) |
|
|
83 |
# model.save('Keras_models/my_model_' + str(i) + '_' + str(j) + '_' + str() + '.h5') |
|
|
84 |
predictions = model.predict(X_val) |
|
|
85 |
score = accuracy_score(change(Y_val), change(predictions)) |
|
|
86 |
print(score) |
|
|
87 |
# Data[i - starti, j - starti] = str(format(score, '.5f')) |
|
|
88 |
# Output = pd.DataFrame(Data) |
|
|
89 |
# name = str(batch_size) + '.csv' |
|
|
90 |
# Output.to_csv(path_or_buf='Keras_models/' + name, index=None, header=None) |