1
1
# TensorFlow + Node.js
2
2
3
- [ TensorFlow] ( https://tensorflow.org ) is Google's machine learning runtime.
4
- It is implemented as C++ runtime, along with Python bindings and framework
5
- out-of-the-box to support building a variety of models, especially neural
6
- networks for deep learning.
3
+ [ TensorFlow] ( https://tensorflow.org ) is Google's machine learning runtime. It
4
+ is implemented as C++ runtime, along with Python framework to support building
5
+ a variety of models, especially neural networks for deep learning.
7
6
8
7
It is interesting to be able to use TensorFlow in a node.js application
9
8
using just JavaScript (or TypeScript if that's your preference). However,
10
9
the Python functionality is vast (several ops, estimator implementations etc.)
11
- and continually expanding. Instead, it would be interesting to consider
10
+ and continually expanding. Instead, it would be more practical to consider
12
11
building Graphs and training models in Python, and then consuming those
13
12
for runtime use-cases (like prediction or inference) in a pure node.js and
14
- Python-free deployment. This is what this node module offers .
13
+ Python-free deployment. This is what this node module enables .
15
14
16
15
This module takes care of the building blocks and mechanics for working
17
16
with the TensorFlow C API, and instead provides an API around Tensors, Graphs,
@@ -24,9 +23,11 @@ This is still in the works, and recently revamped to support TensorFlow 1.4+.
24
23
This is in plan. The idea here is to point to a saved model and be able to
25
24
use it for predictions. Instances-in, inferences-out.
26
25
26
+ Stay tuned for a future update.
27
27
28
28
## Low Level Interface - Tensors, Graphs and Sessions
29
29
30
+ ### Trivial Example - Loading and Running Graphs
30
31
Lets assume we have a simple TensorFlow graph. For illustration purposes, a
31
32
trivial graph produced from this Python code, and saved as a GraphDef
32
33
protocol buffer file.
@@ -48,45 +49,111 @@ TensorFlow session, and then run specific operations to retrive tensors.
48
49
``` javascript
49
50
const tf = require (' tensorflow' );
50
51
51
- // Load the session with the specified graph definition
52
- let session = tf .Session .fromGraphDef (' trivial.graph.proto' );
53
-
54
- // Load references to operations that will be referenced later,
55
- // mapping friendly names to graph names (useful for handling
56
- // fully-qualified tensor or op names)
57
- session .graph .loadReferences ({ result: ' result' })
58
-
52
+ // Load the Graph and create a Session to be able to run the operations
53
+ // defined in the graph.
54
+ let graph = tf .graph (' trivial.graph.proto' );
55
+ let session = graph .createSession ();
56
+
59
57
// Run to evaluate and retrieve the value of the 'result' op.
60
- let outputs = session .run (/* inputs */ null ,
61
- /* outputs */ [ ' result' ] ,
62
- /* targets */ null );
58
+ let result = session .run (/* inputs */ null ,
59
+ /* outputs */ ' result' ,
60
+ /* targets */ null );
63
61
64
- // Should print out '42'
65
- console .log (outputs .result .toValue ());
62
+ // The result is a Tensor, which contains value, type and shape fields.
63
+ // This Should print out '42'
64
+ console .log (result .value );
66
65
67
- // Low-level interface requires explicit cleanup, so be sure to
68
- // delete native objects.
69
- outputs .result .delete ();
70
- session .delete ();
66
+ // Cleanup
67
+ graph .delete ();
71
68
```
72
69
73
- Above is obviously an overly-simplistic sample. A real-sample (forthcoming)
74
- would demonstrate both inputs and outputs, and multi-dimensional tensors
75
- rather than scalars.
70
+ ### Feeding and Fetching Tensors with a Session
76
71
77
- Stay tuned!
72
+ This example goes a bit further - in particular, the Graph contains
73
+ variables, and placeholders, requiring initialization as well as feeding values,
74
+ when executing the graph. Additionally the Tensors are integer matrices.
78
75
79
- As more of this functionality is in place, it will be available on
80
- [ npmjs ] ( https://www.npmjs.org/package/ tensorflow) as any other module.
76
+ ``` python
77
+ import tensorflow as tf
81
78
82
- ## In the works, and more to come ...
79
+ with tf.Graph().as_default() as graph:
80
+ var1 = tf.placeholder(dtype = tf.int32, shape = [2 ,2 ], name = ' var1' )
81
+ var2 = tf.placeholder(dtype = tf.int32, shape = [2 ,1 ], name = ' var2' )
82
+ var3 = tf.Variable(initial_value = [[1 ],[1 ]], dtype = tf.int32)
83
+
84
+ tf.variables_initializer(tf.global_variables(), name = ' init' )
85
+
86
+ with tf.name_scope(' computation' ):
87
+ tf.add(tf.matmul(var1, var2), var3, name = ' result' )
88
+
89
+ tf.train.write_graph(graph, ' .' , ' graph.proto' , as_text = False )
90
+ ```
91
+
92
+ Here is the corresponding node.js snippet to work with the Graph defined above:
93
+
94
+ ``` javascript
95
+ const tf = require (' tensorflow' );
96
+
97
+ let graph = tf .graph (' graph.proto' );
98
+ let session = graph .createSession ();
99
+
100
+ // Run the 'init' op to initialize variables defined in the graph.
101
+ session .run (null , null , ' init' );
102
+
103
+ // Generally you can use arrays directly. This samples demonstrates creating
104
+ // Tensors to explicitly specify types to match the int32 types that the graph
105
+ // expects.
106
+ let a = tf .tensor ([[2 ,2 ],[4 ,4 ]], tf .Types .int32 );
107
+ let b = tf .tensor ([[3 ],[5 ]], tf .Types .int32 );
83
108
109
+ // You can fetch multiple outputs as well.
110
+ let outputs = session .run ({ var1: a, var2: b }, [' var3' , ' computation/result' ]);
111
+ console .log (outputs .var3 .value )
112
+ console .log (outputs[' computation/result' ].value );
113
+
114
+ graph .delete ();
115
+ ```
116
+
117
+ ## Installation
118
+
119
+ Installation is pretty straight-forward. Installing this module automatically brings installs
120
+ the TensorFlow binary dependencies (by default, TensorFlow CPU v1.4.1).
121
+
122
+ npm install tensorflow
123
+
124
+ Optionally, you can specify the build of TensorFlow binaries to install using environment
125
+ variables.
126
+
127
+ export TENSORFLOW_LIB_TYPE=gpu
128
+ export TENSORFLOW_LIB_VERSION=1.5.0
129
+ npm install tensorflow
130
+
131
+ The TensorFlow binaries automatically installed within the directory containing the node
132
+ module. If you have a custom build of TensorFlow you would like to use instead, you can
133
+ suppress downloadinging the binaries at installation time.
134
+
135
+ export TENSORFLOW_LIB_PATH=path-to-custom-binaries
136
+ npm install tensorflow
137
+
138
+ Note that the path you specify must be a directory that contains both ` libtensorflow.so ` and
139
+ ` libtensorflow_framework.so ` .
140
+
141
+
142
+ ## TensorFlow Setup and Docs
143
+ Note that to use the Python interface to build TensorFlow graphs and train models, you will
144
+ also need to install TensorFlow directly within your Python environment.
145
+
146
+ pip install tensorflow==1.4.1
147
+
148
+ For more information, check out the TensorFlow [ install] ( https://www.tensorflow.org/install )
149
+ and [ API] ( https://www.tensorflow.org/api_docs/ ) documentation.
150
+
151
+
152
+ ## In the works, and more to come ...
84
153
Some things on the plan to be tackled.
85
154
86
155
1 . Support for string tensors.
87
- 2 . Support for high-level API (using saved models representing results
88
- of training)
89
- 3 . Nicely packaged and published npm package along with better docs.
90
- 4 . What else? Please file issues...
156
+ 2 . Support for high-level API (and saved models representing results of training)
157
+ 3 . Support for Windows
91
158
92
- If any of this is interesting to you, please let me know!
159
+ Please file issues for feature suggestions, bugs or questions.
0 commit comments