Friday 25 September 2020

Implement tensorflow keras API in 30 minutes

Just published 2.0 for my old and deprecated project https://github.com/yorkie/tensorflow-nodejs, but I decided to restart it with boa, the Python interop library for Node.js.The reason that I dropped out of this project a few years ago is that the Python ecosystem for tensorflow is too mature and re-implement it is too hard, so just developing this library by bridging the TensorFlow C API is also hard to put forward.I created [pipcook/boa](https://github.com/alibaba/pipcook/blob/master/docs/manual/intro-to-boa.md) in few months ago, which lets you call Python functions in Node.js runtime, now I just decided to rewrite the tensorflow2 in boa.With bao, a basic keras migration/implementation for JavaScript only takes 30 minutes to me, it's really easy, and could be maintained forward to support Node.js developers to use Tensorflow's mature and latest APIs.And I just write an example to train mnist dataset:```js const tf = require('tensorflow2');// load mnist dataset. const dataset = tf.keras.dataset.mnist(); // { // train: { x: [Getter], y: [Getter] }, // test: { x: [Getter], y: [Getter] } // }// create model. const model = tf.keras.models.Sequential([ tf.keras.layers.Flatten({ input_shape: [28, 28] }), tf.keras.layers.Dense(128, { activation: 'relu' }), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10) ]); model.summary();// compile the model. const loss_fn = tf.keras.losses.SparseCategoricalCrossentropy({ from_logits: true }); model.compile({ optimizer: 'adam', loss: loss_fn, metrics: [ 'accuracy' ], });// train the model. model.fit(dataset.train.x, dataset.train.y, { epochs: 5 });// save the model model.save('your-model.h5'); ```That's it.If you wanna contribute more Tensorflow APIs, just take a look at this link: https://github.com/yorkie/tensorflow-nodejs/blob/master/lib/keras.js, is that really simple? Just use boa to call tensorflow python's specific apis and convert some arguments from Python to JavaScript!

Submitted September 25, 2020 at 04:01PM by yorkiefixer

No comments:

Post a Comment