Getting Started with TensorFlow.js

使用TensorFlow.js,您不仅可以在浏览器中运行深度学习模型进行推理,你还能够训练它们。在这个简单的样例中,将展示一个相当于“Hello World”的示例。

1、引入TensorFlow.js

使用CDN上的文件,你就可以使用TensorFlow APIs。

<html>
<head>
 <!-- Load TensorFlow.js -->
 <!-- Get latest version at https://github.com/tensorflow/tfjs -->
 <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.2"> </script>

这里使用的版本是 0.11.2,你可以去github上找最新的。

2、创建一个简单的神经网络

由于这只有一个输入值和输出值,因此它可以是单个节点。在JavaScript中,我们可以创建一个tf.sequential,并向其添加layers。

const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

我们还需要指定损失函数和优化器:

model.compile({
   loss: 'meanSquaredError',
   optimizer: 'sgd'
  });

为了训练模型,我们需要数据集来训练模型。构造几个符合Y=2X-1的点,那么当X取[-1, 0, 1, 2, 3],Y取[-3, -1, 1, 3, 5]

const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

调用fit函数进行训练,传入X和Y并指定训练轮数。请注意,只是异步的,在进入下一步之前必须等待返回值,所以这些代码都要写在一个async函数中。

await model.fit(xs, ys, {epochs: 500});

最后传入一个值进行预测。

完整的代码如下:

<html>

 <head>
    <!-- Load TensorFlow.js -->
    <!-- Get latest version at https://github.com/tensorflow/tfjs -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.2">   
    </script>
 </head>

 <body>
   <div id="output_field"></div>
 </body>

 <script>
    async function learnLinear(){

        const model = tf.sequential();
        model.add(tf.layers.dense({
            units: 1, 
            inputShape: [1]
        }));

        model.compile({
            loss: 'meanSquaredError',
            optimizer: 'sgd'
        });

        const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
        const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

        await model.fit(xs, ys, {epochs: 100});

        document.getElementById('output_field').innerText =
            model.predict( tf.tensor2d([10], [1, 1]) );
    }

    learnLinear();
 </script>

<html>

 

 

参考链接:

1. https://medium.com/tensorflow/getting-started-with-tensorflow-js-50f6783489b2

2. https://blog.csdn.net/aliceyangxi1987/article/details/80743590

 

 

posted @ 2019-11-12 22:09  Rogn  阅读(219)  评论(0编辑  收藏  举报