How to call a Python function from Node.js

前端 未结 9 1579
借酒劲吻你
借酒劲吻你 2020-11-22 14:53

I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application

9条回答
  •  遥遥无期
    2020-11-22 15:12

    The Boa is good for your needs, see the example which extends Python tensorflow keras.Sequential class in JavaScript.

    const fs = require('fs');
    const boa = require('@pipcook/boa');
    const { tuple, enumerate } = boa.builtins();
    
    const tf = boa.import('tensorflow');
    const tfds = boa.import('tensorflow_datasets');
    
    const { keras } = tf;
    const { layers } = keras;
    
    const [
      [ train_data, test_data ],
      info
    ] = tfds.load('imdb_reviews/subwords8k', boa.kwargs({
      split: tuple([ tfds.Split.TRAIN, tfds.Split.TEST ]),
      with_info: true,
      as_supervised: true
    }));
    
    const encoder = info.features['text'].encoder;
    const padded_shapes = tuple([
      [ null ], tuple([])
    ]);
    const train_batches = train_data.shuffle(1000)
      .padded_batch(10, boa.kwargs({ padded_shapes }));
    const test_batches = test_data.shuffle(1000)
      .padded_batch(10, boa.kwargs({ padded_shapes }));
    
    const embedding_dim = 16;
    const model = keras.Sequential([
      layers.Embedding(encoder.vocab_size, embedding_dim),
      layers.GlobalAveragePooling1D(),
      layers.Dense(16, boa.kwargs({ activation: 'relu' })),
      layers.Dense(1, boa.kwargs({ activation: 'sigmoid' }))
    ]);
    
    model.summary();
    model.compile(boa.kwargs({
      optimizer: 'adam',
      loss: 'binary_crossentropy',
      metrics: [ 'accuracy' ]
    }));
    

    The complete example is at: https://github.com/alibaba/pipcook/blob/master/example/boa/tf2/word-embedding.js

    I used Boa in another project Pipcook, which is to address the machine learning problems for JavaScript developers, we implemented ML/DL models upon the Python ecosystem(tensorflow,keras,pytorch) by the boa library.

提交回复
热议问题