-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomForestManager.cpp
370 lines (299 loc) · 11.7 KB
/
RandomForestManager.cpp
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
//
// RandomForestManager
// Ride
//
// Created by William Henderson on 12/4/15.
// Copyright © 2015 Knock Softwae, Inc. All rights reserved.
//
#include "RandomForestManager.h"
#include "FFTManager.h"
#ifdef __ANDROID__
#include <android/log.h>
#define DEBUG(str) __android_log_print(ANDROID_LOG_VERBOSE, "RandomForestManager", (str))
#else
#include <iostream>
#define DEBUG(str) (cerr << "RandomForestManager DEBUG: " << str << endl)
#endif
#include <algorithm>
#include <numeric>
#include <opencv2/core/core.hpp>
#include <opencv2/ml/ml.hpp>
#include <vector>
#include <cmath>
#include <fstream>
#include "json/json.h"
#include "Utility.h"
#ifdef __APPLE__
#define FFT_TYPE_NUMBER 0
#else
#define FFT_TYPE_NUMBER 1
#endif
using namespace cv;
using namespace std;
struct RandomForestConfiguration {
int sampleCount;
float samplingRateHz;
string modelUID;
};
struct RandomForestManager {
string modelPath;
string modelUID;
int sampleCount;
float samplingRateHz;
int fftIndex_below2_5hz;
int fftIndex_above2hz;
int fftIndex_above3_5hz;
FFTManager *fftManager;
vector<float> differences;
cv::Ptr<cv::ml::RTrees> model;
};
bool loadConfigurationFromString(RandomForestConfiguration* config, const char* jsonString);
bool loadConfigurationFromJsonFile(RandomForestConfiguration* config, const char* pathToJson);
void loadJson(char* pathToJson);
RandomForestManager *createRandomForestManagerFromConfiguration(RandomForestConfiguration* config) {
RandomForestManager *r = new RandomForestManager;
r->sampleCount = config->sampleCount;
r->samplingRateHz = config->samplingRateHz;
r->modelUID = config->modelUID;
r->fftManager = createFFTManager(r->sampleCount);
float sampleSpacing = 1. / r->samplingRateHz;
r->fftIndex_below2_5hz = floorf(sampleSpacing * r->sampleCount * 2.5);
r->fftIndex_above2hz = ceilf(sampleSpacing * r->sampleCount * 2.0);
r->fftIndex_above3_5hz = ceilf(sampleSpacing * r->sampleCount * 3.5);
r->differences = vector<float>(r->sampleCount);
return r;
}
RandomForestManager *createRandomForestManagerFromJsonString(const char* jsonString) {
RandomForestConfiguration config;
if (loadConfigurationFromString(&config, jsonString)) {
return createRandomForestManagerFromConfiguration(&config);
}
else {
return NULL;
}
}
RandomForestManager *createRandomForestManagerFromFile(const char* pathToJson)
{
RandomForestConfiguration config;
if (loadConfigurationFromJsonFile(&config, pathToJson)) {
return createRandomForestManagerFromConfiguration(&config);
}
else {
return NULL;
}
}
bool randomForestLoadModel(RandomForestManager *r, const char* pathToModelFile) {
if (pathToModelFile == NULL) {
return false;
}
r->modelPath = string(pathToModelFile);
r->model = cv::ml::RTrees::load<cv::ml::RTrees>(r->modelPath);
return true;
}
/**
* Maximum spacing between accelerometer readings, in seconds
*/
float randomForestGetDesiredSamplingInterval(RandomForestManager *r) {
return 1. / r->samplingRateHz;
}
/**
* Minimum length of continuous readings, in seconds
*/
float randomForestGetDesiredSessionDuration(RandomForestManager *r) {
// Desired duration is the difference between the time of the first
// and the time of the last
return (r->sampleCount - 1) / r->samplingRateHz;
}
const char* randomForestGetModelUniqueIdentifier(RandomForestManager *r) {
return r->modelUID.c_str();
}
bool randomForestManagerCanPredict(RandomForestManager *r) {
if (r->model.empty()) {
DEBUG("model is not loaded");
return false;
}
if (r->model->getVarCount() != RANDOM_FOREST_VECTOR_SIZE) {
DEBUG("var count does not match");
return false;
}
return true;
}
void deleteRandomForestManager(RandomForestManager *r)
{
if (r != NULL) {
deleteFFTManager(r->fftManager);
if (!r->model.empty()) {
r->model.release();
}
free(r);
}
}
void calculateFeaturesFromNorms(RandomForestManager *randomForestManager, float* features, float* accelerometerVector) {
LOCAL_TIMING_START();
cv::Mat mags = cv::Mat(randomForestManager->sampleCount, 1, CV_32F, accelerometerVector);
cv::Scalar meanMag,stddevMag;
meanStdDev(mags,meanMag,stddevMag);
float *fftOutput = new float[randomForestManager->sampleCount];
fft(randomForestManager->fftManager, accelerometerVector, randomForestManager->sampleCount, fftOutput);
float maxPower = dominantPower(fftOutput, randomForestManager->sampleCount);
int spectrumLength = randomForestManager->sampleCount / 2; // exclude nyquist frequency
vector<float> spectrum (fftOutput, fftOutput + spectrumLength);
float fftIntegral = trapezoidArea(spectrum.begin() + 1, spectrum.end()); // exclude DC / 0Hz power
float fftIntegralBelow2_5hz = trapezoidArea(
spectrum.begin() + 1, // exclude DC
spectrum.begin() + randomForestManager->fftIndex_below2_5hz + 1); // include 2.5Hz component
features[0] = max(mags);
features[1] = (float)meanMag.val[0];
features[2] = maxMean(mags, 5);
features[3] = (float)stddevMag.val[0];
features[4] = (float)skewness(mags);
features[5] = (float)kurtosis(mags);
features[6] = maxPower;
features[7] = fftIntegral;
features[8] = fftIntegralBelow2_5hz;
features[9] = percentile(accelerometerVector, randomForestManager->sampleCount, 0.25);
features[10] = percentile(accelerometerVector, randomForestManager->sampleCount, 0.5);
features[11] = percentile(accelerometerVector, randomForestManager->sampleCount, 0.75);
features[12] = percentile(accelerometerVector, randomForestManager->sampleCount, 0.9);
LOCAL_TIMING_FINISH("calculateFeaturesFromNorms");
}
void randomForestClassifyFeatures(RandomForestManager *randomForestManager, float* features, float* confidences, int n_classes) {
cv::Mat featuresMat = cv::Mat(1, RANDOM_FOREST_VECTOR_SIZE, CV_32F, (void*) features);
if (randomForestManager->model.empty()) {
return;
}
cv::Mat results;
LOCAL_TIMING_START();
randomForestManager->model->predictProb(featuresMat, results, cv::ml::DTrees::PREDICT_CONFIDENCE);
LOCAL_TIMING_FINISH("predictProb");
for (int i = 0; i < n_classes; ++i) {
confidences[i] = results.at<float>(i);
}
}
bool readingIsLess(AccelerometerReading a, AccelerometerReading b) {
return ((a.t) < (b.t));
}
bool prepareNormsAndSeconds(AccelerometerReading* readings, float* norms, float* seconds, int readingCount) {
LOCAL_TIMING_START();
auto readingVector = std::vector<AccelerometerReading>(readings, readings + readingCount);
std::sort(readings, readings + readingCount, readingIsLess);
if (readingCount < 1) {
return false;
}
float* norm;
float* second;
AccelerometerReading* reading;
int i;
double firstReadingT = readings[0].t;
for (second = seconds, norm = norms, reading = readings, i = 0; i < readingCount; ++i, ++reading, ++norm, ++second) {
*norm = sqrt(
(reading->x * reading->x) +
(reading->y * reading->y) +
(reading->z * reading->z));
*second = (float)(reading->t - firstReadingT);
}
LOCAL_TIMING_FINISH("prepareNormsAndSeconds");
return true;
}
bool randomForestClassifyAccelerometerSignal(RandomForestManager *randomForestManager, AccelerometerReading* readings, int readingCount, float* confidences, int n_classes) {
float* features = new float[RANDOM_FOREST_VECTOR_SIZE];
bool successful = randomForestPrepareFeaturesFromAccelerometerSignal(randomForestManager, readings, readingCount, features, RANDOM_FOREST_VECTOR_SIZE, 0.f);
if (successful) {
randomForestClassifyFeatures(randomForestManager, features, confidences, n_classes);
}
delete[] features;
return successful;
}
bool randomForestPrepareFeaturesFromAccelerometerSignal(RandomForestManager *randomForestManager,
AccelerometerReading* readings, int readingCount,
float* features, int feature_count, float offsetSeconds) {
if (feature_count < RANDOM_FOREST_VECTOR_SIZE) {
return false;
}
float* norms = new float[readingCount];
float* seconds = new float[readingCount];
bool successful = false;
if (prepareNormsAndSeconds(readings, norms, seconds, readingCount)) {
float* resampledNorms = new float[randomForestManager->sampleCount];
float newSpacing = 1.f / ((float)randomForestManager->samplingRateHz);
successful = interpolateSplineRegular(seconds, norms, readingCount, resampledNorms, randomForestManager->sampleCount, newSpacing, offsetSeconds);
if (successful) {
calculateFeaturesFromNorms(randomForestManager, features, resampledNorms);
}
delete[] resampledNorms;
}
delete[] norms;
delete[] seconds;
return successful;
}
int randomForestGetClassLabels(RandomForestManager *randomForestManager, int *labels, int n_classes) {
if (randomForestManager->model.empty()) {
return 0;
}
Mat labelsMat = randomForestManager->model->getClassLabels();
for (int i = 0; i < n_classes && i < labelsMat.rows; ++i) {
labels[i] = labelsMat.at<int>(i);
}
return labelsMat.rows;
}
int randomForestGetClassCount(RandomForestManager *randomForestManager) {
if (randomForestManager->model.empty()) {
return 0;
}
Mat labelsMat = randomForestManager->model->getClassLabels();
return labelsMat.rows;
}
void loadConfigurationFromJsonValue(RandomForestConfiguration* config, Json::Value root) {
if (root["model_metadata_version"].asInt() > 1) {
throw std::runtime_error("Unsupported value for model_metadata_version");
}
Json::Value sampleCount = root["sampling"]["sample_count"];
if (sampleCount.isNull() || !sampleCount.isInt()) {
throw std::runtime_error("Unacceptable sample_count");
}
config->sampleCount = sampleCount.asInt();
if (fmod(log(config->sampleCount)/log(2), 1.0) != 0.0) {
throw std::runtime_error("sampleCount must be a power of 2");
}
Json::Value samplingRateHz = root["sampling"]["sampling_rate_hz"];
if (samplingRateHz.isNull() || !samplingRateHz.isNumeric()) {
throw std::runtime_error("Unsupported sampling_rate_hz");
}
config->samplingRateHz = samplingRateHz.asFloat();
// This field is optional in the case where we are training a new model; returns empty string if not present
config->modelUID = root["cv_sha256"].asString();
}
bool loadConfigurationFromString(RandomForestConfiguration* config, const char* jsonString) {
stringstream ss(jsonString);
Json::Value root;
ss >> root;
try {
loadConfigurationFromJsonValue(config, root);
}
catch (std::runtime_error& e) {
cerr << "ActivityPredictor/Utility.cpp:" << __LINE__ << ": Failed to load configuration: " << e.what() << endl;
return false;
}
catch (std::exception& e) {
cerr << "ActivityPredictor/Utility.cpp:" << __LINE__ << ": Failed to load configuration: " << e.what() << endl;
return false;
}
return true;
}
bool loadConfigurationFromJsonFile(RandomForestConfiguration* config, const char* pathToJson) {
try {
ifstream doc(pathToJson, ifstream::binary);
Json::Value root;
doc >> root;
loadConfigurationFromJsonValue(config, root);
}
catch (std::runtime_error& e) {
cerr << "ActivityPredictor/Utility.cpp:" << __LINE__ << ": Failed to load configuration: " << e.what() << endl;
return false;
}
catch (std::exception& e) {
cerr << "ActivityPredictor/Utility.cpp:" << __LINE__ << ": Failed to load configuration: " << e.what() << endl;
return false;
}
return true;
}