1
|
|
|
#import required python modules |
2
|
|
|
import numpy as np |
3
|
|
|
from numpy import genfromtxt |
4
|
|
|
import pandas as pd |
5
|
|
|
import matplotlib.pyplot as plt |
6
|
|
|
from os import listdir |
7
|
|
|
import os.path |
8
|
|
|
import urllib.request |
9
|
|
|
import zipfile |
10
|
|
|
import keras |
11
|
|
|
from keras.utils.np_utils import to_categorical |
12
|
|
|
|
13
|
|
|
def split_activities(labels, X, borders=10*100): |
|
|
|
|
14
|
|
|
""" |
15
|
|
|
Splits up the data per activity and exclude activity=0. |
16
|
|
|
Also remove borders for each activity. |
17
|
|
|
Returns lists with subdatasets |
18
|
|
|
""" |
19
|
|
|
tot_len = len(labels) |
20
|
|
|
startpoints = np.where([1] + [labels[i]!=labels[i-1] for i in range(1, tot_len)])[0] |
|
|
|
|
21
|
|
|
endpoints = np.append(startpoints[1:]-1, tot_len-1) |
22
|
|
|
acts = [labels[s] for s,e in zip(startpoints, endpoints)] |
|
|
|
|
23
|
|
|
#Also split up the data, and only keep the non-zero activities |
24
|
|
|
Xysplit = [(X[s+borders:e-borders+1,:], a) for s,e,a in zip(startpoints, endpoints, acts) if a != 0] |
|
|
|
|
25
|
|
|
Xysplit = [(X, y) for X,y in Xysplit if len(X)>0] |
|
|
|
|
26
|
|
|
Xlist = [X for X,y in Xysplit] |
|
|
|
|
27
|
|
|
ylist = [y for X,y in Xysplit] |
|
|
|
|
28
|
|
|
return Xlist, ylist |
29
|
|
|
|
30
|
|
|
def sliding_window(frame_length, step, Xsamples, ysamples,ysampleslist,Xsampleslist): |
|
|
|
|
31
|
|
|
""" |
32
|
|
|
Splits time series in ysampleslist and Xsampleslist |
33
|
|
|
into segments by applying a sliding overlapping window |
34
|
|
|
of size equal to frame_length with steps equal to step |
35
|
|
|
it does this for all the samples and appends all the output together. |
36
|
|
|
So, the participant distinction is not kept |
37
|
|
|
""" |
38
|
|
|
for j in range(len(Xsampleslist)): |
39
|
|
|
X = Xsampleslist[j] |
|
|
|
|
40
|
|
|
ybinary = ysampleslist[j] |
41
|
|
|
for i in range(0, X.shape[0]-frame_length, step): |
42
|
|
|
Xsub = X[i:i+frame_length,:] |
|
|
|
|
43
|
|
|
ysub = ybinary |
44
|
|
|
Xsamples.append(Xsub) |
45
|
|
|
ysamples.append(ysub) |
46
|
|
|
|
47
|
|
|
def transform_y(y,mapclasses,nr_classes): |
|
|
|
|
48
|
|
|
""" |
49
|
|
|
Transforms y, a tuple with sequences of class per time segment per sample, |
50
|
|
|
into a binary matrix per sample |
51
|
|
|
""" |
52
|
|
|
ymapped = np.array([mapclasses[c] for c in y], dtype='int') |
53
|
|
|
ybinary = to_categorical(ymapped, nr_classes) |
54
|
|
|
return ybinary |
55
|
|
|
|
56
|
|
|
def addheader(datasets): |
57
|
|
|
""" |
58
|
|
|
The columns of the pandas data frame are numbers |
59
|
|
|
this function adds the column labels |
60
|
|
|
""" |
61
|
|
|
axes = ['x', 'y', 'z'] |
62
|
|
|
IMUsensor_columns = ['temperature'] + \ |
|
|
|
|
63
|
|
|
['acc_16g_' + i for i in axes] + \ |
64
|
|
|
['acc_6g_' + i for i in axes] + \ |
65
|
|
|
['gyroscope_'+ i for i in axes] + \ |
66
|
|
|
['magnometer_'+ i for i in axes] + \ |
67
|
|
|
['orientation_' + str(i) for i in range(4)] |
68
|
|
|
header = ["timestamp", "activityID", "heartrate"] + ["hand_"+s for s in IMUsensor_columns]\ |
|
|
|
|
69
|
|
|
+ ["chest_"+s for s in IMUsensor_columns]+ ["ankle_"+s for s in IMUsensor_columns] |
|
|
|
|
70
|
|
|
for i in range(0,len(datasets)): |
|
|
|
|
71
|
|
|
datasets[i].columns = header |
|
|
|
|
72
|
|
|
return datasets |
73
|
|
|
|
74
|
|
|
def split_dataset(datasets_filled,Xlists,ybinarylists): |
|
|
|
|
75
|
|
|
""" |
76
|
|
|
This function split Xlists and ybinarylists into |
77
|
|
|
a train, test and val subset |
78
|
|
|
""" |
79
|
|
|
train_range = slice(0, 6) |
80
|
|
|
val_range = 6 |
81
|
|
|
test_range = slice(7,len(datasets_filled)) |
|
|
|
|
82
|
|
|
Xtrainlist = [X for Xlist in Xlists[train_range] for X in Xlist] |
|
|
|
|
83
|
|
|
Xvallist = [X for X in Xlists[val_range]] |
|
|
|
|
84
|
|
|
Xtestlist = [X for Xlist in Xlists[test_range] for X in Xlist] |
|
|
|
|
85
|
|
|
ytrainlist = [y for ylist in ybinarylists[train_range] for y in ylist] |
86
|
|
|
yvallist = [y for y in ybinarylists[val_range]] |
87
|
|
|
ytestlist = [y for ylist in ybinarylists[test_range] for y in ylist] |
88
|
|
|
return Xtrainlist, Xvallist, Xtestlist, ytrainlist, yvallist, ytestlist |
89
|
|
|
|
90
|
|
|
def numpify_and_store(x,y,Xname,yname,outdatapath,shuffle=False): |
|
|
|
|
91
|
|
|
""" |
92
|
|
|
Converts python lists x and y into numpy arrays |
93
|
|
|
and stores the numpy array in directory outdatapath |
94
|
|
|
shuffle is optional and shuffles the samples |
95
|
|
|
""" |
96
|
|
|
x = np.array(x) |
97
|
|
|
y = np.array(y) |
98
|
|
|
#Shuffle around the train set |
99
|
|
|
if shuffle is True: |
100
|
|
|
np.random.seed(123) |
101
|
|
|
neworder = np.random.permutation(x.shape[0]) |
102
|
|
|
x = x[neworder,:,:] |
|
|
|
|
103
|
|
|
y = y[neworder,:] |
|
|
|
|
104
|
|
|
# Save binary file |
105
|
|
|
np.save(outdatapath+ Xname, x) |
106
|
|
|
np.save(outdatapath+ yname, y) |
107
|
|
|
|
108
|
|
|
|
109
|
|
|
def fetch_data(directory_to_extract_to): |
110
|
|
|
""" |
111
|
|
|
Fetch the data and extract the contents of the zip file |
112
|
|
|
to the directory_to_extract_to. |
113
|
|
|
First check whether this was done before, if yes, then skip |
114
|
|
|
""" |
115
|
|
|
targetdir = directory_to_extract_to + '/PAMAP2' |
116
|
|
|
if os.path.exists(targetdir): |
117
|
|
|
print('Data previously downloaded and stored in ' + targetdir) |
118
|
|
|
else: |
119
|
|
|
os.makedirs(targetdir) # create target directory |
120
|
|
|
#download the PAMAP2 data, this is 688 Mb |
121
|
|
|
path_to_zip_file = directory_to_extract_to + '/PAMAP2_Dataset.zip' |
122
|
|
|
test_file_exist = os.path.isfile(path_to_zip_file) |
123
|
|
|
if test_file_exist is False: |
124
|
|
|
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00231/PAMAP2_Dataset.zip' |
|
|
|
|
125
|
|
|
#retrieve data from url |
126
|
|
|
local_fn, headers = urllib.request.urlretrieve(url,filename=path_to_zip_file) |
|
|
|
|
127
|
|
|
print('Download complete and stored in: ' + path_to_zip_file ) |
|
|
|
|
128
|
|
|
else: |
129
|
|
|
print('The data was previously downloaded and stored in ' + path_to_zip_file ) |
|
|
|
|
130
|
|
|
# unzip |
131
|
|
|
with zipfile.ZipFile(path_to_zip_file ,"r") as zip_ref: |
|
|
|
|
132
|
|
|
zip_ref.extractall(targetdir) |
133
|
|
|
return targetdir |
134
|
|
|
|
135
|
|
|
|
136
|
|
|
def fetch_and_preprocess(directory_to_extract_to, columns_to_use = None): |
|
|
|
|
137
|
|
|
""" |
138
|
|
|
High level function to fetch_and_preprocess the PAMAP2 dataset |
139
|
|
|
directory_to_extract_to: the directory where the data will be stored |
140
|
|
|
columns_to_use: the columns to use |
141
|
|
|
""" |
142
|
|
|
if columns_to_use is None: |
143
|
|
|
columns_to_use = ['hand_acc_16g_x', 'hand_acc_16g_y', 'hand_acc_16g_z', |
144
|
|
|
'ankle_acc_16g_x', 'ankle_acc_16g_y', 'ankle_acc_16g_z', |
145
|
|
|
'chest_acc_16g_x', 'chest_acc_16g_y', 'chest_acc_16g_z'] |
146
|
|
|
targetdir = fetch_data(directory_to_extract_to) |
147
|
|
|
outdatapath = targetdir + '/PAMAP2_Dataset' + '/slidingwindow512cleaned/' |
148
|
|
|
if not os.path.exists(outdatapath): |
149
|
|
|
os.makedirs(outdatapath) |
150
|
|
|
if os.path.isfile(outdatapath+'X_train.npy'): |
151
|
|
|
print('Data previously pre-processed and np-files saved to ' + outdatapath) |
|
|
|
|
152
|
|
|
else: |
153
|
|
|
datadir = targetdir + '/PAMAP2_Dataset/Protocol' |
154
|
|
|
filenames = listdir(datadir) |
155
|
|
|
print('Start pre-processing all ' + str(len(filenames)) + ' files...') |
156
|
|
|
# load the files and put them in a list of pandas dataframes: |
157
|
|
|
datasets = [pd.read_csv(datadir+'/'+fn, header=None, sep=' ') for fn in filenames] |
|
|
|
|
158
|
|
|
datasets = addheader(datasets) # add headers to the datasets |
159
|
|
|
#Interpolate dataset to get same sample rate between channels |
160
|
|
|
datasets_filled = [d.interpolate() for d in datasets] |
161
|
|
|
# Create mapping for class labels |
162
|
|
|
ysetall = [set(np.array(data.activityID)) - set([0]) for data in datasets_filled] |
|
|
|
|
163
|
|
|
classlabels = list(set.union(*[set(y) for y in ysetall])) |
164
|
|
|
nr_classes = len(classlabels) |
165
|
|
|
mapclasses = {classlabels[i] : i for i in range(len(classlabels))} |
166
|
|
|
#Create input (X) and output (y) sets |
167
|
|
|
Xall = [np.array(data[columns_to_use]) for data in datasets_filled] |
|
|
|
|
168
|
|
|
yall = [np.array(data.activityID) for data in datasets_filled] |
169
|
|
|
Xylists = [split_activities(y, X) for X, y in zip(Xall, yall)] |
|
|
|
|
170
|
|
|
Xlists, ylists = zip(*Xylists) |
|
|
|
|
171
|
|
|
ybinarylists = [transform_y(y, mapclasses, nr_classes) for y in ylists] |
172
|
|
|
# Split in train, test and val |
173
|
|
|
Xtrainlist, Xvallist, Xtestlist, ytrainlist, yvallist, ytestlist = split_dataset(datasets_filled, Xlists, ybinarylists) |
|
|
|
|
174
|
|
|
# Take sliding-window frames. Target is label of last time step |
175
|
|
|
# Data is 100 Hz |
176
|
|
|
frame_length = int(5.12 * 100) |
177
|
|
|
step = 1 * 100 |
178
|
|
|
Xtrain = [] |
|
|
|
|
179
|
|
|
ytrain = [] |
180
|
|
|
Xval = [] |
|
|
|
|
181
|
|
|
yval = [] |
182
|
|
|
Xtest = [] |
|
|
|
|
183
|
|
|
ytest = [] |
184
|
|
|
sliding_window(frame_length, step, Xtrain, ytrain, ytrainlist, Xtrainlist) |
|
|
|
|
185
|
|
|
sliding_window(frame_length, step, Xval, yval, yvallist, Xvallist) |
186
|
|
|
sliding_window(frame_length, step, Xtest, ytest, ytestlist, Xtestlist) |
187
|
|
|
numpify_and_store(Xtrain, ytrain, 'X_train', 'y_train', outdatapath, shuffle=True) |
|
|
|
|
188
|
|
|
numpify_and_store(Xval, yval, 'X_val', 'y_val', outdatapath, shuffle=True) |
|
|
|
|
189
|
|
|
numpify_and_store(Xtest, ytest, 'X_test', 'y_test', outdatapath, shuffle=True) |
|
|
|
|
190
|
|
|
print('Processed data succesfully stored in ' + outdatapath) |
191
|
|
|
return outdatapath |
192
|
|
|
|
193
|
|
|
def load_data(outputpath): |
194
|
|
|
ext = '.npy' |
195
|
|
|
Xtrain = np.load(outputpath+'X_train'+ext) |
|
|
|
|
196
|
|
|
ytrain_binary = np.load(outputpath+'y_train_binary'+ext) |
197
|
|
|
Xval = np.load(outputpath+'X_val'+ext) |
|
|
|
|
198
|
|
|
yval_binary = np.load(outputpath+'y_val_binary'+ext) |
199
|
|
|
Xtest = np.load(outputpath+'X_test'+ext) |
|
|
|
|
200
|
|
|
ytest_binary = np.load(outputpath+'y_test_binary'+ext) |
201
|
|
|
return Xtrain, ytrain_binary, Xval, yval_binary, X_test, ytest_binary |
202
|
|
|
|
This check looks for invalid names for a range of different identifiers.
You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.
If your project includes a Pylint configuration file, the settings contained in that file take precedence.
To find out more about Pylint, please refer to their site.