tensorflow.js
by ADL
通过ADL
并了解如何直接在浏览器中运行ML / DL模型 (And learn how you can run ML/DL models directly in the browser)
An increasing number of developers are using TensorFlow in their machine learning projects. In March this year, the TensorFlow team at Google announced the arrival of the much-awaited JavaScript framework, TensorFlow.js (which was previously called DeepLearn.js).
越来越多的开发人员在其机器学习项目中使用TensorFlow。 今年3月,Google的TensorFlow团队宣布了期待已久JavaScript框架TensorFlow.js(以前称为DeepLearn.js)的到来。
Now developers can build lightweight models and run them in the browser using JavaScript. Let’s understand what the need was for the development of this framework.
现在,开发人员可以构建轻量级模型,并使用JavaScript在浏览器中运行它们。 让我们了解开发此框架的需求。
历史 (History)
Before going to TensorFlow.js, I would like to start off with TensorFlow.
在转到TensorFlow.js之前,我想先从TensorFlow开始。
TensorFlow was developed in 2011 at Google as their propitiatory library for Machine learning/Deep learning applications at Google. This library was open sourced in 2015 under the Apache License.
TensorFlow于2011年在Google开发,作为其在Google的机器学习/深度学习应用程序的推广库。 该库于2015年根据Apache许可开源。
TensorFlow is built in C++, which enables the code to execute at a very low level. TensorFlow has bindings to different language like Python, R, & Java. This enables TensorFlow to be used in these languages.
TensorFlow是用C ++构建的,它使代码可以在非常低的级别上执行。 TensorFlow具有对不同语言(如Python,R和Java)的绑定。 这使TensorFlow可以在这些语言中使用。
So, the obvious question is: what about JavaScript?
因此,显而易见的问题是:JavaScript呢?
Conventionally, in JavaScript, ML/DL was performed by using an API. An API was made using some framework, and the model was deployed at the server. The client sent a request using JavaScript to get results from the server.
传统上,在JavaScript中,使用API来执行ML / DL。 使用某种框架制作了一个API,并将该模型部署在服务器上。 客户端使用JavaScript发送了一个请求,以从服务器获取结果。
In 2017, a project called Deeplearn.js appeared, which aimed to enable ML/DL in JavaScript, without the API hassle.
在2017年,一个名为Deeplearn.js的项目出现了,该项目旨在在没有API麻烦的情况下在JavaScript中启用ML / DL。
But there were questions about speed. It was very well known that JavaScript code could not run on GPU. To solve this problem, WebGL was introduced. This is a browser interface to OpenGL. WebGL enabled the execution of JavaScript code on GPU.
但是还有关于速度的问题。 众所周知,JavaScript代码无法在GPU上运行。 为了解决这个问题,引入了WebGL。 这是OpenGL的浏览器界面。 WebGL支持在GPU上执行JavaScript代码。
In March 2018, the DeepLearn.js team got merged into the TensorFlow Team at Google and was renamed TensorFlow.js.
2018年3月,DeepLearn.js团队合并到Google的TensorFlow团队中,并更名为TensorFlow.js。
Watch the below video for further details:
观看下面的视频以了解更多详细信息:
TensorFlow.js (TensorFlow.js)
Tensorflow.js provides two things:
Tensorflow.js提供了两件事:
- The CoreAPI, which deals with the low level code CoreAPI,处理底层代码
- LayerAPI is built over the CoreAPI, and makes our lives easier by increasing the level of abstraction. LayerAPI建立在CoreAPI之上,并通过增加抽象级别使我们的生活更轻松。
入门 (Getting Started)
There are two main ways to get TensorFlow.js in your project:
在项目中获取TensorFlow.js的主要方法有两种:
1.通过<script>标签 (1. via <script> Tag)
Add the following code to an HTML file:
将以下代码添加到HTML文件:
<html> <head> <!-- Load TensorFlow.js --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script> </head>
<body> Hello </body></html>
2.通过NPM (2. via NPM)
Add TensorFlow.js to your project using yarn or npm.
使用yarn或npm将TensorFlow.js添加到您的项目中。
yarn add @tensorflow/tfjs
npm install @tensorflow/tfjs
In your main js file:
在您的主要js文件中:
import * as tf from '@tensorflow/tfjs';
核心API (CoreAPI)
1.张量 (1. Tensors)
So, what is a Tensor ?
那么,什么是张量?
- A scalar is a single number. For example, x = 1 标量是单个数字。 例如,x = 1
A vector is an array of numbers. For example, x=[1,2]
向量是数字数组。 例如, x = [1,2]
A matrix is a 2-D array
矩阵是二维数组
([[1, 2],
([[[1,2],
[3, 4],
[3,4],
[5, 6]])
[5,6]])
A tensor is a n-dimensional array with n>2
张量是n > 2的n维数组
TensorFlow.js has utility functions for common cases like Scalar, 1D, 2D, 3D and 4D tensors, as well a number of functions to initialize tensors in ways useful for machine learning.
TensorFlow.js具有适用于标量,1D,2D,3D和4D张量的常见情况的实用程序功能,以及许多以对机器学习有用的方式初始化张量的功能。
程式码范例 (Code Examples)
tf.tensor():
tf.tensor():
// Pass an array of values to create a vector.tf.tensor([1, 2, 3, 4]).print();
tf.scalar():
tf.scalar():
tf.scalar(3.14).print();
And so on…
等等…
Watch the Below Video to get a deep insight into Tensors in TensorFlow.js:
观看下面的视频以深入了解TensorFlow.js中的Tensors:
2.变量与运算 (2. Variables & Operations)
Tensors are immutable data structures. That means their values can’t be changed once they are set.
张量是不可变的数据结构。 这意味着它们的值一旦设置就无法更改。
However, tf.variable()
is introduced in TensorFlow.js. The real use case for tf.variable()
is when we need to change the data frequently, such as when adjusting model weights in Machine Learning.
然而, tf.variable()
在TensorFlow.js中引入。 tf.variable()
的真正用例是当我们需要频繁更改数据时,例如在机器学习中调整模型权重时。
Code sample:
代码示例:
const x = tf.variable(tf.tensor([1, 2, 3]));x.assign(tf.tensor([4, 5, 6]));x.print();
运作方式 (Operations)
There are various operations in TensorFlow.js. In order to perform mathematical computation on Tensors, we use operations. Tensors are immutable, so all operations always return new Tensors and never modify input Tensors. So tf.variable()
can be used in order to save memory.
TensorFlow.js中有各种操作。 为了在张量上执行数学计算,我们使用运算。 张量是不可变的,因此所有操作总是返回新的张量,而从不修改输入张量。 因此,可以使用tf.variable()
来节省内存。
Let’s look into some operations:
让我们看一些操作:
tf.add() — Adds two tf.Tensors element-wise
tf.add()—将两个tf.Tensor逐元素相加
const a = tf.tensor1d([1, 2, 3, 4]);const b = tf.tensor1d([10, 20, 30, 40]);a.add(b).print(); // or tf.add(a, b)
There are many operations in TensorFlow.js. You can check the documentation for other operations. I will demonstrate one more operation here: tf.matmul()
TensorFlow.js中有许多操作。 您可以查看文档中的其他操作。 我将在这里演示另一个操作: tf.matmul()
tf.matmul() — Computes the dot product of two matrices, A * B.
tf.matmul()—计算两个矩阵A * B的点积。
const a = tf.tensor2d([1, 2], [1, 2]);const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
a.matMul(b).print(); // or tf.matMul(a, b)
Watch the below video for deep insight into Variable and Operations:
观看下面的视频,深入了解变量和运算:
3.内存管理 (3. Memory Management)
Memory management is the key in Machine Learning/Deep Learning tasks, because they are generally computationally expensive.
内存管理是机器学习/深度学习任务的关键,因为它们通常在计算上很昂贵。
TensorFlow.js provides two major ways to manage memory:
TensorFlow.js提供了两种主要的内存管理方式:
- tf.dispose() tf.dispose()
- tf.tidy() tf.tidy()
They both typically do the same thing, but they do it in different ways.
他们通常都做相同的事情,但是他们以不同的方式来做。
tf.tidy() (tf.tidy())
This executes the provided function fn
and after it is executed, cleans up all intermediate tensors allocated by fn
except those returned by fn
.
此执行所提供的功能fn
和它被执行后,清除由分配的所有中间张量fn
除了那些由返回fn
。
tf.tidy()
helps avoid memory leaks. In general, it wraps calls to operations in tf.tidy()
for automatic memory cleanup.
tf.tidy()
有助于避免内存泄漏。 通常,它将对操作的调用包装在tf.tidy()
以进行自动内存清除。
Code example:
代码示例:
const y = tf.tidy(() => { // aa, b, and two will be cleaned up when the tidy ends. const two= tf.scalar(2); const aa = tf.scalar(2); const b = aa.square(); console.log('numTensors (in tidy): ' + tf.memory().numTensors); // The value returned inside the tidy function will return // through the tidy, in this case to the variable y. return b.add(two);});console.log('numTensors (outside tidy): ' + tf.memory().numTensors);y.print();
tf.dispose() (tf.dispose())
Disposes any tf.Tensors found within the mentioned object.
处置在上述对象内找到的所有tf.Tensor 。
Code example:
代码示例:
const two= tf.scalar(2);
two.dispose()
LayersAPI (LayersAPI)
Layers are the primary building block for constructing a ML/DL Model. Each layer will typically perform some computation to transform its input to its output. Under the hood, every layer uses the CoreAPI of Tensorflow.js.
层是构建ML / DL模型的主要构建块。 每层通常将执行一些计算,以将其输入转换为输出。 在底层,每个层都使用Tensorflow.js的CoreAPI。
Layers will automatically take care of creating and initializing the various internal variables/weights they need to function. So, basically it makes life easier by increasing the level of abstraction.
图层将自动创建和初始化它们需要起作用的各种内部变量/权重。 因此,基本上,通过提高抽象级别,它使生活更轻松。
We will make a simple example feed forward network using the LayerAPI. The Feed Forward network we will build is as below:
我们将使用LayerAPI制作一个简单的示例前馈网络。 我们将建立的前馈网络如下:
码: (Code:)
Index.html
Index.html
<html><head><title></title><script src=”https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script><script src=”main.js” type=”text/javascript”></script>
</head>
<body>Tensorflow JS Demo
</body></html>
main.js
main.js
const model = tf.sequential();
//config for layerconst config_hidden = { inputShape:[3], activation:'sigmoid', units:4}const config_output={ units:2, activation:'sigmoid'}
//defining the hidden and output layerconst hidden = tf.layers.dense(config_hidden);const output = tf.layers.dense(config_output);
//adding layers to modelmodel.add(hidden);model.add(output);
//define an optimizerconst optimize=tf.train.sgd(0.1);
//config for modelconst config={optimizer:optimize,loss:'meanSquaredError'}
//compiling the modelmodel.compile(config);
console.log('Model Successfully Compiled');
//Dummy training dataconst x_train = tf.tensor([ [0.1,0.5,0.1], [0.9,0.3,0.4], [0.4,0.5,0.5], [0.7,0.1,0.9]])
//Dummy training labelsconst y_train = tf.tensor([ [0.2,0.8], [0.9,0.10], [0.4,0.6], [0.5,0.5]])
//Dummy testing dataconst x_test = tf.tensor([ [0.9,0.1,0.5]])
train_data().then(function(){ console.log('Training is Complete'); console.log('Predictions :'); model.predict(x_test).print();})
async function train_data(){ for(let i=0;i<10;i++){ const res = await model.fit(x_train,y_train,epoch=1000,batch_size=10); console.log(res.history.loss[0]); }}
Output:
输出:
Watch the below videos for deep insight and code explanation:
观看以下视频,获得更深入的了解和代码说明:
I understand that this is a small overview on the Tensorflow.js Library. I feel this can be a starting point before you read the documentation and go through some real world applications.
我了解这是Tensorflow.js库的一个简短概述。 我认为这可能是您阅读文档并浏览一些实际应用程序之前的起点。
I will be posting real world examples using TensorFlow.js as below:
我将使用TensorFlow.js发布如下示例:
More Real world examples coming soon…Stay Tuned…
更多现实世界的例子即将推出…… 敬请期待 ……
我对此 (My take on this)
This is excellent for coders who are familiar with JavaScript and are trying to find their way in the ML/DL world!
对于熟悉JavaScript并试图在ML / DL世界中找到自己的出路的程序员来说,这是极好的选择!
It makes things a lot simpler for people coming from a non-ML/DL background, but who are looking to understand this field. The use cases for this are many, and I personally think it’s something we need at the moment.
对于非ML / DL背景的人来说,它使事情变得简单得多,但是他们希望了解这一领域。 这个的用例很多,我个人认为这是我们目前需要的。
In my next article and video, I will talk about ML5 which is built over TensorFlow.js. ML5 is built at New York University and is under active development.
在我的下一篇文章和视频中,我将讨论基于TensorFlow.js构建的ML5 。 ML5是在纽约大学制造的,并且正在积极开发中。
What do you think about TensorFlow.js? Let me know in the comments section below. If you like this article, you would also like my Videos on Youtube.
您如何看待TensorFlow.js? 在下面的评论部分中告诉我。 如果您喜欢这篇文章,也希望我在YouTube上的视频。
If you liked my article, please click the ? below And follow me on Medium & :
如果您喜欢我的文章, 请单击“?”。 下面并跟随我进入Medium &:
If you have any questions, please let me know in a comment below or Twitter.
如果您有任何疑问,请在下面的评论或Twitter中让我知道。
翻译自: https://www.freecodecamp.org/news/get-to-know-tensorflow-js-in-7-minutes-afcd0dfd3d2f/
tensorflow.js