-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmotor_activity_detection.py
192 lines (150 loc) · 5.41 KB
/
motor_activity_detection.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
# -*- coding: utf-8 -*-
"""Motor Activity Detection.ipynb
Automatically generated by Colaboratory.
"""
# Commented out IPython magic to ensure Python compatibility.
# %tensorflow_version 2.x
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout
from tensorflow.keras.models import Sequential
from sklearn.model_selection import train_test_split
from scipy import stats
datasets_config = [
('output_label_idle.txt', 'idle'),
('output_label_idle_2.txt', 'idle'),
('output_label_working.txt', 'working'),
('output_label_working_2.txt', 'working')
]
column_names = ['ax', 'ay', 'az']
def load_dataset(config):
dataframes = []
for filename, label in config:
dataframe = pd.read_csv(filename, names=column_names)
dataframe['label'] = label
dataframes.append(dataframe)
return pd.concat(dataframes)
dataset = load_dataset(datasets_config)
for label in np.unique(dataset['label']):
print("{}: {}".format(label, len(dataset[dataset['label'] == label])))
def plot_axis(axis, data, title):
axis.plot(data)
axis.set_title(title)
axis.xaxis.set_visible(False)
axis.set_ylim([min(data)-np.std(data),max(data)+np.std(data)])
axis.grid(True)
def plot_activity(activity, data):
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(15,10),sharex=True)
plot_axis(ax0, data["ax"], "X Axis")
plot_axis(ax1, data["ay"], "Y Axis")
plot_axis(ax2, data["az"], "Z Axis")
plt.subplots_adjust(hspace=0.2)
fig.suptitle(activity)
plt.subplots_adjust(top=0.9)
plt.show()
for activity in np.unique(dataset['label']):
subset = dataset[dataset['label'] == activity][:100]
plot_activity(activity, subset)
def windows(data, size):
start = 0
while start < len(data):
yield int(start), int(start + size)
start += size
def segment_signals(data, window_size = 100):
data_per_class = []
for label in np.unique(data['label']):
subset = data[data['label'] == label]
length = len(subset)
remaining = length % window_size
max_length = length - remaining
data_per_class.append(subset[:max_length])
trimmed_data = pd.concat(data_per_class)
result = []
labels = []
for (start, end) in windows(trimmed_data, window_size):
row = []
x_axes = data['ax'][start:end] / 1000.0
y_axes = data['ay'][start:end] / 1000.0
z_axes = data['az'][start:end] / 1000.0
for x, y, z in zip(x_axes, y_axes, z_axes):
row.append(x)
row.append(y)
row.append(z)
row = np.array(row)
row = row.reshape((100, 3))
label = stats.mode(trimmed_data['label'][start:end])[0][0]
result.append(row)
labels.append(label)
return np.array(result), np.array(labels)
segments, labels = segment_signals(dataset, 100)
segments.shape
labels = np.asarray(pd.get_dummies(labels), dtype=np.int8)
n_rows = segments.shape[1]
n_cols = segments.shape[2]
n_channels = 1
n_filters = 16
kernel_size = 2
pooling_window_size = 2
n_fc_layer= 16
train_split_ratio = 0.8
epochs = 100
batch_size = 10
n_class = labels.shape[1]
dropout_ratio = 0.1
reshaped_segments = segments.reshape(segments.shape[0], n_rows, n_cols, 1)
reshaped_segments.shape
train_split = np.random.rand(len(reshaped_segments)) < train_split_ratio
train_x = reshaped_segments[train_split]
test_x = reshaped_segments[~train_split]
train_x = np.nan_to_num(train_x)
test_x = np.nan_to_num(test_x)
train_y = labels[train_split]
test_y = labels[~train_split]
# train_x, test_x, train_y, test_y = train_test_split(reshaped_segments, labels, test_size=.3, random_state=611)
print("Train X shape:", train_x.shape)
print("Train Y shape:", train_y.shape)
def cnn_model():
model = Sequential()
model.add(Conv2D(n_filters, (kernel_size, kernel_size), input_shape=(n_rows, n_cols, 1), activation='relu', padding='same'))
model.add(MaxPooling2D((pooling_window_size, pooling_window_size)))
model.add(Dropout(dropout_ratio))
model.add(Flatten())
model.add(Dense(n_fc_layer, activation='relu'))
model.add(Dropout(dropout_ratio))
model.add(Dense(n_class, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=['accuracy'])
return model
model = cnn_model()
model.summary()
history = model.fit(train_x,
train_y,
epochs=epochs,
validation_split=1-train_split_ratio,
batch_size=batch_size)
print(history.history.keys())
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
score = model.evaluate(test_x, test_y)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model to disk
open("model.tflite", "wb").write(tflite_model)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
tflite_model = converter.convert()
# Save the model to disk
open("model_quantized.tflite", "wb").write(tflite_model)