diff --git a/tensorflow/lite/micro/docs/new_platform_support.md b/tensorflow/lite/micro/docs/new_platform_support.md index 069a38a9e35..692d98ed036 100644 --- a/tensorflow/lite/micro/docs/new_platform_support.md +++ b/tensorflow/lite/micro/docs/new_platform_support.md @@ -45,7 +45,6 @@ only the sources that are necessary to build the code TFLM library. python3 tensorflow/lite/micro/tools/project_generation/create_tflm_tree.py \ -e hello_world \ -e micro_speech \ - -e magic_wand \ -e person_detection \ /tmp/tflm-tree ``` @@ -114,7 +113,7 @@ optimized kernel implementations (and associated third party dependencies). For example: ``` python3 tensorflow/lite/micro/tools/project_generation/create_tflm_tree.py \ - -e hello_world -e magic_wand -e micro_speech -e person_detection \ + -e hello_world -e micro_speech -e person_detection \ --makefile_options="TARGET=cortex_m_generic OPTIMIZED_KERNEL_DIR=cmsis_nn TARGET_ARCH=project_generation" \ /tmp/tflm-cmsis ``` diff --git a/tensorflow/lite/micro/examples/magic_wand/BUILD b/tensorflow/lite/micro/examples/magic_wand/BUILD deleted file mode 100644 index 238614c6196..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/BUILD +++ /dev/null @@ -1,171 +0,0 @@ -# Description: -# TensorFlow Lite for Microcontrollers "gesture recognition" example. -load("//tensorflow/lite/micro:build_def.bzl", "generate_cc_arrays") - -package( - default_visibility = ["//visibility:public"], - # Disabling layering_check because of http://b/177257332 - features = ["-layering_check"], - licenses = ["notice"], -) - -generate_cc_arrays( - name = "generated_magic_wand_model_cc", - src = "magic_wand.tflite", - out = "magic_wand_model_data.cc", -) - -generate_cc_arrays( - name = "generated_magic_wand_model_hdr", - src = "magic_wand.tflite", - out = "magic_wand_model_data.h", -) - -cc_library( - name = "magic_wand_model_data", - srcs = [ - ":generated_magic_wand_model_cc", - ], - hdrs = [ - ":generated_magic_wand_model_hdr", - ], -) - -cc_library( - name = "sample_feature_data", - srcs = [ - "ring_micro_features_data.cc", - "slope_micro_features_data.cc", - ], - hdrs = [ - "ring_micro_features_data.h", - "slope_micro_features_data.h", - ], -) - -cc_test( - name = "magic_wand_test", - srcs = [ - "magic_wand_test.cc", - ], - deps = [ - ":magic_wand_model_data", - ":sample_feature_data", - "//tensorflow/lite/micro:micro_framework", - "//tensorflow/lite/micro:micro_log", - "//tensorflow/lite/micro:op_resolvers", - "//tensorflow/lite/micro/testing:micro_test", - "//tensorflow/lite/schema:schema_fbs", - ], -) - -cc_library( - name = "constants", - hdrs = [ - "constants.h", - ], -) - -cc_library( - name = "accelerometer_handler", - srcs = [ - "accelerometer_handler.cc", - ], - hdrs = [ - "accelerometer_handler.h", - ], - deps = [ - "//tensorflow/lite/c:common", - ], -) - -cc_test( - name = "accelerometer_handler_test", - srcs = [ - "accelerometer_handler_test.cc", - ], - deps = [ - ":accelerometer_handler", - "//tensorflow/lite/c:common", - "//tensorflow/lite/micro:micro_framework", - "//tensorflow/lite/micro:op_resolvers", - "//tensorflow/lite/micro/testing:micro_test", - ], -) - -cc_library( - name = "gesture_predictor", - srcs = [ - "gesture_predictor.cc", - ], - hdrs = [ - "gesture_predictor.h", - ], - deps = [ - ":constants", - ], -) - -cc_test( - name = "gesture_predictor_test", - srcs = [ - "gesture_predictor_test.cc", - ], - deps = [ - ":constants", - ":gesture_predictor", - "//tensorflow/lite/micro:micro_framework", - "//tensorflow/lite/micro/testing:micro_test", - ], -) - -cc_library( - name = "output_handler", - srcs = [ - "output_handler.cc", - ], - hdrs = [ - "output_handler.h", - ], - deps = [ - "//tensorflow/lite/c:common", - "//tensorflow/lite/micro:micro_log", - ], -) - -cc_test( - name = "output_handler_test", - srcs = [ - "output_handler_test.cc", - ], - deps = [ - ":output_handler", - "//tensorflow/lite/c:common", - "//tensorflow/lite/micro:micro_framework", - "//tensorflow/lite/micro/testing:micro_test", - ], -) - -cc_binary( - name = "magic_wand", - srcs = [ - "main.cc", - "main_functions.cc", - "main_functions.h", - ], - copts = [ - "-Werror", - "-Wsign-compare", - ], - deps = [ - ":accelerometer_handler", - ":constants", - ":gesture_predictor", - ":magic_wand_model_data", - ":output_handler", - "//tensorflow/lite/micro:micro_framework", - "//tensorflow/lite/micro:op_resolvers", - "//tensorflow/lite/micro:system_setup", - "//tensorflow/lite/schema:schema_fbs", - ], -) diff --git a/tensorflow/lite/micro/examples/magic_wand/Makefile.inc b/tensorflow/lite/micro/examples/magic_wand/Makefile.inc deleted file mode 100644 index fc19bb4e3bc..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/Makefile.inc +++ /dev/null @@ -1,85 +0,0 @@ -ACCELEROMETER_HANDLER_TEST_SRCS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/accelerometer_handler_test.cc - -ACCELEROMETER_HANDLER_TEST_HDRS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h - -OUTPUT_HANDLER_TEST_SRCS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/output_handler.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/output_handler_test.cc - -OUTPUT_HANDLER_TEST_HDRS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/output_handler.h - -GESTURE_PREDICTOR_TEST_SRCS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/gesture_predictor.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/gesture_predictor_test.cc - -GESTURE_PREDICTOR_TEST_HDRS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/constants.h \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/gesture_predictor.h \ - -magic_wand_TEST_SRCS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/magic_wand_test.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.cc - -magic_wand_TEST_HDRS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.h \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.h - -magic_wand_SRCS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/main.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/main_functions.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/gesture_predictor.cc \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/output_handler.cc - -magic_wand_HDRS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/main_functions.h \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/constants.h \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/gesture_predictor.h \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/output_handler.h - -magic_wand_GENERATOR_INPUTS := \ -$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/magic_wand.tflite - -magic_wand_GENERATED_SRCS := \ -$(GENERATED_SRCS_DIR)$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/magic_wand_model_data.cc - -magic_wand_GENERATED_HDRS := \ -$(GENERATED_SRCS_DIR)$(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/magic_wand_model_data.h - -#Find any platform - specific rules for this example. -include $(wildcard $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/*/Makefile.inc) - -# Tests the accelerometer handler -$(eval $(call microlite_test,gesture_accelerometer_handler_test,\ -$(ACCELEROMETER_HANDLER_TEST_SRCS),$(ACCELEROMETER_HANDLER_TEST_HDRS))) - -# Tests the output handler -$(eval $(call microlite_test,gesture_output_handler_test,\ -$(OUTPUT_HANDLER_TEST_SRCS),$(OUTPUT_HANDLER_TEST_HDRS))) - -# Tests the gesture predictor -$(eval $(call microlite_test,gesture_predictor_test,\ -$(GESTURE_PREDICTOR_TEST_SRCS),$(GESTURE_PREDICTOR_TEST_HDRS))) - -# Tests loading and running the gesture recognition model -$(eval $(call microlite_test,magic_wand_test,\ -$(magic_wand_TEST_SRCS),$(magic_wand_TEST_HDRS),$(magic_wand_GENERATOR_INPUTS))) - -# Builds a standalone binary -$(eval $(call microlite_test,magic_wand,\ -$(magic_wand_SRCS),$(magic_wand_HDRS),$(magic_wand_GENERATOR_INPUTS))) - -magic_wand_SRCS += $(magic_wand_GENERATED_SRCS) -magic_wand_HDRS += $(magic_wand_GENERATED_HDRS) - -list_magic_wand_example_sources: - @echo $(magic_wand_SRCS) - -list_magic_wand_example_headers: - @echo $(magic_wand_HDRS) \ No newline at end of file diff --git a/tensorflow/lite/micro/examples/magic_wand/README.md b/tensorflow/lite/micro/examples/magic_wand/README.md deleted file mode 100644 index e8eb3d8fa41..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# Magic wand example - -This example shows how you can use TensorFlow Lite to run a 20 kilobyte neural -network model to recognize gestures with an accelerometer. - -## Table of contents - -- [Getting started](#getting-started) -- [Run the tests on a development machine](#run-the-tests-on-a-development-machine) -- [Train your own model](#train-your-own-model) - -To stop viewing the debug output with `screen`, hit `Ctrl+A`, immediately -followed by the `K` key, then hit the `Y` key. - -## Run the tests on a development machine - -```bash -make -f tensorflow/lite/micro/tools/make/Makefile test_magic_wand_test -``` - -This will take a few minutes, and downloads frameworks the code uses like -[flatbuffers](https://google.github.io/flatbuffers/). Once that process has -finished, you should see a series of files get compiled, followed by some -logging output from a test, which should conclude with `~~~ALL TESTS PASSED~~~`. - -If you see this, it means that a small program has been built and run that loads -the trained TensorFlow model, runs some example inputs through it, and got the -expected outputs. - -## Train your own model - -To train your own model, or create a new model for a new set of gestures, -follow the instructions in [magic_wand/train/README.md](train/README.md). diff --git a/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.cc b/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.cc deleted file mode 100644 index 8cb6045f908..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.cc +++ /dev/null @@ -1,35 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h" - -int begin_index = 0; - -TfLiteStatus SetupAccelerometer() { return kTfLiteOk; } - -bool ReadAccelerometer(float* input, int length) { - begin_index += 3; - // Reset begin_index to simulate behavior of loop buffer - if (begin_index >= 600) begin_index = 0; - // Only return true after the function was called 100 times, simulating the - // desired behavior of a real implementation (which does not return data until - // a sufficient amount is available) - if (begin_index > 300) { - for (int i = 0; i < length; ++i) input[i] = 0; - return true; - } else { - return false; - } -} diff --git a/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h b/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h deleted file mode 100644 index 726909291ba..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h +++ /dev/null @@ -1,27 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#ifndef TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_ACCELEROMETER_HANDLER_H_ -#define TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_ACCELEROMETER_HANDLER_H_ - -#define kChannelNumber 3 - -#include "tensorflow/lite/c/common.h" - -extern int begin_index; -extern TfLiteStatus SetupAccelerometer(); -extern bool ReadAccelerometer(float* input, int length); - -#endif // TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_ACCELEROMETER_HANDLER_H_ diff --git a/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler_test.cc b/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler_test.cc deleted file mode 100644 index 391cb5e5de9..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/accelerometer_handler_test.cc +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h" - -#include - -#include "tensorflow/lite/c/common.h" -#include "tensorflow/lite/micro/testing/micro_test.h" - -TF_LITE_MICRO_TESTS_BEGIN - -TF_LITE_MICRO_TEST(TestSetup) { - TfLiteStatus setup_status = SetupAccelerometer(); - TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, setup_status); -} - -TF_LITE_MICRO_TEST(TestAccelerometer) { - float input[384] = {0.0}; - // Test that the function returns false before insufficient data is available - bool inference_flag = ReadAccelerometer(input, 384); - TF_LITE_MICRO_EXPECT_EQ(inference_flag, false); - - // Test that the function returns true once sufficient data is available to - // fill the model's input buffer (128 sets of values) - for (int i = 1; i <= 128; i++) { - inference_flag = ReadAccelerometer(input, 384); - } - TF_LITE_MICRO_EXPECT_EQ(inference_flag, true); -} - -TF_LITE_MICRO_TESTS_END diff --git a/tensorflow/lite/micro/examples/magic_wand/constants.h b/tensorflow/lite/micro/examples/magic_wand/constants.h deleted file mode 100644 index 3f0da6c9a83..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/constants.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#ifndef TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_CONSTANTS_H_ -#define TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_CONSTANTS_H_ - -// The expected accelerometer data sample frequency -const float kTargetHz = 25; - -// What gestures are supported. -constexpr int kGestureCount = 4; -constexpr int kWingGesture = 0; -constexpr int kRingGesture = 1; -constexpr int kSlopeGesture = 2; -constexpr int kNoGesture = 3; - -// These control the sensitivity of the detection algorithm. If you're seeing -// too many false positives or not enough true positives, you can try tweaking -// these thresholds. Often, increasing the size of the training set will give -// more robust results though, so consider retraining if you are seeing poor -// predictions. -constexpr float kDetectionThreshold = 0.8f; -constexpr int kPredictionHistoryLength = 5; -constexpr int kPredictionSuppressionDuration = 25; - -#endif // TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_CONSTANTS_H_ diff --git a/tensorflow/lite/micro/examples/magic_wand/gesture_predictor.cc b/tensorflow/lite/micro/examples/magic_wand/gesture_predictor.cc deleted file mode 100644 index b09499a836d..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/gesture_predictor.cc +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/gesture_predictor.h" - -#include "tensorflow/lite/micro/examples/magic_wand/constants.h" - -namespace { -// State for the averaging algorithm we're using. -float prediction_history[kGestureCount][kPredictionHistoryLength] = {}; -int prediction_history_index = 0; -int prediction_suppression_count = 0; -} // namespace - -// Return the result of the last prediction -// 0: wing("W"), 1: ring("O"), 2: slope("angle"), 3: unknown -int PredictGesture(float* output) { - // Record the latest predictions in our rolling history buffer. - for (int i = 0; i < kGestureCount; ++i) { - prediction_history[i][prediction_history_index] = output[i]; - } - // Figure out which slot to put the next predictions into. - ++prediction_history_index; - if (prediction_history_index >= kPredictionHistoryLength) { - prediction_history_index = 0; - } - - // Average the last n predictions for each gesture, and find which has the - // highest score. - int max_predict_index = -1; - float max_predict_score = 0.0f; - for (int i = 0; i < kGestureCount; i++) { - float prediction_sum = 0.0f; - for (int j = 0; j < kPredictionHistoryLength; ++j) { - prediction_sum += prediction_history[i][j]; - } - const float prediction_average = prediction_sum / kPredictionHistoryLength; - if ((max_predict_index == -1) || (prediction_average > max_predict_score)) { - max_predict_index = i; - max_predict_score = prediction_average; - } - } - - // If there's been a recent prediction, don't trigger a new one too soon. - if (prediction_suppression_count > 0) { - --prediction_suppression_count; - } - // If we're predicting no gesture, or the average score is too low, or there's - // been a gesture recognised too recently, return no gesture. - if ((max_predict_index == kNoGesture) || - (max_predict_score < kDetectionThreshold) || - (prediction_suppression_count > 0)) { - return kNoGesture; - } else { - // Reset the suppression counter so we don't come up with another prediction - // too soon. - prediction_suppression_count = kPredictionSuppressionDuration; - return max_predict_index; - } -} diff --git a/tensorflow/lite/micro/examples/magic_wand/gesture_predictor.h b/tensorflow/lite/micro/examples/magic_wand/gesture_predictor.h deleted file mode 100644 index 713cb561035..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/gesture_predictor.h +++ /dev/null @@ -1,21 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#ifndef TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_GESTURE_PREDICTOR_H_ -#define TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_GESTURE_PREDICTOR_H_ - -extern int PredictGesture(float* output); - -#endif // TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_GESTURE_PREDICTOR_H_ diff --git a/tensorflow/lite/micro/examples/magic_wand/gesture_predictor_test.cc b/tensorflow/lite/micro/examples/magic_wand/gesture_predictor_test.cc deleted file mode 100644 index 7488666df05..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/gesture_predictor_test.cc +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/gesture_predictor.h" - -#include "tensorflow/lite/micro/examples/magic_wand/constants.h" -#include "tensorflow/lite/micro/testing/micro_test.h" - -TF_LITE_MICRO_TESTS_BEGIN - -TF_LITE_MICRO_TEST(SuccessfulPrediction) { - // Use the threshold from the 0th gesture. - float probabilities[kGestureCount] = {kDetectionThreshold, 0.0, 0.0, 0.0}; - int prediction; - // Loop just too few times to trigger a prediction. - for (int i = 0; i < kPredictionHistoryLength - 1; i++) { - prediction = PredictGesture(probabilities); - TF_LITE_MICRO_EXPECT_EQ(prediction, kNoGesture); - } - // Call once more, triggering a prediction - // for category 0. - prediction = PredictGesture(probabilities); - TF_LITE_MICRO_EXPECT_EQ(prediction, 0); -} - -TF_LITE_MICRO_TEST(FailPartWayThere) { - // Use the threshold from the 0th gesture. - float probabilities[kGestureCount] = {kDetectionThreshold, 0.0, 0.0, 0.0}; - int prediction; - // Loop just too few times to trigger a prediction. - for (int i = 0; i <= kPredictionHistoryLength - 1; i++) { - prediction = PredictGesture(probabilities); - TF_LITE_MICRO_EXPECT_EQ(prediction, kNoGesture); - } - // Call with a different prediction, triggering a failure. - probabilities[0] = 0.0; - probabilities[2] = 1.0; - prediction = PredictGesture(probabilities); - TF_LITE_MICRO_EXPECT_EQ(prediction, kNoGesture); -} - -TF_LITE_MICRO_TEST(InsufficientProbability) { - // Just below the detection threshold. - float probabilities[kGestureCount] = {kDetectionThreshold - 0.1f, 0.0, 0.0, - 0.0}; - int prediction; - // Loop the exact right number of times - for (int i = 0; i <= kPredictionHistoryLength; i++) { - prediction = PredictGesture(probabilities); - TF_LITE_MICRO_EXPECT_EQ(prediction, kNoGesture); - } -} - -TF_LITE_MICRO_TESTS_END diff --git a/tensorflow/lite/micro/examples/magic_wand/magic_wand.tflite b/tensorflow/lite/micro/examples/magic_wand/magic_wand.tflite deleted file mode 100755 index 36bf8ce4539..00000000000 Binary files a/tensorflow/lite/micro/examples/magic_wand/magic_wand.tflite and /dev/null differ diff --git a/tensorflow/lite/micro/examples/magic_wand/magic_wand_test.cc b/tensorflow/lite/micro/examples/magic_wand/magic_wand_test.cc deleted file mode 100644 index 9db63c8a750..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/magic_wand_test.cc +++ /dev/null @@ -1,145 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/magic_wand_model_data.h" -#include "tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.h" -#include "tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.h" -#include "tensorflow/lite/micro/micro_interpreter.h" -#include "tensorflow/lite/micro/micro_log.h" -#include "tensorflow/lite/micro/micro_mutable_op_resolver.h" -#include "tensorflow/lite/micro/testing/micro_test.h" -#include "tensorflow/lite/schema/schema_generated.h" - -TF_LITE_MICRO_TESTS_BEGIN - -TF_LITE_MICRO_TEST(LoadModelAndPerformInference) { - // Map the model into a usable data structure. This doesn't involve any - // copying or parsing, it's a very lightweight operation. - const tflite::Model* model = ::tflite::GetModel(g_magic_wand_model_data); - if (model->version() != TFLITE_SCHEMA_VERSION) { - MicroPrintf( - "Model provided is schema version %d not equal " - "to supported version %d.\n", - model->version(), TFLITE_SCHEMA_VERSION); - } - - // Pull in only the operation implementations we need. - // This relies on a complete list of all the ops needed by this graph. - // An easier approach is to just use the AllOpsResolver, but this will - // incur some penalty in code space for op implementations that are not - // needed by this graph. - static tflite::MicroMutableOpResolver<5> micro_op_resolver; // NOLINT - micro_op_resolver.AddConv2D(); - micro_op_resolver.AddDepthwiseConv2D(); - micro_op_resolver.AddFullyConnected(); - micro_op_resolver.AddMaxPool2D(); - micro_op_resolver.AddSoftmax(); - - // Create an area of memory to use for input, output, and intermediate arrays. - // Finding the minimum value for your model may require some trial and error. - const int tensor_arena_size = 60 * 1024; - uint8_t tensor_arena[tensor_arena_size]; - - // Build an interpreter to run the model with - tflite::MicroInterpreter interpreter(model, micro_op_resolver, tensor_arena, - tensor_arena_size); - - // Allocate memory from the tensor_arena for the model's tensors - interpreter.AllocateTensors(); - - // Obtain a pointer to the model's input tensor - TfLiteTensor* input = interpreter.input(0); - - // Make sure the input has the properties we expect - TF_LITE_MICRO_EXPECT(input != nullptr); - TF_LITE_MICRO_EXPECT_EQ(4, input->dims->size); - // The value of each element gives the length of the corresponding tensor. - TF_LITE_MICRO_EXPECT_EQ(1, input->dims->data[0]); - TF_LITE_MICRO_EXPECT_EQ(128, input->dims->data[1]); - TF_LITE_MICRO_EXPECT_EQ(3, input->dims->data[2]); - TF_LITE_MICRO_EXPECT_EQ(1, input->dims->data[3]); - // The input is a 32 bit floating point value - TF_LITE_MICRO_EXPECT_EQ(kTfLiteFloat32, input->type); - - // Provide an input value - const float* ring_features_data = g_ring_micro_f9643d42_nohash_4_data; - MicroPrintf("%d", input->bytes); - for (size_t i = 0; i < (input->bytes / sizeof(float)); ++i) { - input->data.f[i] = ring_features_data[i]; - } - - // Run the model on this input and check that it succeeds - TfLiteStatus invoke_status = interpreter.Invoke(); - if (invoke_status != kTfLiteOk) { - MicroPrintf("Invoke failed\n"); - } - TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, invoke_status); - - // Obtain a pointer to the output tensor and make sure it has the - // properties we expect. - TfLiteTensor* output = interpreter.output(0); - TF_LITE_MICRO_EXPECT_EQ(2, output->dims->size); - TF_LITE_MICRO_EXPECT_EQ(1, output->dims->data[0]); - TF_LITE_MICRO_EXPECT_EQ(4, output->dims->data[1]); - TF_LITE_MICRO_EXPECT_EQ(kTfLiteFloat32, output->type); - - // There are four possible classes in the output, each with a score. - const int kWingIndex = 0; - const int kRingIndex = 1; - const int kSlopeIndex = 2; - const int kNegativeIndex = 3; - - // Make sure that the expected "Ring" score is higher than the other - // classes. - float wing_score = output->data.f[kWingIndex]; - float ring_score = output->data.f[kRingIndex]; - float slope_score = output->data.f[kSlopeIndex]; - float negative_score = output->data.f[kNegativeIndex]; - TF_LITE_MICRO_EXPECT_GT(ring_score, wing_score); - TF_LITE_MICRO_EXPECT_GT(ring_score, slope_score); - TF_LITE_MICRO_EXPECT_GT(ring_score, negative_score); - - // Now test with a different input, from a recording of "Slope". - const float* slope_features_data = g_slope_micro_f2e59fea_nohash_1_data; - for (size_t i = 0; i < (input->bytes / sizeof(float)); ++i) { - input->data.f[i] = slope_features_data[i]; - } - - // Run the model on this "Slope" input. - invoke_status = interpreter.Invoke(); - if (invoke_status != kTfLiteOk) { - MicroPrintf("Invoke failed\n"); - } - TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, invoke_status); - - // Get the output from the model, and make sure it's the expected size and - // type. - output = interpreter.output(0); - TF_LITE_MICRO_EXPECT_EQ(2, output->dims->size); - TF_LITE_MICRO_EXPECT_EQ(1, output->dims->data[0]); - TF_LITE_MICRO_EXPECT_EQ(4, output->dims->data[1]); - TF_LITE_MICRO_EXPECT_EQ(kTfLiteFloat32, output->type); - - // Make sure that the expected "Slope" score is higher than the other classes. - wing_score = output->data.f[kWingIndex]; - ring_score = output->data.f[kRingIndex]; - slope_score = output->data.f[kSlopeIndex]; - negative_score = output->data.f[kNegativeIndex]; - TF_LITE_MICRO_EXPECT_GT(slope_score, wing_score); - TF_LITE_MICRO_EXPECT_GT(slope_score, ring_score); - TF_LITE_MICRO_EXPECT_GT(slope_score, negative_score); -} - -TF_LITE_MICRO_TESTS_END diff --git a/tensorflow/lite/micro/examples/magic_wand/main.cc b/tensorflow/lite/micro/examples/magic_wand/main.cc deleted file mode 100644 index 7dab1cd41d3..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/main.cc +++ /dev/null @@ -1,27 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/main_functions.h" - -// This is the default main used on systems that have the standard C entry -// point. Other devices (for example FreeRTOS or ESP32) that have different -// requirements for entry code (like an app_main function) should specialize -// this main.cc file in a target-specific subfolder. -int main(int argc, char* argv[]) { - setup(); - while (true) { - loop(); - } -} diff --git a/tensorflow/lite/micro/examples/magic_wand/main_functions.cc b/tensorflow/lite/micro/examples/magic_wand/main_functions.cc deleted file mode 100644 index 7f5775ce4c1..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/main_functions.cc +++ /dev/null @@ -1,113 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/main_functions.h" - -#include "tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h" -#include "tensorflow/lite/micro/examples/magic_wand/constants.h" -#include "tensorflow/lite/micro/examples/magic_wand/gesture_predictor.h" -#include "tensorflow/lite/micro/examples/magic_wand/magic_wand_model_data.h" -#include "tensorflow/lite/micro/examples/magic_wand/output_handler.h" -#include "tensorflow/lite/micro/micro_interpreter.h" -#include "tensorflow/lite/micro/micro_log.h" -#include "tensorflow/lite/micro/micro_mutable_op_resolver.h" -#include "tensorflow/lite/micro/system_setup.h" -#include "tensorflow/lite/schema/schema_generated.h" - -// Globals, used for compatibility with Arduino-style sketches. -namespace { -const tflite::Model* model = nullptr; -tflite::MicroInterpreter* interpreter = nullptr; -TfLiteTensor* model_input = nullptr; -int input_length; - -// Create an area of memory to use for input, output, and intermediate arrays. -// The size of this will depend on the model you're using, and may need to be -// determined by experimentation. -constexpr int kTensorArenaSize = 60 * 1024; -alignas(16) uint8_t tensor_arena[kTensorArenaSize]; -} // namespace - -// The name of this function is important for Arduino compatibility. -void setup() { - tflite::InitializeTarget(); - - // Map the model into a usable data structure. This doesn't involve any - // copying or parsing, it's a very lightweight operation. - model = tflite::GetModel(g_magic_wand_model_data); - if (model->version() != TFLITE_SCHEMA_VERSION) { - MicroPrintf( - "Model provided is schema version %d not equal " - "to supported version %d.", - model->version(), TFLITE_SCHEMA_VERSION); - return; - } - - // Pull in only the operation implementations we need. - // This relies on a complete list of all the ops needed by this graph. - // An easier approach is to just use the AllOpsResolver, but this will - // incur some penalty in code space for op implementations that are not - // needed by this graph. - static tflite::MicroMutableOpResolver<5> micro_op_resolver; // NOLINT - micro_op_resolver.AddConv2D(); - micro_op_resolver.AddDepthwiseConv2D(); - micro_op_resolver.AddFullyConnected(); - micro_op_resolver.AddMaxPool2D(); - micro_op_resolver.AddSoftmax(); - - // Build an interpreter to run the model with. - static tflite::MicroInterpreter static_interpreter( - model, micro_op_resolver, tensor_arena, kTensorArenaSize); - interpreter = &static_interpreter; - - // Allocate memory from the tensor_arena for the model's tensors. - interpreter->AllocateTensors(); - - // Obtain pointer to the model's input tensor. - model_input = interpreter->input(0); - if ((model_input->dims->size != 4) || (model_input->dims->data[0] != 1) || - (model_input->dims->data[1] != 128) || - (model_input->dims->data[2] != kChannelNumber) || - (model_input->type != kTfLiteFloat32)) { - MicroPrintf("Bad input tensor parameters in model"); - return; - } - - input_length = model_input->bytes / sizeof(float); - - TfLiteStatus setup_status = SetupAccelerometer(); - if (setup_status != kTfLiteOk) { - MicroPrintf("Set up failed\n"); - } -} - -void loop() { - // Attempt to read new data from the accelerometer. - bool got_data = ReadAccelerometer(model_input->data.f, input_length); - // If there was no new data, wait until next time. - if (!got_data) return; - - // Run inference, and report any error. - TfLiteStatus invoke_status = interpreter->Invoke(); - if (invoke_status != kTfLiteOk) { - MicroPrintf("Invoke failed on index: %d\n", begin_index); - return; - } - // Analyze the results to obtain a prediction - int gesture_index = PredictGesture(interpreter->output(0)->data.f); - - // Produce an output - HandleOutput(gesture_index); -} diff --git a/tensorflow/lite/micro/examples/magic_wand/main_functions.h b/tensorflow/lite/micro/examples/magic_wand/main_functions.h deleted file mode 100644 index d69755b3a58..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/main_functions.h +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#ifndef TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_MAIN_FUNCTIONS_H_ -#define TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_MAIN_FUNCTIONS_H_ - -// Expose a C friendly interface for main functions. -#ifdef __cplusplus -extern "C" { -#endif - -// Initializes all data needed for the example. The name is important, and needs -// to be setup() for Arduino compatibility. -void setup(); - -// Runs one iteration of data gathering and inference. This should be called -// repeatedly from the application code. The name needs to be loop() for Arduino -// compatibility. -void loop(); - -#ifdef __cplusplus -} -#endif - -#endif // TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_MAIN_FUNCTIONS_H_ diff --git a/tensorflow/lite/micro/examples/magic_wand/output_handler.cc b/tensorflow/lite/micro/examples/magic_wand/output_handler.cc deleted file mode 100644 index 92436a79b0d..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/output_handler.cc +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/output_handler.h" - -#include "tensorflow/lite/micro/micro_log.h" - -void HandleOutput(int kind) { - // light (red: wing, blue: ring, green: slope) - if (kind == 0) { - MicroPrintf( - "WING:\n\r* * *\n\r * * * " - "*\n\r * * * *\n\r * * * *\n\r * * " - "* *\n\r * *\n\r"); - } else if (kind == 1) { - MicroPrintf( - "RING:\n\r *\n\r * *\n\r * *\n\r " - " * *\n\r * *\n\r * *\n\r " - " *\n\r"); - } else if (kind == 2) { - MicroPrintf( - "SLOPE:\n\r *\n\r *\n\r *\n\r *\n\r " - "*\n\r *\n\r *\n\r * * * * * * * *\n\r"); - } -} diff --git a/tensorflow/lite/micro/examples/magic_wand/output_handler.h b/tensorflow/lite/micro/examples/magic_wand/output_handler.h deleted file mode 100644 index 0677b2c863a..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/output_handler.h +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#ifndef TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_OUTPUT_HANDLER_H_ -#define TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_OUTPUT_HANDLER_H_ - -#include "tensorflow/lite/c/common.h" - -void HandleOutput(int kind); - -#endif // TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_OUTPUT_HANDLER_H_ diff --git a/tensorflow/lite/micro/examples/magic_wand/output_handler_test.cc b/tensorflow/lite/micro/examples/magic_wand/output_handler_test.cc deleted file mode 100644 index bceccd743a3..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/output_handler_test.cc +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/output_handler.h" - -#include "tensorflow/lite/micro/testing/micro_test.h" - -TF_LITE_MICRO_TESTS_BEGIN - -TF_LITE_MICRO_TEST(TestCallability) { - HandleOutput(0); - HandleOutput(1); - HandleOutput(2); - HandleOutput(3); -} - -TF_LITE_MICRO_TESTS_END diff --git a/tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.cc b/tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.cc deleted file mode 100644 index 49f7d5422f3..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.cc +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.h" - -const int g_ring_micro_f9643d42_nohash_4_length = 128; -const int g_ring_micro_f9643d42_nohash_4_dim = 3; -// Raw accelerometer data with a sample rate of 25Hz -const float g_ring_micro_f9643d42_nohash_4_data[] = { - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, -665.0, 228.0, 827.0, -680.0, 339.0, 716.0, - -680.0, 564.0, 812.0, -679.0, 552.0, 818.0, -665.0, 528.0, 751.0, - -658.0, 432.0, 618.0, -655.0, 445.0, 592.0, -667.0, 484.0, 556.0, - -684.0, 590.0, 510.0, -674.0, 672.0, 475.0, -660.0, 786.0, 390.0, - -562.0, 1124.0, 128.0, -526.0, 1140.0, 111.0, -486.0, 1044.0, 33.0, - -416.0, 652.0, -134.0, -390.0, 534.0, -143.0, -365.0, 381.0, -117.0, - -314.0, 60.0, 94.0, -322.0, 7.0, 190.0, -338.0, -95.0, 342.0, - -360.0, -106.0, 842.0, -351.0, -41.0, 965.0, -352.0, 12.0, 960.0, - -366.0, 42.0, 1124.0, -322.0, 56.0, 1178.0, -312.0, 15.0, 1338.0, - -254.0, 10.0, 1532.0, -241.0, 5.0, 1590.0, -227.0, 60.0, 1565.0, - -204.0, 282.0, 1560.0, -180.0, 262.0, 1524.0, -138.0, 385.0, 1522.0, - -84.0, 596.0, 1626.0, -55.0, 639.0, 1604.0, -19.0, 771.0, 1511.0, - 16.0, 932.0, 1132.0, 15.0, 924.0, 1013.0, 1.0, 849.0, 812.0, - -88.0, 628.0, 500.0, -114.0, 609.0, 463.0, -155.0, 559.0, 382.0, - -234.0, 420.0, 278.0, -254.0, 390.0, 272.0, -327.0, 200.0, 336.0, - -558.0, -556.0, 630.0, -640.0, -607.0, 740.0, -706.0, -430.0, 868.0, - -778.0, 42.0, 1042.0, -763.0, 84.0, 973.0, -735.0, 185.0, 931.0, - -682.0, 252.0, 766.0, -673.0, 230.0, 757.0, -671.0, 218.0, 757.0, - -656.0, 222.0, 714.0, -659.0, 238.0, 746.0, -640.0, 276.0, 731.0, - -634.0, 214.0, 754.0, -637.0, 207.0, 735.0, -637.0, 194.0, 742.0, - -634.0, 248.0, 716.0, -631.0, 265.0, 697.0, -628.0, 252.0, 797.0, - -592.0, 204.0, 816.0, -618.0, 218.0, 812.0, -633.0, 231.0, 828.0, - -640.0, 222.0, 736.0, -634.0, 221.0, 787.0, -}; diff --git a/tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.h b/tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.h deleted file mode 100644 index 9cd02cd53b0..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/ring_micro_features_data.h +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#ifndef TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_RING_MICRO_FEATURES_DATA_H_ -#define TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_RING_MICRO_FEATURES_DATA_H_ - -extern const int g_ring_micro_f9643d42_nohash_4_length; -extern const int g_ring_micro_f9643d42_nohash_4_dim; -extern const float g_ring_micro_f9643d42_nohash_4_data[]; - -#endif // TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_RING_MICRO_FEATURES_DATA_H_ diff --git a/tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.cc b/tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.cc deleted file mode 100644 index 3790b938e9c..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.cc +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.h" - -const int g_slope_micro_f2e59fea_nohash_1_length = 128; -const int g_slope_micro_f2e59fea_nohash_1_dim = 3; -// Raw accelerometer data with a sample rate of 25Hz -const float g_slope_micro_f2e59fea_nohash_1_data[] = { - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 0.0, -766.0, 132.0, 709.0, -751.0, 249.0, 659.0, - -714.0, 314.0, 630.0, -709.0, 244.0, 623.0, -707.0, 230.0, 659.0, - -704.0, 202.0, 748.0, -714.0, 219.0, 728.0, -722.0, 239.0, 710.0, - -744.0, 116.0, 612.0, -753.0, -49.0, 570.0, -748.0, -279.0, 527.0, - -668.0, -664.0, 592.0, -601.0, -635.0, 609.0, -509.0, -559.0, 606.0, - -286.0, -162.0, 536.0, -255.0, -144.0, 495.0, -209.0, -85.0, 495.0, - 6.0, 416.0, 698.0, -33.0, 304.0, 1117.0, -82.0, 405.0, 1480.0, - -198.0, 1008.0, 1908.0, -229.0, 990.0, 1743.0, -234.0, 934.0, 1453.0, - -126.0, 838.0, 896.0, -78.0, 792.0, 911.0, -27.0, 741.0, 918.0, - 114.0, 734.0, 960.0, 135.0, 613.0, 959.0, 152.0, 426.0, 1015.0, - 106.0, -116.0, 1110.0, 63.0, -314.0, 1129.0, -12.0, -486.0, 1179.0, - -118.0, -656.0, 1510.0, -116.0, -558.0, 1553.0, -126.0, -361.0, 1367.0, - -222.0, -76.0, 922.0, -210.0, -26.0, 971.0, -194.0, 50.0, 1053.0, - -178.0, 72.0, 1082.0, -169.0, 100.0, 1073.0, -162.0, 133.0, 1050.0, - -156.0, 226.0, 976.0, -154.0, 323.0, 886.0, -130.0, 240.0, 1154.0, - -116.0, 124.0, 916.0, -132.0, 124.0, 937.0, -153.0, 115.0, 981.0, - -184.0, 94.0, 962.0, -177.0, 85.0, 1017.0, -173.0, 92.0, 1027.0, - -168.0, 158.0, 1110.0, -181.0, 101.0, 1030.0, -180.0, 139.0, 1054.0, - -152.0, 10.0, 1044.0, -169.0, 74.0, 1007.0, -}; diff --git a/tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.h b/tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.h deleted file mode 100644 index 6ed0c3c3cdb..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/slope_micro_features_data.h +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#ifndef TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_SLOPE_MICRO_FEATURES_DATA_H_ -#define TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_SLOPE_MICRO_FEATURES_DATA_H_ - -extern const int g_slope_micro_f2e59fea_nohash_1_length; -extern const int g_slope_micro_f2e59fea_nohash_1_dim; -extern const float g_slope_micro_f2e59fea_nohash_1_data[]; - -#endif // TENSORFLOW_LITE_MICRO_EXAMPLES_MAGIC_WAND_SLOPE_MICRO_FEATURES_DATA_H_ diff --git a/tensorflow/lite/micro/examples/magic_wand/train/README.md b/tensorflow/lite/micro/examples/magic_wand/train/README.md deleted file mode 100644 index 4ceda344a53..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/README.md +++ /dev/null @@ -1,191 +0,0 @@ -# Gesture Recognition Magic Wand Training Scripts - -## Introduction - -The scripts in this directory can be used to train a TensorFlow model that -classifies gestures based on accelerometer data. The code uses Python 3.7 and -TensorFlow 2.0. The resulting model is less than 20KB in size. - -The following document contains instructions on using the scripts to train a -model, and capturing your own training data. - -This project was inspired by the [Gesture Recognition Magic Wand](https://github.com/jewang/gesture-demo) -project by Jennifer Wang. - -## Training - -### Dataset - -Three magic gestures were chosen, and data were collected from 7 -different people. Some random long movement sequences were collected and divided -into shorter pieces, which made up "negative" data along with some other -automatically generated random data. - -The dataset can be downloaded from the following URL: - -[download.tensorflow.org/models/tflite/magic_wand/data.tar.gz](http://download.tensorflow.org/models/tflite/magic_wand/data.tar.gz) - -### Training in Colab - -The following [Google Colaboratory](https://colab.research.google.com) -notebook demonstrates how to train the model. It's the easiest way to get -started: - - - - -
- Run in Google Colab - - View source on GitHub -
- -If you'd prefer to run the scripts locally, use the following instructions. - -### Running the scripts - -Use the following command to install the required dependencies: - -```shell -pip install -r requirements.txt -``` - -There are two ways to train the model: - -- Random data split, which mixes different people's data together and randomly - splits them into training, validation, and test sets -- Person data split, which splits the data by person - -#### Random data split - -Using a random split results in higher training accuracy than a person split, -but inferior performance on new data. - -```shell -$ python data_prepare.py - -$ python data_split.py - -$ python train.py --model CNN --person false -``` - -#### Person data split - -Using a person data split results in lower training accuracy but better -performance on new data. - -```shell -$ python data_prepare.py - -$ python data_split_person.py - -$ python train.py --model CNN --person true -``` - -#### Model type - -In the `--model` argument, you can provide `CNN` or `LSTM`. The CNN model has a -smaller size and lower latency. - -## Collecting new data - -To obtain new training data using the -[SparkFun Edge development board](https://sparkfun.com/products/15170), you can -modify one of the examples in the [SparkFun Edge BSP](https://github.com/sparkfun/SparkFun_Edge_BSP) -and deploy it using the Ambiq SDK. - -### Install the Ambiq SDK and SparkFun Edge BSP - -Follow SparkFun's -[Using SparkFun Edge Board with Ambiq Apollo3 SDK](https://learn.sparkfun.com/tutorials/using-sparkfun-edge-board-with-ambiq-apollo3-sdk/all) -guide to set up the Ambiq SDK and SparkFun Edge BSP. - -#### Modify the example code - -First, `cd` into -`AmbiqSuite-Rel2.2.0/boards/SparkFun_Edge_BSP/examples/example1_edge_test`. - -##### Modify `src/tf_adc/tf_adc.c` - -Add `true` in line 62 as the second parameter of function -`am_hal_adc_samples_read`. - -##### Modify `src/main.c` - -Add the line below in `int main(void)`, just before the line `while(1)`: - -```cc -am_util_stdio_printf("-,-,-\r\n"); -``` - -Change the following lines in `while(1){...}` - -```cc -am_util_stdio_printf("Acc [mg] %04.2f x, %04.2f y, %04.2f z, Temp [deg C] %04.2f, MIC0 [counts / 2^14] %d\r\n", acceleration_mg[0], acceleration_mg[1], acceleration_mg[2], temperature_degC, (audioSample) ); -``` - -to: - -```cc -am_util_stdio_printf("%04.2f,%04.2f,%04.2f\r\n", acceleration_mg[0], acceleration_mg[1], acceleration_mg[2]); -``` - -#### Flash the binary - -Follow the instructions in -[SparkFun's guide](https://learn.sparkfun.com/tutorials/using-sparkfun-edge-board-with-ambiq-apollo3-sdk/all#example-applications) -to flash the binary to the device. - -#### Collect accelerometer data - -First, in a new terminal window, run the following command to begin logging -output to `output.txt`: - -```shell -$ script output.txt -``` - -Next, in the same window, use `screen` to connect to the device: - -```shell -$ screen ${DEVICENAME} 115200 -``` - -Output information collected from accelerometer sensor will be shown on the -screen and saved in `output.txt`, in the format of "x,y,z" per line. - -Press the `RST` button to start capturing a new gesture, then press Button 14 -when it ends. New data will begin with a line "-,-,-". - -To exit `screen`, hit +Ctrl\\+A+, immediately followed by the +K+ key, -then hit the +Y+ key. Then run - -```shell -$ exit -``` - -to stop logging data. Data will be saved in `output.txt`. For compatibility -with the training scripts, change the file name to include person's name and -the gesture name, in the following format: - -``` -output_{gesture_name}_{person_name}.txt -``` - -#### Edit and run the scripts - -Edit the following files to include your new gesture names (replacing -"wing", "ring", and "slope") - -- `data_load.py` -- `data_prepare.py` -- `data_split.py` - -Edit the following files to include your new person names (replacing "hyw", -"shiyun", "tangsy", "dengyl", "jiangyh", "xunkai", "lsj", "pengxl", "liucx", -and "zhangxy"): - -- `data_prepare.py` -- `data_split_person.py` - -Finally, run the commands described earlier to train a new model. diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_augmentation.py b/tensorflow/lite/micro/examples/magic_wand/train/data_augmentation.py deleted file mode 100644 index 9c90be97f3b..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_augmentation.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -# pylint: disable=g-bad-import-order -"""Data augmentation that will be used in data_load.py.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import random - -import numpy as np - - -def time_wrapping(molecule, denominator, data): - """Generate (molecule/denominator)x speed data.""" - tmp_data = [[0 for i in range(len(data[0]))] - for j in range((int(len(data) / molecule) - 1) * denominator)] - for i in range(int(len(data) / molecule) - 1): - for j in range(len(data[i])): - for k in range(denominator): - tmp_data[denominator * i + - k][j] = (data[molecule * i + k][j] * (denominator - k) + - data[molecule * i + k + 1][j] * k) / denominator - return tmp_data - - -def augment_data(original_data, original_label): - """Perform data augmentation.""" - new_data = [] - new_label = [] - for idx, (data, label) in enumerate(zip(original_data, original_label)): # pylint: disable=unused-variable - # Original data - new_data.append(data) - new_label.append(label) - # Sequence shift - for num in range(5): # pylint: disable=unused-variable - new_data.append((np.array(data, dtype=np.float32) + - (random.random() - 0.5) * 200).tolist()) - new_label.append(label) - # Random noise - tmp_data = [[0 for i in range(len(data[0]))] for j in range(len(data))] - for num in range(5): - for i in range(len(tmp_data)): - for j in range(len(tmp_data[i])): - tmp_data[i][j] = data[i][j] + 5 * random.random() - new_data.append(tmp_data) - new_label.append(label) - # Time warping - fractions = [(3, 2), (5, 3), (2, 3), (3, 4), (9, 5), (6, 5), (4, 5)] - for molecule, denominator in fractions: - new_data.append(time_wrapping(molecule, denominator, data)) - new_label.append(label) - # Movement amplification - for molecule, denominator in fractions: - new_data.append( - (np.array(data, dtype=np.float32) * molecule / denominator).tolist()) - new_label.append(label) - return new_data, new_label diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_augmentation_test.py b/tensorflow/lite/micro/examples/magic_wand/train/data_augmentation_test.py deleted file mode 100644 index a439603a706..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_augmentation_test.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -# pylint: disable=g-bad-import-order -"""Test for data_augmentation.py.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import unittest - -import numpy as np - -from data_augmentation import augment_data -from data_augmentation import time_wrapping - - -class TestAugmentation(unittest.TestCase): - - def test_time_wrapping(self): - original_data = np.random.rand(10, 3).tolist() - wrapped_data = time_wrapping(4, 5, original_data) - self.assertEqual(len(wrapped_data), int(len(original_data) / 4 - 1) * 5) - self.assertEqual(len(wrapped_data[0]), len(original_data[0])) - - def test_augment_data(self): - original_data = [ - np.random.rand(128, 3).tolist(), - np.random.rand(66, 2).tolist(), - np.random.rand(9, 1).tolist() - ] - original_label = ["data", "augmentation", "test"] - augmented_data, augmented_label = augment_data(original_data, - original_label) - self.assertEqual(25 * len(original_data), len(augmented_data)) - self.assertIsInstance(augmented_data, list) - self.assertEqual(25 * len(original_label), len(augmented_label)) - self.assertIsInstance(augmented_label, list) - for i in range(len(original_label)): - self.assertEqual(augmented_label[25 * i], original_label[i]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_load.py b/tensorflow/lite/micro/examples/magic_wand/train/data_load.py deleted file mode 100644 index 0416ae314cb..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_load.py +++ /dev/null @@ -1,104 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -# pylint: disable=g-bad-import-order -"""Load data from the specified paths and format them for training.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import json - -import numpy as np -import tensorflow as tf - -from data_augmentation import augment_data - -LABEL_NAME = "gesture" -DATA_NAME = "accel_ms2_xyz" - - -class DataLoader(object): - """Loads data and prepares for training.""" - - def __init__(self, train_data_path, valid_data_path, test_data_path, - seq_length): - self.dim = 3 - self.seq_length = seq_length - self.label2id = {"wing": 0, "ring": 1, "slope": 2, "negative": 3} - self.train_data, self.train_label, self.train_len = self.get_data_file( - train_data_path, "train") - self.valid_data, self.valid_label, self.valid_len = self.get_data_file( - valid_data_path, "valid") - self.test_data, self.test_label, self.test_len = self.get_data_file( - test_data_path, "test") - - def get_data_file(self, data_path, data_type): - """Get train, valid and test data from files.""" - data = [] - label = [] - with open(data_path, "r") as f: - lines = f.readlines() - for idx, line in enumerate(lines): # pylint: disable=unused-variable - dic = json.loads(line) - data.append(dic[DATA_NAME]) - label.append(dic[LABEL_NAME]) - if data_type == "train": - data, label = augment_data(data, label) - length = len(label) - print(data_type + "_data_length:" + str(length)) - return data, label, length - - def pad(self, data, seq_length, dim): - """Get neighbour padding.""" - noise_level = 20 - padded_data = [] - # Before- Neighbour padding - tmp_data = (np.random.rand(seq_length, dim) - 0.5) * noise_level + data[0] - tmp_data[(seq_length - - min(len(data), seq_length)):] = data[:min(len(data), seq_length)] - padded_data.append(tmp_data) - # After- Neighbour padding - tmp_data = (np.random.rand(seq_length, dim) - 0.5) * noise_level + data[-1] - tmp_data[:min(len(data), seq_length)] = data[:min(len(data), seq_length)] - padded_data.append(tmp_data) - return padded_data - - def format_support_func(self, padded_num, length, data, label): - """Support function for format.(Helps format train, valid and test.)""" - # Add 2 padding, initialize data and label - length *= padded_num - features = np.zeros((length, self.seq_length, self.dim)) - labels = np.zeros(length) - # Get padding for train, valid and test - for idx, (data, label) in enumerate(zip(data, label)): - padded_data = self.pad(data, self.seq_length, self.dim) - for num in range(padded_num): - features[padded_num * idx + num] = padded_data[num] - labels[padded_num * idx + num] = self.label2id[label] - # Turn into tf.data.Dataset - dataset = tf.data.Dataset.from_tensor_slices( - (features, labels.astype("int32"))) - return length, dataset - - def format(self): - """Format data(including padding, etc.) and get the dataset for the model.""" - padded_num = 2 - self.train_len, self.train_data = self.format_support_func( - padded_num, self.train_len, self.train_data, self.train_label) - self.valid_len, self.valid_data = self.format_support_func( - padded_num, self.valid_len, self.valid_data, self.valid_label) - self.test_len, self.test_data = self.format_support_func( - padded_num, self.test_len, self.test_data, self.test_label) diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_load_test.py b/tensorflow/lite/micro/examples/magic_wand/train/data_load_test.py deleted file mode 100644 index c0b9cf81657..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_load_test.py +++ /dev/null @@ -1,97 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -# pylint: disable=g-bad-import-order -"""Test for data_load.py.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import unittest -from data_load import DataLoader - -import tensorflow as tf - - -class TestLoad(unittest.TestCase): - - def setUp(self): # pylint: disable=g-missing-super-call - self.loader = DataLoader("./data/train", - "./data/valid", - "./data/test", - seq_length=512) - - def test_get_data(self): - self.assertIsInstance(self.loader.train_data, list) - self.assertIsInstance(self.loader.train_label, list) - self.assertIsInstance(self.loader.valid_data, list) - self.assertIsInstance(self.loader.valid_label, list) - self.assertIsInstance(self.loader.test_data, list) - self.assertIsInstance(self.loader.test_label, list) - self.assertEqual(self.loader.train_len, len(self.loader.train_data)) - self.assertEqual(self.loader.train_len, len(self.loader.train_label)) - self.assertEqual(self.loader.valid_len, len(self.loader.valid_data)) - self.assertEqual(self.loader.valid_len, len(self.loader.valid_label)) - self.assertEqual(self.loader.test_len, len(self.loader.test_data)) - self.assertEqual(self.loader.test_len, len(self.loader.test_label)) - - def test_pad(self): - original_data1 = [[2, 3], [1, 1]] - expected_data1_0 = [[2, 3], [2, 3], [2, 3], [2, 3], [1, 1]] - expected_data1_1 = [[2, 3], [1, 1], [1, 1], [1, 1], [1, 1]] - original_data2 = [[-2, 3], [-77, -681], [5, 6], [9, -7], [22, 3333], - [9, 99], [-100, 0]] - expected_data2 = [[-2, 3], [-77, -681], [5, 6], [9, -7], [22, 3333]] - padding_data1 = self.loader.pad(original_data1, seq_length=5, dim=2) - padding_data2 = self.loader.pad(original_data2, seq_length=5, dim=2) - for i in range(len(padding_data1[0])): - for j in range(len(padding_data1[0].tolist()[0])): - self.assertLess( - abs(padding_data1[0].tolist()[i][j] - expected_data1_0[i][j]), - 10.001) - for i in range(len(padding_data1[1])): - for j in range(len(padding_data1[1].tolist()[0])): - self.assertLess( - abs(padding_data1[1].tolist()[i][j] - expected_data1_1[i][j]), - 10.001) - self.assertEqual(padding_data2[0].tolist(), expected_data2) - self.assertEqual(padding_data2[1].tolist(), expected_data2) - - def test_format(self): - self.loader.format() - expected_train_label = int( - self.loader.label2id[self.loader.train_label[0]]) - expected_valid_label = int( - self.loader.label2id[self.loader.valid_label[0]]) - expected_test_label = int(self.loader.label2id[self.loader.test_label[0]]) - for feature, label in self.loader.train_data: # pylint: disable=unused-variable - format_train_label = label.numpy() - break - for feature, label in self.loader.valid_data: - format_valid_label = label.numpy() - break - for feature, label in self.loader.test_data: - format_test_label = label.numpy() - break - self.assertEqual(expected_train_label, format_train_label) - self.assertEqual(expected_valid_label, format_valid_label) - self.assertEqual(expected_test_label, format_test_label) - self.assertIsInstance(self.loader.train_data, tf.data.Dataset) - self.assertIsInstance(self.loader.valid_data, tf.data.Dataset) - self.assertIsInstance(self.loader.test_data, tf.data.Dataset) - - -if __name__ == "__main__": - unittest.main() diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_prepare.py b/tensorflow/lite/micro/examples/magic_wand/train/data_prepare.py deleted file mode 100644 index c94ac65b96a..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_prepare.py +++ /dev/null @@ -1,162 +0,0 @@ -# coding=utf-8 -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Prepare data for further process. - -Read data from "/slope", "/ring", "/wing", "/negative" and save them -in "/data/complete_data" in python dict format. - -It will generate a new file with the following structure: -├── data -│   └── complete_data -""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import csv -import json -import os -import random - -LABEL_NAME = "gesture" -DATA_NAME = "accel_ms2_xyz" -folders = ["wing", "ring", "slope"] -names = [ - "hyw", "shiyun", "tangsy", "dengyl", "zhangxy", "pengxl", "liucx", - "jiangyh", "xunkai" -] - - -def prepare_original_data(folder, name, data, file_to_read): # pylint: disable=redefined-outer-name - """Read collected data from files.""" - if folder != "negative": - with open(file_to_read, "r") as f: - lines = csv.reader(f) - data_new = {} - data_new[LABEL_NAME] = folder - data_new[DATA_NAME] = [] - data_new["name"] = name - for idx, line in enumerate(lines): # pylint: disable=unused-variable,redefined-outer-name - if len(line) == 3: - if line[2] == "-" and data_new[DATA_NAME]: - data.append(data_new) - data_new = {} - data_new[LABEL_NAME] = folder - data_new[DATA_NAME] = [] - data_new["name"] = name - elif line[2] != "-": - data_new[DATA_NAME].append([float(i) for i in line[0:3]]) - data.append(data_new) - else: - with open(file_to_read, "r") as f: - lines = csv.reader(f) - data_new = {} - data_new[LABEL_NAME] = folder - data_new[DATA_NAME] = [] - data_new["name"] = name - for idx, line in enumerate(lines): - if len(line) == 3 and line[2] != "-": - if len(data_new[DATA_NAME]) == 120: - data.append(data_new) - data_new = {} - data_new[LABEL_NAME] = folder - data_new[DATA_NAME] = [] - data_new["name"] = name - else: - data_new[DATA_NAME].append([float(i) for i in line[0:3]]) - data.append(data_new) - - -def generate_negative_data(data): # pylint: disable=redefined-outer-name - """Generate negative data labeled as 'negative6~8'.""" - # Big movement -> around straight line - for i in range(100): - if i > 80: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative8"} - elif i > 60: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative7"} - else: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative6"} - start_x = (random.random() - 0.5) * 2000 - start_y = (random.random() - 0.5) * 2000 - start_z = (random.random() - 0.5) * 2000 - x_increase = (random.random() - 0.5) * 10 - y_increase = (random.random() - 0.5) * 10 - z_increase = (random.random() - 0.5) * 10 - for j in range(128): - dic[DATA_NAME].append([ - start_x + j * x_increase + (random.random() - 0.5) * 6, - start_y + j * y_increase + (random.random() - 0.5) * 6, - start_z + j * z_increase + (random.random() - 0.5) * 6 - ]) - data.append(dic) - # Random - for i in range(100): - if i > 80: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative8"} - elif i > 60: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative7"} - else: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative6"} - for j in range(128): - dic[DATA_NAME].append([(random.random() - 0.5) * 1000, - (random.random() - 0.5) * 1000, - (random.random() - 0.5) * 1000]) - data.append(dic) - # Stay still - for i in range(100): - if i > 80: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative8"} - elif i > 60: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative7"} - else: - dic = {DATA_NAME: [], LABEL_NAME: "negative", "name": "negative6"} - start_x = (random.random() - 0.5) * 2000 - start_y = (random.random() - 0.5) * 2000 - start_z = (random.random() - 0.5) * 2000 - for j in range(128): - dic[DATA_NAME].append([ - start_x + (random.random() - 0.5) * 40, - start_y + (random.random() - 0.5) * 40, - start_z + (random.random() - 0.5) * 40 - ]) - data.append(dic) - - -# Write data to file -def write_data(data_to_write, path): - with open(path, "w") as f: - for idx, item in enumerate(data_to_write): # pylint: disable=unused-variable,redefined-outer-name - dic = json.dumps(item, ensure_ascii=False) - f.write(dic) - f.write("\n") - - -if __name__ == "__main__": - data = [] # pylint: disable=redefined-outer-name - for idx1, folder in enumerate(folders): - for idx2, name in enumerate(names): - prepare_original_data(folder, name, data, - "./%s/output_%s_%s.txt" % (folder, folder, name)) - for idx in range(5): - prepare_original_data("negative", "negative%d" % (idx + 1), data, - "./negative/output_negative_%d.txt" % (idx + 1)) - generate_negative_data(data) - print("data_length: " + str(len(data))) - if not os.path.exists("./data"): - os.makedirs("./data") - write_data(data, "./data/complete_data") diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_prepare_test.py b/tensorflow/lite/micro/examples/magic_wand/train/data_prepare_test.py deleted file mode 100644 index 638082a1ebf..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_prepare_test.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Test for data_prepare.py.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import csv -import json -import os -import unittest -from data_prepare import generate_negative_data -from data_prepare import prepare_original_data -from data_prepare import write_data - - -class TestPrepare(unittest.TestCase): - - def setUp(self): # pylint: disable=g-missing-super-call - self.file = "./%s/output_%s_%s.txt" % (folders[0], folders[0], names[0]) # pylint: disable=undefined-variable - self.data = [] - prepare_original_data(folders[0], names[0], self.data, self.file) # pylint: disable=undefined-variable - - def test_prepare_data(self): - num = 0 - with open(self.file, "r") as f: - lines = csv.reader(f) - for idx, line in enumerate(lines): # pylint: disable=unused-variable - if len(line) == 3 and line[2] == "-": - num += 1 - self.assertEqual(len(self.data), num) - self.assertIsInstance(self.data, list) - self.assertIsInstance(self.data[0], dict) - self.assertEqual(list(self.data[-1]), ["gesture", "accel_ms2_xyz", "name"]) - self.assertEqual(self.data[0]["name"], names[0]) # pylint: disable=undefined-variable - - def test_generate_negative(self): - original_len = len(self.data) - generate_negative_data(self.data) - self.assertEqual(original_len + 300, len(self.data)) - generated_num = 0 - for idx, data in enumerate(self.data): # pylint: disable=undefined-variable, unused-variable - if data["name"] == "negative6" or data["name"] == "negative7" or data[ - "name"] == "negative8": - generated_num += 1 - self.assertEqual(generated_num, 300) - - def test_write_data(self): - data_path_test = "./data/data0" - write_data(self.data, data_path_test) - with open(data_path_test, "r") as f: - lines = f.readlines() - self.assertEqual(len(lines), len(self.data)) - self.assertEqual(json.loads(lines[0]), self.data[0]) - self.assertEqual(json.loads(lines[-1]), self.data[-1]) - os.remove(data_path_test) - - -if __name__ == "__main__": - unittest.main() diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_split.py b/tensorflow/lite/micro/examples/magic_wand/train/data_split.py deleted file mode 100644 index fb9a74c6415..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_split.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding=utf-8 -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Mix and split data. - -Mix different people's data together and randomly split them into train, -validation and test. These data would be saved separately under "/data". -It will generate new files with the following structure: - -├── data -│   ├── complete_data -│   ├── test -│   ├── train -│   └── valid -""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import json -import random -from data_prepare import write_data - - -# Read data -def read_data(path): - data = [] # pylint: disable=redefined-outer-name - with open(path, "r") as f: - lines = f.readlines() - for idx, line in enumerate(lines): # pylint: disable=unused-variable - dic = json.loads(line) - data.append(dic) - print("data_length:" + str(len(data))) - return data - - -def split_data(data, train_ratio, valid_ratio): # pylint: disable=redefined-outer-name - """Splits data into train, validation and test according to ratio.""" - train_data = [] # pylint: disable=redefined-outer-name - valid_data = [] # pylint: disable=redefined-outer-name - test_data = [] # pylint: disable=redefined-outer-name - num_dic = {"wing": 0, "ring": 0, "slope": 0, "negative": 0} - for idx, item in enumerate(data): # pylint: disable=unused-variable - for i in num_dic: - if item["gesture"] == i: - num_dic[i] += 1 - print(num_dic) - train_num_dic = {} - valid_num_dic = {} - for i in num_dic: - train_num_dic[i] = int(train_ratio * num_dic[i]) - valid_num_dic[i] = int(valid_ratio * num_dic[i]) - random.seed(30) - random.shuffle(data) - for idx, item in enumerate(data): - for i in num_dic: - if item["gesture"] == i: - if train_num_dic[i] > 0: - train_data.append(item) - train_num_dic[i] -= 1 - elif valid_num_dic[i] > 0: - valid_data.append(item) - valid_num_dic[i] -= 1 - else: - test_data.append(item) - print("train_length:" + str(len(train_data))) - print("test_length:" + str(len(test_data))) - return train_data, valid_data, test_data - - -if __name__ == "__main__": - data = read_data("./data/complete_data") - train_data, valid_data, test_data = split_data(data, 0.6, 0.2) - write_data(train_data, "./data/train") - write_data(valid_data, "./data/valid") - write_data(test_data, "./data/test") diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_split_person.py b/tensorflow/lite/micro/examples/magic_wand/train/data_split_person.py deleted file mode 100644 index 75ac5c53082..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_split_person.py +++ /dev/null @@ -1,73 +0,0 @@ -# coding=utf-8 -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Split data into train, validation and test dataset according to person. - -That is, use some people's data as train, some other people's data as -validation, and the rest ones' data as test. These data would be saved -separately under "/person_split". - -It will generate new files with the following structure: -├──person_split -│   ├── test -│   ├── train -│   └──valid -""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import os -import random -from data_split import read_data -from data_split import write_data - - -def person_split(whole_data, train_names, valid_names, test_names): # pylint: disable=redefined-outer-name - """Split data by person.""" - random.seed(30) - random.shuffle(whole_data) - train_data = [] # pylint: disable=redefined-outer-name - valid_data = [] # pylint: disable=redefined-outer-name - test_data = [] # pylint: disable=redefined-outer-name - for idx, data in enumerate(whole_data): # pylint: disable=redefined-outer-name,unused-variable - if data["name"] in train_names: - train_data.append(data) - elif data["name"] in valid_names: - valid_data.append(data) - elif data["name"] in test_names: - test_data.append(data) - print("train_length:" + str(len(train_data))) - print("valid_length:" + str(len(valid_data))) - print("test_length:" + str(len(test_data))) - return train_data, valid_data, test_data - - -if __name__ == "__main__": - data = read_data("./data/complete_data") - train_names = [ - "hyw", "shiyun", "tangsy", "dengyl", "jiangyh", "xunkai", "negative3", - "negative4", "negative5", "negative6" - ] - valid_names = ["lsj", "pengxl", "negative2", "negative7"] - test_names = ["liucx", "zhangxy", "negative1", "negative8"] - train_data, valid_data, test_data = person_split(data, train_names, - valid_names, test_names) - if not os.path.exists("./person_split"): - os.makedirs("./person_split") - write_data(train_data, "./person_split/train") - write_data(valid_data, "./person_split/valid") - write_data(test_data, "./person_split/test") diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_split_person_test.py b/tensorflow/lite/micro/examples/magic_wand/train/data_split_person_test.py deleted file mode 100644 index b4e0e004c1e..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_split_person_test.py +++ /dev/null @@ -1,52 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Test for data_split_person.py.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import unittest -from data_split_person import person_split -from data_split_person import read_data - - -class TestSplitPerson(unittest.TestCase): - - def setUp(self): # pylint: disable=g-missing-super-call - self.data = read_data("./data/complete_data") - - def test_person_split(self): - train_names = ["dengyl"] - valid_names = ["liucx"] - test_names = ["tangsy"] - dengyl_num = 63 - liucx_num = 63 - tangsy_num = 30 - train_data, valid_data, test_data = person_split(self.data, train_names, - valid_names, test_names) - self.assertEqual(len(train_data), dengyl_num) - self.assertEqual(len(valid_data), liucx_num) - self.assertEqual(len(test_data), tangsy_num) - self.assertIsInstance(train_data, list) - self.assertIsInstance(valid_data, list) - self.assertIsInstance(test_data, list) - self.assertIsInstance(train_data[0], dict) - self.assertIsInstance(valid_data[0], dict) - self.assertIsInstance(test_data[0], dict) - - -if __name__ == "__main__": - unittest.main() diff --git a/tensorflow/lite/micro/examples/magic_wand/train/data_split_test.py b/tensorflow/lite/micro/examples/magic_wand/train/data_split_test.py deleted file mode 100644 index 692dac3edb4..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/data_split_test.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Test for data_split.py.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import json -import unittest -from data_split import read_data -from data_split import split_data - - -class TestSplit(unittest.TestCase): - - def setUp(self): # pylint: disable=g-missing-super-call - self.data = read_data("./data/complete_data") - self.num_dic = {"wing": 0, "ring": 0, "slope": 0, "negative": 0} - with open("./data/complete_data", "r") as f: - lines = f.readlines() - self.num = len(lines) - - def test_read_data(self): - self.assertEqual(len(self.data), self.num) - self.assertIsInstance(self.data, list) - self.assertIsInstance(self.data[0], dict) - self.assertEqual(set(list(self.data[-1])), - set(["gesture", "accel_ms2_xyz", "name"])) - - def test_split_data(self): - with open("./data/complete_data", "r") as f: - lines = f.readlines() - for idx, line in enumerate(lines): # pylint: disable=unused-variable - dic = json.loads(line) - for ges in self.num_dic: - if dic["gesture"] == ges: - self.num_dic[ges] += 1 - train_data_0, valid_data_0, test_data_100 = split_data(self.data, 0, 0) - train_data_50, valid_data_50, test_data_0 = split_data(self.data, 0.5, 0.5) - train_data_60, valid_data_20, test_data_20 = split_data( - self.data, 0.6, 0.2) - len_60 = int(self.num_dic["wing"] * 0.6) + int( - self.num_dic["ring"] * 0.6) + int(self.num_dic["slope"] * 0.6) + int( - self.num_dic["negative"] * 0.6) - len_50 = int(self.num_dic["wing"] * 0.5) + int( - self.num_dic["ring"] * 0.5) + int(self.num_dic["slope"] * 0.5) + int( - self.num_dic["negative"] * 0.5) - len_20 = int(self.num_dic["wing"] * 0.2) + int( - self.num_dic["ring"] * 0.2) + int(self.num_dic["slope"] * 0.2) + int( - self.num_dic["negative"] * 0.2) - self.assertEqual(len(train_data_0), 0) - self.assertEqual(len(train_data_50), len_50) - self.assertEqual(len(train_data_60), len_60) - self.assertEqual(len(valid_data_0), 0) - self.assertEqual(len(valid_data_50), len_50) - self.assertEqual(len(valid_data_20), len_20) - self.assertEqual(len(test_data_100), self.num) - self.assertEqual(len(test_data_0), (self.num - 2 * len_50)) - self.assertEqual(len(test_data_20), (self.num - len_60 - len_20)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tensorflow/lite/micro/examples/magic_wand/train/netmodels/CNN/weights.h5 b/tensorflow/lite/micro/examples/magic_wand/train/netmodels/CNN/weights.h5 deleted file mode 100644 index 1d825b3aaf7..00000000000 Binary files a/tensorflow/lite/micro/examples/magic_wand/train/netmodels/CNN/weights.h5 and /dev/null differ diff --git a/tensorflow/lite/micro/examples/magic_wand/train/requirements.txt b/tensorflow/lite/micro/examples/magic_wand/train/requirements.txt deleted file mode 100644 index bb47d481d05..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -numpy==1.22.0 -tensorflow==2.9.3 diff --git a/tensorflow/lite/micro/examples/magic_wand/train/train.py b/tensorflow/lite/micro/examples/magic_wand/train/train.py deleted file mode 100644 index 1f496fdc77d..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/train.py +++ /dev/null @@ -1,200 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -# pylint: disable=redefined-outer-name -# pylint: disable=g-bad-import-order -"""Build and train neural networks.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import argparse -import datetime -import os -from data_load import DataLoader - -import numpy as np -import tensorflow as tf - -logdir = "logs/scalars/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") -tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=logdir) - - -def reshape_function(data, label): - reshaped_data = tf.reshape(data, [-1, 3, 1]) - return reshaped_data, label - - -def calculate_model_size(model): - print(model.summary()) - var_sizes = [ - np.product(list(map(int, v.shape))) * v.dtype.size - for v in model.trainable_variables - ] - print("Model size:", sum(var_sizes) / 1024, "KB") - - -def build_cnn(seq_length): - """Builds a convolutional neural network in Keras.""" - model = tf.keras.Sequential([ - tf.keras.layers.Conv2D( - 8, (4, 3), - padding="same", - activation="relu", - input_shape=(seq_length, 3, 1)), # output_shape=(batch, 128, 3, 8) - tf.keras.layers.MaxPool2D((3, 3)), # (batch, 42, 1, 8) - tf.keras.layers.Dropout(0.1), # (batch, 42, 1, 8) - tf.keras.layers.Conv2D(16, (4, 1), padding="same", - activation="relu"), # (batch, 42, 1, 16) - tf.keras.layers.MaxPool2D((3, 1), padding="same"), # (batch, 14, 1, 16) - tf.keras.layers.Dropout(0.1), # (batch, 14, 1, 16) - tf.keras.layers.Flatten(), # (batch, 224) - tf.keras.layers.Dense(16, activation="relu"), # (batch, 16) - tf.keras.layers.Dropout(0.1), # (batch, 16) - tf.keras.layers.Dense(4, activation="softmax") # (batch, 4) - ]) - model_path = os.path.join("./netmodels", "CNN") - print("Built CNN.") - if not os.path.exists(model_path): - os.makedirs(model_path) - model.load_weights("./netmodels/CNN/weights.h5") - return model, model_path - - -def build_lstm(seq_length): - """Builds an LSTM in Keras.""" - model = tf.keras.Sequential([ - tf.keras.layers.Bidirectional( - tf.keras.layers.LSTM(22), - input_shape=(seq_length, 3)), # output_shape=(batch, 44) - tf.keras.layers.Dense(4, activation="sigmoid") # (batch, 4) - ]) - model_path = os.path.join("./netmodels", "LSTM") - print("Built LSTM.") - if not os.path.exists(model_path): - os.makedirs(model_path) - return model, model_path - - -def load_data(train_data_path, valid_data_path, test_data_path, seq_length): - data_loader = DataLoader(train_data_path, - valid_data_path, - test_data_path, - seq_length=seq_length) - data_loader.format() - return data_loader.train_len, data_loader.train_data, data_loader.valid_len, \ - data_loader.valid_data, data_loader.test_len, data_loader.test_data - - -def build_net(args, seq_length): - if args.model == "CNN": - model, model_path = build_cnn(seq_length) - elif args.model == "LSTM": - model, model_path = build_lstm(seq_length) - else: - print("Please input correct model name.(CNN LSTM)") - return model, model_path - - -def train_net( - model, - model_path, # pylint: disable=unused-argument - train_len, # pylint: disable=unused-argument - train_data, - valid_len, - valid_data, # pylint: disable=unused-argument - test_len, - test_data, - kind): - """Trains the model.""" - calculate_model_size(model) - epochs = 50 - batch_size = 64 - model.compile(optimizer="adam", - loss="sparse_categorical_crossentropy", - metrics=["accuracy"]) - if kind == "CNN": - train_data = train_data.map(reshape_function) - test_data = test_data.map(reshape_function) - valid_data = valid_data.map(reshape_function) - test_labels = np.zeros(test_len) - idx = 0 - for data, label in test_data: # pylint: disable=unused-variable - test_labels[idx] = label.numpy() - idx += 1 - train_data = train_data.batch(batch_size).repeat() - valid_data = valid_data.batch(batch_size) - test_data = test_data.batch(batch_size) - model.fit(train_data, - epochs=epochs, - validation_data=valid_data, - steps_per_epoch=1000, - validation_steps=int((valid_len - 1) / batch_size + 1), - callbacks=[tensorboard_callback]) - loss, acc = model.evaluate(test_data) - pred = np.argmax(model.predict(test_data), axis=1) - confusion = tf.math.confusion_matrix(labels=tf.constant(test_labels), - predictions=tf.constant(pred), - num_classes=4) - print(confusion) - print("Loss {}, Accuracy {}".format(loss, acc)) - # Convert the model to the TensorFlow Lite format without quantization - converter = tf.lite.TFLiteConverter.from_keras_model(model) - tflite_model = converter.convert() - - # Save the model to disk - open("model.tflite", "wb").write(tflite_model) - - # Convert the model to the TensorFlow Lite format with quantization - converter = tf.lite.TFLiteConverter.from_keras_model(model) - converter.optimizations = [tf.lite.Optimize.DEFAULT] - tflite_model = converter.convert() - - # Save the model to disk - open("model_quantized.tflite", "wb").write(tflite_model) - - basic_model_size = os.path.getsize("model.tflite") - print("Basic model is %d bytes" % basic_model_size) - quantized_model_size = os.path.getsize("model_quantized.tflite") - print("Quantized model is %d bytes" % quantized_model_size) - difference = basic_model_size - quantized_model_size - print("Difference is %d bytes" % difference) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--model", "-m") - parser.add_argument("--person", "-p") - args = parser.parse_args() - - seq_length = 128 - - print("Start to load data...") - if args.person == "true": - train_len, train_data, valid_len, valid_data, test_len, test_data = \ - load_data("./person_split/train", "./person_split/valid", - "./person_split/test", seq_length) - else: - train_len, train_data, valid_len, valid_data, test_len, test_data = \ - load_data("./data/train", "./data/valid", "./data/test", seq_length) - - print("Start to build net...") - model, model_path = build_net(args, seq_length) - - print("Start training...") - train_net(model, model_path, train_len, train_data, valid_len, valid_data, - test_len, test_data, args.model) - - print("Training finished!") diff --git a/tensorflow/lite/micro/examples/magic_wand/train/train_magic_wand_model.ipynb b/tensorflow/lite/micro/examples/magic_wand/train/train_magic_wand_model.ipynb deleted file mode 100644 index 928287f654d..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/train_magic_wand_model.ipynb +++ /dev/null @@ -1,238 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "1BtkMGSYQOTQ" - }, - "source": [ - "# Train a gesture recognition model for microcontroller use" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "BaFfr7DHRmGF" - }, - "source": [ - "This notebook demonstrates how to train a 20kb gesture recognition model for [TensorFlow Lite for Microcontrollers](https://tensorflow.org/lite/microcontrollers/overview). It will produce the same model used in the [magic_wand](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/examples/magic_wand) example application.\n", - "\n", - "The model is designed to be used with [Google Colaboratory](https://colab.research.google.com).\n", - "\n", - "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", - " \u003ctd\u003e\n", - " \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/examples/magic_wand/train/train_magic_wand_model.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n", - " \u003c/td\u003e\n", - " \u003ctd\u003e\n", - " \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/examples/magic_wand/train/train_magic_wand_model.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n", - " \u003c/td\u003e\n", - "\u003c/table\u003e\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "xXgS6rxyT7Qk" - }, - "source": [ - "Training is much faster using GPU acceleration. Before you proceed, ensure you are using a GPU runtime by going to **Runtime -\u003e Change runtime type** and selecting **GPU**. Training will take around 5 minutes on a GPU runtime." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "LG6ErX5FRIaV" - }, - "source": [ - "## Configure dependencies\n", - "\n", - "Run the following cell to ensure the correct version of TensorFlow is used." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "STNft9TrfoVh" - }, - "source": [ - "We'll also clone the TensorFlow repository, which contains the training scripts, and copy them into our workspace." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "ygkWw73dRNda" - }, - "outputs": [], - "source": [ - "# Clone the repository from GitHub\n", - "!git clone --depth 1 -q https://github.com/tensorflow/tflite-micro\n", - "# Copy the training scripts into our workspace\n", - "!cp -r tflite-micro/tensorflow/lite/micro/examples/magic_wand/train train" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "pXI7R4RehFdU" - }, - "source": [ - "## Prepare the data\n", - "\n", - "Next, we'll download the data and extract it into the expected location within the training scripts' directory." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "W2Sg2AKzVr2L" - }, - "outputs": [], - "source": [ - "# Download the data we will use to train the model\n", - "!wget http://download.tensorflow.org/models/tflite/magic_wand/data.tar.gz\n", - "# Extract the data into the train directory\n", - "!tar xvzf data.tar.gz -C train 1\u003e/dev/null" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "DNjukI1Sgl2C" - }, - "source": [ - "We'll then run the scripts that split the data into training, validation, and test sets." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "XBqSVpi6Vxss" - }, - "outputs": [], - "source": [ - "# The scripts must be run from within the train directory\n", - "%cd train\n", - "# Prepare the data\n", - "!python data_prepare.py\n", - "# Split the data by person\n", - "!python data_split_person.py" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "5-cmVbFvhTvy" - }, - "source": [ - "## Load TensorBoard\n", - "\n", - "Now, we set up TensorBoard so that we can graph our accuracy and loss as training proceeds." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "CCx6SN9NWRPw" - }, - "outputs": [], - "source": [ - "# Load TensorBoard\n", - "%load_ext tensorboard\n", - "%tensorboard --logdir logs/scalars" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "ERC2Cr4PhaOl" - }, - "source": [ - "## Begin training\n", - "\n", - "The following cell will begin the training process. Training will take around 5 minutes on a GPU runtime. You'll see the metrics in TensorBoard after a few epochs." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "DXmQZgbuWQFO" - }, - "outputs": [], - "source": [ - "!python train.py --model CNN --person true" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "4gXbVzcXhvGD" - }, - "source": [ - "## Create a C source file\n", - "\n", - "The `train.py` script writes a model, `model.tflite`, to the training scripts' directory.\n", - "\n", - "In the following cell, we convert this model into a C++ source file we can use with TensorFlow Lite for Microcontrollers." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "8wgei4OGe3Nz" - }, - "outputs": [], - "source": [ - "# Install xxd if it is not available\n", - "!apt-get -qq install xxd\n", - "# Save the file as a C source file\n", - "!xxd -i model.tflite \u003e /content/model.cc\n", - "# Print the source file\n", - "!cat /content/model.cc" - ] - } - ], - "metadata": { - "accelerator": "GPU", - "colab": { - "collapsed_sections": [], - "name": "Train a gesture recognition model for microcontroller use", - "provenance": [], - "toc_visible": true - }, - "kernelspec": { - "display_name": "Python 3", - "name": "python3" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} diff --git a/tensorflow/lite/micro/examples/magic_wand/train/train_test.py b/tensorflow/lite/micro/examples/magic_wand/train/train_test.py deleted file mode 100644 index a4985770174..00000000000 --- a/tensorflow/lite/micro/examples/magic_wand/train/train_test.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Test for train.py.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import unittest - -import numpy as np -import tensorflow as tf -from train import build_cnn -from train import build_lstm -from train import load_data -from train import reshape_function - - -class TestTrain(unittest.TestCase): - - def setUp(self): # pylint: disable=g-missing-super-call - self.seq_length = 128 - self.train_len, self.train_data, self.valid_len, self.valid_data, \ - self.test_len, self.test_data = \ - load_data("./data/train", "./data/valid", "./data/test", - self.seq_length) - - def test_load_data(self): - self.assertIsInstance(self.train_data, tf.data.Dataset) - self.assertIsInstance(self.valid_data, tf.data.Dataset) - self.assertIsInstance(self.test_data, tf.data.Dataset) - - def test_build_net(self): - cnn, cnn_path = build_cnn(self.seq_length) - lstm, lstm_path = build_lstm(self.seq_length) - cnn_data = np.random.rand(60, 128, 3, 1) - lstm_data = np.random.rand(60, 128, 3) - cnn_prob = cnn(tf.constant(cnn_data, dtype="float32")).numpy() - lstm_prob = lstm(tf.constant(lstm_data, dtype="float32")).numpy() - self.assertIsInstance(cnn, tf.keras.Sequential) - self.assertIsInstance(lstm, tf.keras.Sequential) - self.assertEqual(cnn_path, "./netmodels/CNN") - self.assertEqual(lstm_path, "./netmodels/LSTM") - self.assertEqual(cnn_prob.shape, (60, 4)) - self.assertEqual(lstm_prob.shape, (60, 4)) - - def test_reshape_function(self): - for data, label in self.train_data: - original_data_shape = data.numpy().shape - original_label_shape = label.numpy().shape - break - self.train_data = self.train_data.map(reshape_function) - for data, label in self.train_data: - reshaped_data_shape = data.numpy().shape - reshaped_label_shape = label.numpy().shape - break - self.assertEqual( - reshaped_data_shape, - (int(original_data_shape[0] * original_data_shape[1] / 3), 3, 1)) - self.assertEqual(reshaped_label_shape, original_label_shape) - - -if __name__ == "__main__": - unittest.main() diff --git a/tensorflow/lite/micro/tools/ci_build/test_project_generation.sh b/tensorflow/lite/micro/tools/ci_build/test_project_generation.sh index 5fdd87baea5..8814a60e933 100755 --- a/tensorflow/lite/micro/tools/ci_build/test_project_generation.sh +++ b/tensorflow/lite/micro/tools/ci_build/test_project_generation.sh @@ -52,7 +52,7 @@ source ${TENSORFLOW_ROOT}tensorflow/lite/micro/tools/ci_build/helper_functions.s # Next, we test that create_tflm_tree can be used to build example binaries. We # perform this test with a Makefile (instead of bazel) because make is more # commonly understood and because we use make for cross-compilation. -EXAMPLES="-e hello_world -e magic_wand -e micro_speech -e person_detection" +EXAMPLES="-e hello_world -e micro_speech -e person_detection" TEST_OUTPUT_DIR="$(mktemp -d)" diff --git a/tensorflow/lite/micro/tools/make/targets/arc_custom_makefile.inc b/tensorflow/lite/micro/tools/make/targets/arc_custom_makefile.inc index 1e6287d761c..84e2d030e24 100644 --- a/tensorflow/lite/micro/tools/make/targets/arc_custom_makefile.inc +++ b/tensorflow/lite/micro/tools/make/targets/arc_custom_makefile.inc @@ -62,7 +62,6 @@ MICROLITE_TEST_SRCS := $(filter-out $(EXCLUDED_TESTS), $(MICROLITE_TEST_SRCS)) EXCLUDED_EXAMPLE_TESTS := \ $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/hello_world/Makefile.inc \ - $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/Makefile.inc \ $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/memory_footprint/Makefile.inc \ $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/micro_speech/Makefile.inc \ $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/network_tester/Makefile.inc \ diff --git a/tensorflow/lite/micro/tools/make/targets/bluepill_makefile.inc b/tensorflow/lite/micro/tools/make/targets/bluepill_makefile.inc index fb86db7e014..c14bda496e7 100644 --- a/tensorflow/lite/micro/tools/make/targets/bluepill_makefile.inc +++ b/tensorflow/lite/micro/tools/make/targets/bluepill_makefile.inc @@ -73,7 +73,6 @@ EXCLUDED_TESTS += $(TENSORFLOW_ROOT)tensorflow/lite/micro/flatbuffer_utils_test. MICROLITE_TEST_SRCS := $(filter-out $(EXCLUDED_TESTS), $(MICROLITE_TEST_SRCS)) EXCLUDED_EXAMPLE_TESTS := \ - $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/Makefile.inc \ $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/micro_speech/Makefile.inc MICRO_LITE_EXAMPLE_TESTS := $(filter-out $(EXCLUDED_EXAMPLE_TESTS), $(MICRO_LITE_EXAMPLE_TESTS)) diff --git a/tensorflow/lite/micro/tools/make/targets/stm32f4_makefile.inc b/tensorflow/lite/micro/tools/make/targets/stm32f4_makefile.inc index 7ffd7ece160..21db90549a5 100644 --- a/tensorflow/lite/micro/tools/make/targets/stm32f4_makefile.inc +++ b/tensorflow/lite/micro/tools/make/targets/stm32f4_makefile.inc @@ -94,7 +94,6 @@ EXCLUDED_TESTS += ${TENSORFLOW_ROOT}tensorflow/lite/micro/flatbuffer_utils_test. MICROLITE_TEST_SRCS := $(filter-out $(EXCLUDED_TESTS), $(MICROLITE_TEST_SRCS)) EXCLUDED_EXAMPLE_TESTS := \ - ${TENSORFLOW_ROOT}tensorflow/lite/micro/examples/magic_wand/Makefile.inc \ ${TENSORFLOW_ROOT}tensorflow/lite/micro/examples/micro_speech/Makefile.inc MICRO_LITE_EXAMPLE_TESTS := $(filter-out $(EXCLUDED_EXAMPLE_TESTS), $(MICRO_LITE_EXAMPLE_TESTS)) diff --git a/tensorflow/lite/micro/tools/make/targets/xtensa_makefile.inc b/tensorflow/lite/micro/tools/make/targets/xtensa_makefile.inc index 62af4b5020f..8d970c72bb9 100644 --- a/tensorflow/lite/micro/tools/make/targets/xtensa_makefile.inc +++ b/tensorflow/lite/micro/tools/make/targets/xtensa_makefile.inc @@ -84,7 +84,6 @@ MICROLITE_TEST_SRCS := $(filter-out $(EXCLUDED_TESTS), $(MICROLITE_TEST_SRCS)) EXCLUDED_EXAMPLE_TESTS := \ $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/hello_world/Makefile.inc \ $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/image_recognition_experimental/Makefile.inc \ - $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/magic_wand/Makefile.inc \ $(TENSORFLOW_ROOT)tensorflow/lite/micro/examples/network_tester/Makefile.inc MICRO_LITE_EXAMPLE_TESTS := $(filter-out $(EXCLUDED_EXAMPLE_TESTS), $(MICRO_LITE_EXAMPLE_TESTS)) MICRO_LITE_EXAMPLE_TESTS += $(shell find $(TENSORFLOW_ROOT)third_party/xtensa/examples/ -name Makefile.inc) diff --git a/tensorflow/lite/micro/tools/project_generation/Makefile b/tensorflow/lite/micro/tools/project_generation/Makefile index 199d57192d7..092ba7e07f4 100644 --- a/tensorflow/lite/micro/tools/project_generation/Makefile +++ b/tensorflow/lite/micro/tools/project_generation/Makefile @@ -117,10 +117,6 @@ hello_world: libtflm @mkdir -p $(BINDIR) $(CXX) $(CXXFLAGS) $(HELLO_WORLD_SRCS) $(HELLO_WORLD_INCLUDES) $(LIB) -o $(BINDIR)/$@ -magic_wand: libtflm - @mkdir -p $(BINDIR) - $(CXX) $(CXXFLAGS) $(wildcard examples/magic_wand/*.cc) $(INCLUDES) $(LIB) -o $(BINDIR)/$@ - MICRO_SPEECH_SRCS := $(wildcard examples/micro_speech/*.cc) MICRO_SPEECH_SRCS += $(wildcard examples/micro_speech/*/*.cc) MICRO_SPEECH_THIRD_PARTY_SRCS := @@ -138,4 +134,4 @@ person_detection: libtflm @mkdir -p $(BINDIR) $(CXX) $(CXXFLAGS) $(PERSON_DETECTION_SRCS) $(PERSON_DETECTION_THIRD_PARTY_SRCS) $(PERSON_DETECTION_INCLUDES) $(LIB) -o $(BINDIR)/$@ -examples: hello_world magic_wand micro_speech person_detection +examples: hello_world micro_speech person_detection