diff --git a/GUIDE.md b/GUIDE.md index 6b968a0..4e46568 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -22,11 +22,10 @@ Here's the basic plan: build a 32-bit version of [Protobuf](https://github.com/g 1. [Install basic dependencies](#1-install-basic-dependencies) 2. [Build Protobuf](#2-build-protobuf) -3. [Build gRPC](#3-build-grpc) -3. [Build Bazel](#4-build-bazel) -4. [Install USB Memory as Swap](#5-install-a-memory-drive-as-swap-for-compiling) -5. [Compiling TensorFlow](#6-compiling-tensorflow) -6. [Cleaning Up](#7-cleaning-up) +3. [Install USB Memory as Swap](#3-install-a-memory-drive-as-swap-for-compiling) +4. [Build Bazel](#4-build-bazel) +5. [Compiling TensorFlow](#5-compiling-tensorflow) +6. [Cleaning Up](#6-cleaning-up) 7. [References](#references) ## The Build @@ -50,7 +49,9 @@ sudo apt-get install autoconf automake libtool maven For Bazel: ```shell -sudo apt-get install pkg-config zip g++ zlib1g-dev unzip +sudo apt-get install pkg-config zip g++ zlib1g-dev unzip openjdk-8-jdk +# Select the java-8-openjdk option for the update-alternatives command +sudo update-alternatives --config java ``` For TensorFlow: @@ -58,11 +59,11 @@ For TensorFlow: ``` # For Python 2.7 sudo apt-get install python-pip python-numpy swig python-dev -sudo pip install wheel +pip install --user wheel # For Python 3.3+ sudo apt-get install python3-pip python3-numpy swig python3-dev -sudo pip3 install wheel +pip3 install --user wheel ``` To be able to take advantage of certain optimization flags: @@ -92,7 +93,7 @@ Now move into the new `protobuf` directory, configure it, and `make` it. _Note: ```shell cd protobuf -git checkout v3.0.0 +git checkout v3.1.0 ./autogen.sh ./configure make -j 4 @@ -106,13 +107,74 @@ Great! You should now have `protoc` installed in `/usr/local/bin`, and should be protoc --version ``` -Now that we have the `protoc` compiler, we can start building Bazel. Let's move up a directory and do that. +Now that we have the `protoc` compiler, let's install a USB stick as additional swap memory. ``` cd .. ``` -### 3. Build Bazel +### 3. Install a Memory Drive as Swap for Compiling + +In order to succesfully build TensorFlow, your Raspberry Pi needs a little bit more memory to fall back on. Fortunately, this process is pretty straightforward. Grab a USB storage drive that has at least 1GB of memory. I used a flash drive I could live without that carried no important data. That said, we're only going to be using the drive as swap while we compile, so this process shouldn't do too much damage to a relatively new USB drive. + +First, put insert your USB drive, and find the `/dev/XXX` path for the device. + +```shell +sudo blkid +``` + +As an example, my drive's path was `/dev/sda1` + +Once you've found your device, unmount it by using the `umount` command. + +```shell +sudo umount /dev/XXX +``` + +Then format your device to be swap: + +```shell +sudo mkswap /dev/XXX +``` + +If the previous command outputted an alphanumeric UUID, copy that now. Otherwise, find the UUID by running `blkid` again. Copy the UUID associated with `/dev/XXX` + +```shell +sudo blkid +``` + +Now edit your `/etc/fstab` file to register your swap file. (I'm a Vim guy, but Nano is installed by default) + +```shell +sudo nano /etc/fstab +``` + +On a separate line, enter the following information. Replace the X's with the UUID (without quotes) + +```bash +UUID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX none swap sw,pri=5 0 0 +``` + +Save `/etc/fstab`, exit your text editor, and run the following command: + +```shell +sudo swapon -a +``` + +If you get an error claiming it can't find your UUID, go back and edit `/etc/fstab`. Replace the `UUID=XXX..` bit with the original `/dev/XXX` information. + +```shell +sudo nano /etc/fstab +``` + +```bash +# Replace the UUID with /dev/XXX +/dev/XXX none swap sw,pri=5 0 0 +``` + +Alright! You've got swap! Don't throw out the `/dev/XXX` information yet- you'll need it to remove the device safely later on. + +### 4. Build Bazel To build [Bazel](https://github.com/bazelbuild/bazel), we're going to need to download a zip file containing a distribution archive. Let's do that now and extract it into a new directory called `bazel`: @@ -155,7 +217,7 @@ Finally, we have to add one thing to `tools/cpp/cc_configure.bzl` - open it up f nano tools/cpp/cc_configure.bzl ``` -Place the line `return "arm"` around line 141 (at the beginning of the `_get_cpu_value` function): +Place the line `return "arm"` around line 133 (at the beginning of the `_get_cpu_value` function): ```shell ... @@ -179,7 +241,7 @@ sudo cp output/bazel /usr/local/bin/bazel To make sure it's working properly, run `bazel` on the command line and verify it prints help text. Note: this may take 15-30 seconds to run, so be patient! ```shell -$ bazel +bazel Usage: bazel ... @@ -216,73 +278,12 @@ Move out of the `bazel` directory, and we'll move onto the next step. cd .. ``` -### 4. Install a Memory Drive as Swap for Compiling - -In order to succesfully build TensorFlow, your Raspberry Pi needs a little bit more memory to fall back on. Fortunately, this process is pretty straightforward. Grab a USB storage drive that has at least 1GB of memory. I used a flash drive I could live without that carried no important data. That said, we're only going to be using the drive as swap while we compile, so this process shouldn't do too much damage to a relatively new USB drive. - -First, put insert your USB drive, and find the `/dev/XXX` path for the device. - -```shell -sudo blkid -``` - -As an example, my drive's path was `/dev/sda1` - -Once you've found your device, unmount it by using the `umount` command. - -```shell -sudo umount /dev/XXX -``` - -Then format your device to be swap: - -```shell -sudo mkswap /dev/XXX -``` - -If the previous command outputted an alphanumeric UUID, copy that now. Otherwise, find the UUID by running `blkid` again. Copy the UUID associated with `/dev/XXX` - -```shell -sudo blkid -``` - -Now edit your `/etc/fstab` file to register your swap file. (I'm a Vim guy, but Nano is installed by default) - -```shell -sudo nano /etc/fstab -``` - -On a separate line, enter the following information. Replace the X's with the UUID (without quotes) - -```bash -UUID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX none swap sw,pri=5 0 0 -``` - -Save `/etc/fstab`, exit your text editor, and run the following command: - -```shell -sudo swapon -a -``` - -If you get an error claiming it can't find your UUID, go back and edit `/etc/fstab`. Replace the `UUID=XXX..` bit with the original `/dev/XXX` information. - -```shell -sudo nano /etc/fstab -``` - -```bash -# Replace the UUID with /dev/XXX -/dev/XXX none swap sw,pri=5 0 0 -``` - -Alright! You've got swap! Don't throw out the `/dev/XXX` information yet- you'll need it to remove the device safely later on. - ### 5. Compiling TensorFlow First things first, clone the TensorFlow repository and move into the newly created directory. ```shell -git clone --recurse-submodules https://github.com/tensorflow/tensorflow +git clone --recurse-submodules https://github.com/tensorflow/tensorflow.git cd tensorflow ``` @@ -297,7 +298,7 @@ grep -Rl 'lib64' | xargs sed -i 's/lib64/lib/g' Next, we need to delete a particular line in `tensorflow/core/platform/platform.h`. Open up the file in your favorite text editor: ```shell -$ sudo nano tensorflow/core/platform/platform.h +sudo nano tensorflow/core/platform/platform.h ``` Now, scroll down toward the bottom and delete the following line containing `#define IS_MOBILE_PLATFORM` (around line 48): @@ -311,10 +312,25 @@ Now, scroll down toward the bottom and delete the following line containing `#de This keeps our Raspberry Pi device (which has an ARM CPU) from being recognized as a mobile device. +Finally, we have to adjust the protocol to access the Numeric JS library- for some reason the Cloudflare security certificates don't work properly over `https`. We'll need to fix this in the Bazel `WORKSPACE` file: + +```shell +sudo nano WORKSPACE +``` + +Around line 283, change `https` to `http`: + +``` +http_file( + name = "numericjs_numeric_min_js", + url = "http://cdnjs.cloudflare.com/ajax/libs/numeric/1.2.6/numeric.min.js", +) +``` + Now let's configure the build: ```shell -$ ./configure +./configure Please specify the location of python. [Default is /usr/bin/python]: /usr/bin/python Do you wish to build TensorFlow with Google Cloud Platform support? [y/N] N @@ -323,9 +339,9 @@ Do you wish to build TensorFlow with Hadoop File System support? [y/N] N Please input the desired Python library path to use. Default is [/usr/local/lib/python2.7/dist-packages] Do you wish to build TensorFlow with OpenCL support? [y/N] N Do you wish to build TensorFlow with GPU support? [y/N] -N``` +``` -_Note: if you want to build for Python 3, specify `/usr/bin/python3` for Python's location._ +_Note: if you want to build for Python 3, specify `/usr/bin/python3` for Python's location and `/usr/local/lib/python3.4/dist-packages` for the Python library path._ Now we can use it to build TensorFlow! **Warning: This takes a really, really long time. Several hours.** @@ -344,7 +360,7 @@ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg And then install it! ```shell -sudo pip install /tmp/tensorflow_pkg/tensorflow-0.12.1-cp27-none-linux_armv7l.whl +pip install --user /tmp/tensorflow_pkg/tensorflow-1.0.1-cp27-none-linux_armv7l.whl ``` ### 6. Cleaning Up diff --git a/README.md b/README.md index a6a926d..6aba298 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ## Donate -If you find the binaries and instructions in this repository useful, [please consider donating to help keep this repository maintained](https://pledgie.com/campaigns/33260). It takes hours of work for each new version of TensorFlow, as well as responding to issues and pull requests. +If you find the binaries and instructions in this repository useful, [please consider donating to help keep this repository maintained](https://pledgie.com/campaigns/33260). It takes hours of work to compile each new version of TensorFlow, in addition to time spent responding to issues and pull requests. ## Intro @@ -25,25 +25,37 @@ This is the easiest way to get TensorFlow onto your Raspberry Pi 3. Note that cu First, install the dependencies for TensorFlow: ```shell -$ sudo apt-get update +sudo apt-get update # For Python 2.7 -$ sudo apt-get install python-pip python-dev +sudo apt-get install python-pip python-dev # For Python 3.3+ -$ sudo apt-get install python3-pip python3-dev +sudo apt-get install python3-pip python3-dev ``` Next, download the wheel file from this repository and install it: ```shell # For Python 2.7 -$ wget https://github.com/samjabrahams/tensorflow-on-raspberry-pi/releases/download/v0.12.1/tensorflow-0.12.1-cp27-none-linux_armv7l.whl -$ sudo pip install tensorflow-0.12.1-cp27-none-linux_armv7l.whl +wget https://github.com/samjabrahams/tensorflow-on-raspberry-pi/releases/download/v1.0.1/tensorflow-1.0.1-cp27-none-linux_armv7l.whl +pip install --user tensorflow-1.0.1-cp27-none-linux_armv7l.whl + +# For Python 3.4 +wget https://github.com/samjabrahams/tensorflow-on-raspberry-pi/releases/download/v1.0.1/tensorflow-1.0.1-cp34-cp34m-linux_armv7l.whl +pip3 install --user tensorflow-1.0.1-cp34-cp34m-linux_armv7l.whl +``` + +Finally, we need to reinstall the `mock` library to keep it from throwing an error when we import TensorFlow: + +```shell +# For Python 2.7 +pip uninstall mock +pip install --user mock # For Python 3.3+ -$ wget https://github.com/samjabrahams/tensorflow-on-raspberry-pi/releases/download/v0.12.1/tensorflow-0.12.1-py3-none-any.whl -$ sudo pip3 install tensorflow-0.12.1-py3-none-any.whl +pip3 uninstall mock +pip3 install --user mock ``` And that should be it! @@ -56,20 +68,22 @@ Instructions on setting up a Docker image to run on Raspberry Pi are being maint _This section will attempt to maintain a list of remedies for problems that may occur while installing from `pip`_ -#### "tensorflow-0.11-cp27-none-linux_armv7l.whl is not a supported wheel on this platform." +#### "tensorflow-1.0.1-cp27-none-linux_armv7l.whl is not a supported wheel on this platform." This wheel was built with Python 2.7, and can't be installed with a version of `pip` that uses Python 3. If you get the above message, try running the following command instead: ``` -$ sudo pip2 install tensorflow-0.12.1-cp27-none-linux_armv7l.whl +sudo pip2 install tensorflow-1.0.1-cp27-none-linux_armv7l.whl ``` -Vice-versa for trying to install the Python 3 wheel. If you get the error "tensorflow-0.11-py3-none-any.whl is not a supported wheel on this platform.", try this command: +Vice-versa for trying to install the Python 3 wheel. If you get the error "tensorflow-1.0.1-cp34-cp34m-any.whl is not a supported wheel on this platform.", try this command: ``` -$ sudo pip3 install tensorflow-0.12.1-py3-none-any.whl +pip3 install --user tensorflow-1.0.1-cp34-cp34m-linux_armv7l.whl ``` +**Note: the provided binaries are for Python 2.7 and 3.4 _only_. If you've installed Python 3.5/3.6 from source on your machine, you'll need to either explicitly install these wheels for 3.4, or you'll need to build TensorFlow [from source](GUIDE.md). Once there's an officially supported installation of Python 3.5+, this repo will start including wheels for those versions.** + ## Building from Source [_Step-by-step guide_](GUIDE.md) diff --git a/benchmarks/inceptionv3/main.cc b/benchmarks/inceptionv3/main.cc deleted file mode 100644 index d452b0f..0000000 --- a/benchmarks/inceptionv3/main.cc +++ /dev/null @@ -1,366 +0,0 @@ -/* Copyright 2015 Google Inc. 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. -==============================================================================*/ - -// A minimal but useful C++ example showing how to load an Imagenet-style object -// recognition TensorFlow model, prepare input images for it, run them through -// the graph, and interpret the results. -// -// It's designed to have as few dependencies and be as clear as possible, so -// it's more verbose than it could be in production code. In particular, using -// auto for the types of a lot of the returned values from TensorFlow calls can -// remove a lot of boilerplate, but I find the explicit types useful in sample -// code to make it simple to look up the classes involved. -// -// To use it, compile and then run in a working directory with the -// learning/brain/tutorials/label_image/data/ folder below it, and you should -// see the top five labels for the example Lena image output. You can then -// customize it to use your own models or images by changing the file names at -// the top of the main() function. -// -// The googlenet_graph.pb file included by default is created from Inception. -// -// This file has been modified by Sam Abrahams to print out basic run-time -// information. These modifications have been surrounded with the comments: -// "MODIFICATION BY SAM ABRAHAMS" and "END OF MODIFICATION" - -#include - -// MODIFICATION BY SAM ABRAHAMS -#include -#include -// END OF MODIFICATION - -#include "tensorflow/cc/ops/const_op.h" -#include "tensorflow/cc/ops/image_ops.h" -#include "tensorflow/cc/ops/standard_ops.h" -#include "tensorflow/core/framework/graph.pb.h" -#include "tensorflow/core/framework/tensor.h" -#include "tensorflow/core/graph/default_device.h" -#include "tensorflow/core/graph/graph_def_builder.h" -#include "tensorflow/core/lib/core/errors.h" -#include "tensorflow/core/lib/core/stringpiece.h" -#include "tensorflow/core/lib/core/threadpool.h" -#include "tensorflow/core/lib/io/path.h" -#include "tensorflow/core/lib/strings/stringprintf.h" -#include "tensorflow/core/platform/init_main.h" -#include "tensorflow/core/platform/logging.h" -#include "tensorflow/core/platform/types.h" -#include "tensorflow/core/public/session.h" -#include "tensorflow/core/util/command_line_flags.h" - -// These are all common classes it's handy to reference with no namespace. -using tensorflow::Flag; -using tensorflow::Tensor; -using tensorflow::Status; -using tensorflow::string; -using tensorflow::int32; - -// Takes a file name, and loads a list of labels from it, one per line, and -// returns a vector of the strings. It pads with empty strings so the length -// of the result is a multiple of 16, because our model expects that. -Status ReadLabelsFile(string file_name, std::vector* result, - size_t* found_label_count) { - std::ifstream file(file_name); - if (!file) { - return tensorflow::errors::NotFound("Labels file ", file_name, - " not found."); - } - result->clear(); - string line; - while (std::getline(file, line)) { - result->push_back(line); - } - *found_label_count = result->size(); - const int padding = 16; - while (result->size() % padding) { - result->emplace_back(); - } - return Status::OK(); -} - -// Given an image file name, read in the data, try to decode it as an image, -// resize it to the requested size, and then scale the values as desired. -Status ReadTensorFromImageFile(string file_name, const int input_height, - const int input_width, const float input_mean, - const float input_std, - std::vector* out_tensors) { - tensorflow::GraphDefBuilder b; - string input_name = "file_reader"; - string output_name = "normalized"; - tensorflow::Node* file_reader = - tensorflow::ops::ReadFile(tensorflow::ops::Const(file_name, b.opts()), - b.opts().WithName(input_name)); - // Now try to figure out what kind of file it is and decode it. - const int wanted_channels = 3; - tensorflow::Node* image_reader; - if (tensorflow::StringPiece(file_name).ends_with(".png")) { - image_reader = tensorflow::ops::DecodePng( - file_reader, - b.opts().WithAttr("channels", wanted_channels).WithName("png_reader")); - } else { - // Assume if it's not a PNG then it must be a JPEG. - image_reader = tensorflow::ops::DecodeJpeg( - file_reader, - b.opts().WithAttr("channels", wanted_channels).WithName("jpeg_reader")); - } - // Now cast the image data to float so we can do normal math on it. - tensorflow::Node* float_caster = tensorflow::ops::Cast( - image_reader, tensorflow::DT_FLOAT, b.opts().WithName("float_caster")); - // The convention for image ops in TensorFlow is that all images are expected - // to be in batches, so that they're four-dimensional arrays with indices of - // [batch, height, width, channel]. Because we only have a single image, we - // have to add a batch dimension of 1 to the start with ExpandDims(). - tensorflow::Node* dims_expander = tensorflow::ops::ExpandDims( - float_caster, tensorflow::ops::Const(0, b.opts()), b.opts()); - // Bilinearly resize the image to fit the required dimensions. - tensorflow::Node* resized = tensorflow::ops::ResizeBilinear( - dims_expander, tensorflow::ops::Const({input_height, input_width}, - b.opts().WithName("size")), - b.opts()); - // Subtract the mean and divide by the scale. - tensorflow::ops::Div( - tensorflow::ops::Sub( - resized, tensorflow::ops::Const({input_mean}, b.opts()), b.opts()), - tensorflow::ops::Const({input_std}, b.opts()), - b.opts().WithName(output_name)); - - // This runs the GraphDef network definition that we've just constructed, and - // returns the results in the output tensor. - tensorflow::GraphDef graph; - TF_RETURN_IF_ERROR(b.ToGraphDef(&graph)); - std::unique_ptr session( - tensorflow::NewSession(tensorflow::SessionOptions())); - TF_RETURN_IF_ERROR(session->Create(graph)); - TF_RETURN_IF_ERROR(session->Run({}, {output_name}, {}, out_tensors)); - return Status::OK(); -} - -// Reads a model graph definition from disk, and creates a session object you -// can use to run it. -Status LoadGraph(string graph_file_name, - std::unique_ptr* session) { - tensorflow::GraphDef graph_def; - Status load_graph_status = - ReadBinaryProto(tensorflow::Env::Default(), graph_file_name, &graph_def); - if (!load_graph_status.ok()) { - return tensorflow::errors::NotFound("Failed to load compute graph at '", - graph_file_name, "'"); - } - session->reset(tensorflow::NewSession(tensorflow::SessionOptions())); - Status session_create_status = (*session)->Create(graph_def); - if (!session_create_status.ok()) { - return session_create_status; - } - return Status::OK(); -} - -// Analyzes the output of the Inception graph to retrieve the highest scores and -// their positions in the tensor, which correspond to categories. -Status GetTopLabels(const std::vector& outputs, int how_many_labels, - Tensor* indices, Tensor* scores) { - tensorflow::GraphDefBuilder b; - string output_name = "top_k"; - tensorflow::ops::TopKV2(tensorflow::ops::Const(outputs[0], b.opts()), - tensorflow::ops::Const(how_many_labels, b.opts()), - b.opts().WithName(output_name)); - // This runs the GraphDef network definition that we've just constructed, and - // returns the results in the output tensors. - tensorflow::GraphDef graph; - TF_RETURN_IF_ERROR(b.ToGraphDef(&graph)); - std::unique_ptr session( - tensorflow::NewSession(tensorflow::SessionOptions())); - TF_RETURN_IF_ERROR(session->Create(graph)); - // The TopK node returns two outputs, the scores and their original indices, - // so we have to append :0 and :1 to specify them both. - std::vector out_tensors; - TF_RETURN_IF_ERROR(session->Run({}, {output_name + ":0", output_name + ":1"}, - {}, &out_tensors)); - *scores = out_tensors[0]; - *indices = out_tensors[1]; - return Status::OK(); -} - -// Given the output of a model run, and the name of a file containing the labels -// this prints out the top five highest-scoring values. -Status PrintTopLabels(const std::vector& outputs, - string labels_file_name) { - std::vector labels; - size_t label_count; - Status read_labels_status = - ReadLabelsFile(labels_file_name, &labels, &label_count); - if (!read_labels_status.ok()) { - LOG(ERROR) << read_labels_status; - return read_labels_status; - } - const int how_many_labels = std::min(5, static_cast(label_count)); - Tensor indices; - Tensor scores; - TF_RETURN_IF_ERROR(GetTopLabels(outputs, how_many_labels, &indices, &scores)); - tensorflow::TTypes::Flat scores_flat = scores.flat(); - tensorflow::TTypes::Flat indices_flat = indices.flat(); - for (int pos = 0; pos < how_many_labels; ++pos) { - const int label_index = indices_flat(pos); - const float score = scores_flat(pos); - LOG(INFO) << labels[label_index] << " (" << label_index << "): " << score; - } - return Status::OK(); -} - -// This is a testing function that returns whether the top label index is the -// one that's expected. -Status CheckTopLabel(const std::vector& outputs, int expected, - bool* is_expected) { - *is_expected = false; - Tensor indices; - Tensor scores; - const int how_many_labels = 1; - TF_RETURN_IF_ERROR(GetTopLabels(outputs, how_many_labels, &indices, &scores)); - tensorflow::TTypes::Flat indices_flat = indices.flat(); - if (indices_flat(0) != expected) { - LOG(ERROR) << "Expected label #" << expected << " but got #" - << indices_flat(0); - *is_expected = false; - } else { - *is_expected = true; - } - return Status::OK(); -} - -int main(int argc, char* argv[]) { - // These are the command-line flags the program can understand. - // They define where the graph and input data is located, and what kind of - // input the model expects. If you train your own model, or use something - // other than GoogLeNet you'll need to update these. - string image = "tensorflow/examples/label_image/data/grace_hopper.jpg"; - string graph = - "tensorflow/examples/label_image/data/" - "tensorflow_inception_graph.pb"; - string labels = - "tensorflow/examples/label_image/data/" - "imagenet_comp_graph_label_strings.txt"; - int32 input_width = 299; - int32 input_height = 299; - int32 input_mean = 128; - int32 input_std = 128; - string input_layer = "Mul"; - string output_layer = "softmax"; - bool self_test = false; - string root_dir = ""; - const bool parse_result = tensorflow::ParseFlags( - &argc, argv, {Flag("image", &image), // - Flag("graph", &graph), // - Flag("labels", &labels), // - Flag("input_width", &input_width), // - Flag("input_height", &input_height), // - Flag("input_mean", &input_mean), // - Flag("input_std", &input_std), // - Flag("input_layer", &input_layer), // - Flag("output_layer", &output_layer), // - Flag("self_test", &self_test), // - Flag("root_dir", &root_dir)}); - if (!parse_result) { - LOG(ERROR) << "Error parsing command-line flags."; - return -1; - } - - // We need to call this to set up global state for TensorFlow. - tensorflow::port::InitMain(argv[0], &argc, &argv); - if (argc > 1) { - LOG(ERROR) << "Unknown argument " << argv[1]; - return -1; - } - - // MODIFICATION BY SAM ABRAHAMS - struct timeval stp; - gettimeofday(&stp, NULL); - long int sms = stp.tv_sec * 1000 + stp.tv_usec / 1000; - // END OF MODIFICATION - - // First we load and initialize the model. - std::unique_ptr session; - string graph_path = tensorflow::io::JoinPath(root_dir, graph); - Status load_graph_status = LoadGraph(graph_path, &session); - if (!load_graph_status.ok()) { - LOG(ERROR) << load_graph_status; - return -1; - } - - // Get the image from disk as a float array of numbers, resized and normalized - // to the specifications the main graph expects. - std::vector resized_tensors; - string image_path = tensorflow::io::JoinPath(root_dir, image); - Status read_tensor_status = - ReadTensorFromImageFile(image_path, input_height, input_width, input_mean, - input_std, &resized_tensors); - if (!read_tensor_status.ok()) { - LOG(ERROR) << read_tensor_status; - return -1; - } - const Tensor& resized_tensor = resized_tensors[0]; - - // MODIFICATION BY SAM ABRAHAMS - struct timeval mtp; - gettimeofday(&mtp, NULL); - long int mms = mtp.tv_sec * 1000 + mtp.tv_usec / 1000; - // END OF MODIFICATION - - // Actually run the image through the model. - std::vector outputs; - Status run_status = session->Run({{input_layer, resized_tensor}}, - {output_layer}, {}, &outputs); - if (!run_status.ok()) { - LOG(ERROR) << "Running model failed: " << run_status; - return -1; - } - - // This is for automated testing to make sure we get the expected result with - // the default settings. We know that label 866 (military uniform) should be - // the top label for the Admiral Hopper image. - if (self_test) { - bool expected_matches; - Status check_status = CheckTopLabel(outputs, 866, &expected_matches); - if (!check_status.ok()) { - LOG(ERROR) << "Running check failed: " << check_status; - return -1; - } - if (!expected_matches) { - LOG(ERROR) << "Self-test failed!"; - return -1; - } - } - - // MODIFICATION BY SAM ABRAHAMS - struct timeval etp; - gettimeofday(&etp, NULL); - long int ems = etp.tv_sec * 1000 + etp.tv_usec / 1000; - // END OF MODIFICATION - - // Do something interesting with the results we've generated. - Status print_status = PrintTopLabels(outputs, labels); - if (!print_status.ok()) { - LOG(ERROR) << "Running print failed: " << print_status; - return -1; - } - - // MODIFICATION BY SAM ABRAHAMS - long int graph_time = mms - sms; - long int eval_time = ems - mms; - - printf ("%d milliseconds to build graph\n", graph_time); - printf ("%d milliseconds to evaluate image\n", eval_time); - // END OF MODIFICATION - - return 0; -}