博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在浏览器中设置Tensorflow.js以进行机器学习
阅读量:2525 次
发布时间:2019-05-11

本文共 13928 字,大约阅读时间需要 46 分钟。

by Kevin Scott

凯文·斯科特(Kevin Scott)

如何在浏览器中设置Tensorflow.js以进行机器学习 (How to set up Tensorflow.js for machine learning in your browser)

Until recently, just getting started writing your first line of machine learning code required a hefty upfront investment in time and money.

直到最近,才刚刚开始编写您的第一行机器学习代码,就需要大量的前期时间和金钱投资。

Last year, specifically for machine learning. I researched the parts and assembled it myself. Just doing that cost me around $1600 and 30 hours of setup time. I’m still trying to wrangle the computer’s configuration and libraries and make it work with various frameworks.

去年, 专门为机器学习 。 我研究了零件并自己组装。 仅仅这样做就花了我大约1600美元和30个小时的设置时间。 我仍在尝试弄乱计算机的配置和库,并使其与各种框架一起使用。

The good news is that getting started with machine learning today has never been easier. In fact, if you’re reading this, it means you already have the tools you need to dive right in. You can now learn the machine learning framework Tensorflow right in your browser, using JavaScript.

好消息是,如今开始学习机器学习从未如此简单。 实际上,如果您正在阅读此书 ,则意味着您已经具备了直接学习所需的工具。 现在您可以使用JavaScript在浏览器中直接学习机器学习框架Tensorflow。

Tensorflow.js (Tensorflow.js)

Google at the Google I/O 2018. There are s for running machine learning algorithms in the browser.

谷歌在Google I / O 2018上 。在浏览器中运行机器学习算法有很多 。

In addition, it’s a great opportunity to use JavaScript to explore machine learning concepts without having to install a thing.

此外,这是使用JavaScript无需安装任何东西即可探索机器学习概念的绝佳机会。

If you’re new to JavaScript, or if it’s been a while since you’ve written any front-end code, some of the recent changes in the JavaScript ecosystem might throw you for a loop. I’ll list the basics of modern Javascript you need to get the Tensorflow.js examples running, and start exploring machine learning.

如果您不熟悉JavaScript,或者自从编写任何前端代码以来已经有一段时间了,那么JavaScript生态系统中的一些最新更改可能会让您陷入困境。 我将列出运行Tensorflow.js示例所需的现代Javascript的基础,并开始探索机器学习。

设置教程 (Setup tutorial)

Let me repeat something: all you need to run Tensorflow.js is your web browser.

让我重复一遍: 运行Tensorflow.js所需的只是您的Web浏览器

It’s easy to lose sight amongst all the talk of transpilers, bundlers, and packagers, but all you need is a web browser to run Tensorflow.js. The code you develop locally is the same code you’ll be able to ship to your users to run on their browsers.

在所有有关编译器,打包器和打包器的讨论中,很容易看不见,但是您所需要的只是一个运行Tensorflow.js的Web浏览器。 您在本地开发的代码与可以交付给用户以在其浏览器上运行的代码相同。

Let’s see three quick ways to get the Hello World example working without installing anything. I’ll be using the from the Tensorflow.js documentation.

让我们看一下三种无需安装任何东西就能使Hello World示例正常工作的快速方法。 我将使用Tensorflow.js文档中的 。

浏览器控制台Getting started (Getting started with your browser console)

Every modern web browser ships with some sort of interactive JavaScript Console built in. I use Chrome, which includes a JavaScript Console you can open with “View > Developer > JavaScript Console”.

每个现代的Web浏览器都附带内置某种交互式JavaScript控制台。我使用Chrome,其中包括一个JavaScript控制台,您可以使用“查看>开发人员> JavaScript控制台”打开它。

This JavaScript Console lets you write JavaScript and execute it immediately. We’ll use this to run the Getting Started example from the .

使用此JavaScript控制台,您可以编写JavaScript并立即执行它。 我们将使用它来运行的Getting Started示例。

First, you’ll need to include the Tensorflow.js JavaScript file. A hosted version of the file is available via the below. A quick way to include an external .js file via the console is:

首先,您需要包括Tensorflow.js JavaScript文件。 可通过下面的获得文件的托管版本。 通过控制台包含外部.js文件的快速方法是:

var script = document.createElement('script');script.src = "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.10.0";document.getElementsByTagName('head')[0].appendChild(script);

Copy and paste this into your JavaScript Console, and you’ll have a copy of Tensorflow saved as the variable tf. (If you type tf in your console, you'll see a reference to it).

将其复制并粘贴到您JavaScript控制台中,您将有一个Tensorflow副本保存为变量tf 。 (如果您在控制台中键入tf ,则会看到对其的引用)。

You can then copy and paste the rest of the Getting Started example (the JavaScript between the second <script> tag) by pasting it directly into your console.

然后,您可以将其直接粘贴到控制台中,然后复制并粘贴“入门”示例的其余部分(第二个<scri pt>标记之间JavaScript)。

JavaScript托管平台入门 (Getting started with a JavaScript hosting platform)

An alternative approach is to use an online JavaScript hosting platform. Three popular ones are , , and . These platforms can automatically include scripts for you and take care of transpiling your code in the browser, which makes getting started a cinch.

另一种方法是使用在线JavaScript托管平台。 三种流行的是 , 和 。 这些平台可以自动为您提供脚本,并照顾在浏览器中转译代码的麻烦,这使入门变得很困难。

You can view to see an implementation working. Make sure to open your browser console, as explained above, to see the output.

您可以上查看以查看实现的工作。 确保如上所述打开浏览器控制台以查看输出。

本地入门 (Getting started locally)

A third option for getting Tensorflow.js working involves saving the code as a .html file and opening it locally on your computer. And you don't need a web server to do this!

使Tensorflow.js正常运行的第三种方法是将代码另存为.html文件,然后在您的计算机上本地打开。 而且您不需要Web服务器即可执行此操作!

Copy the HTML code into a file, and open it in your web browser. For instance, if you save the file onto your desktop and you’re on a Mac, you might open it in your browser with the following URL:

将HTML代码复制到文件中,然后在Web浏览器中将其打开。 例如,如果您将文件保存到桌面上并且使用的是Mac,则可以使用以下URL在浏览器中打开文件:

file:///Users/YOURNAME/Desktop/sample.html

file:///Users/YOURNAME/Desktop/sample.html

It is important to note that viewing HTML files this way introduces limitations, including issues with referencing relative links, handling ajax calls, and security, among other things. But it's a quick and easy way to get something running in your browser.

重要的是要注意,以这种方式查看HTML文件会引入限制,其中包括引用相对链接,处理ajax调用和安全性等问题。 但这是在浏览器中运行某些东西的快速简便的方法。

现代JavaScript开发工作流程 (The modern JavaScript development workflow)

Hopefully by this point, you can see how easy it is to get something basic to show up in your browser. If you begin looking at the Tensorflow.js examples, you might be thinking:

希望到此为止,您可以看到将基本内容显示在浏览器中是多么容易。 如果您开始看Tensorflow.js示例,您可能会想:

  • how do I organize my files?

    如何组织我的文件?
  • how do I manage third party libraries in my code?

    如何在代码中管理第三方库?
  • what’s with these syntax errors?

    这些语法错误是什么?

As soon as you move beyond the basic “Hello World” example above and into some of the other examples, you’ll begin to run into syntax issues and organization issues. That’s where a strong JavaScript pipeline will be your best friend.

一旦您超越了上面的基本“ Hello World”示例并进入了其他一些示例,您将开始遇到语法问题和组织问题。 在那里,强大JavaScript管道将是您最好的朋友。

一点JavaScript历史 (A little bit of JavaScript history)

As our expectations for web apps have grown over the past decade, the front-end ecosystem has exploded in complexity.

随着我们对Web应用程序的期望在过去十年中不断增长,前端生态系统的复杂性呈爆炸式增长。

JavaScript in particular has matured a lot as a programming language, adopting a number of forward-thinking changes while continuing to support one of the largest userbases of any programming language.

特别是,JavaScript作为一种编程语言已经非常成熟,它采用了许多具有前瞻性的更改,同时继续支持所有编程语言中最大的用户群之一。

New changes to the language spec are referenced with acronyms like ES5, ES6, ES2015, and E2016.

对语言规范的新更改以ES5,ES6,ES2015和E2016等首字母缩写词引用。

‘ES’ stands for ECMAScript, and . The numbers 5 and 6 were traditionally used to refer to versions of the standard, but nowadays years are used for additional clarity.

“ ES”代表ECMAScript, 。 数字5和6传统上是用来指标准的版本,但如今,为了更清晰起见,使用了几年。

. Some cutting edge or proposed features are not yet supported, and older browsers (in particular Internet Explorer) will never support the latest spec.

。 尚不支持某些最先进的功能或建议的功能,并且较旧的浏览器(尤其是Internet Explorer)将永远不支持最新的规范。

Because of this instability, if you want to reach the widest audience possible, you use something called a . This is software that converts your JavaScript code written with modern conveniences into a version with wide-spread adoption. ES5 is widely supported, and is generally a good target.

由于这种不稳定性,如果您想吸引尽可能多的受众,则可以使用称为 。 该软件可将以现代便利性编写JavaScript代码转换为被广泛采用的版本。 ES5得到了广泛的支持,通常是一个不错的目标。

Many of the Tensorflow.js examples make use of new syntax that is not yet widely supported in browsers, and requires transpiling. I’ll explain the syntax first and then explain how to get them working.

Tensorflow.js的许多示例都使用了新的语法,该语法尚未在浏览器中得到广泛支持,并且需要转译。 我将首先解释语法,然后解释如何使其工作。

importexport (import and export)

import and export are two bits of syntax recently introduced into JavaScript for importing modules. The saga of JavaScript modules is , but the .

importexport是JavaScript最近引入的用于导入模块的语法的两位。 JavaScript模块的传奇故事 ,但是 。

Unfortunately, as of May 2018, import is not supported by any browsers, so to use it you need to use a transpiler.

不幸的是,截至2018年5月,任何浏览器均不支持import ,因此要使用它,您需要使用翻译器。

In the Getting Started docs, you’ll see an example of import upfront:

在“入门”文档中,您将看到一个预import示例:

import * as tf from '@tensorflow/tfjs';

This is basically the same as:

这基本上与以下内容相同:

var tf = require('@tensorflow/tfjs');

You also might see something like:

您可能还会看到类似以下内容的内容:

import { util, tensor2d } from '@tensorflow/tfjs';

The equivalent using require is:

使用require的等效项是:

var tf = require("@tensorflow/tfjs");var util = tf.util;var tensor2d = tf.tensor2d

async await (async and await)

Javascript has traditionally been used heavily with UIs, which perform a lot of asynchronous actions. There have been three broad patterns for handling asynchronous code over the years: .

传统上,Java脚本经常与执行大量异步操作的UI一起使用。 多年来,已经有三种处理异步代码的广泛模式: 。

async/await provides a way of defining asynchronous functions in a synchronous way. make use of this async / await syntax.

async / await提供了一种以同步方式定义异步功能的方法。 都使用了这种async / await语法。

Here’s two versions of the same code, the first written with async/await, the second using promises:

这是同一代码的两个版本,第一个使用async / await编写,第二个使用promises:

// With async/awaitasync function loadMobilenet() {  const mobilenet = await tf.loadModel(      'https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json');  // Return a model that outputs an internal activation.  const layer = mobilenet.getLayer('conv_pw_13_relu');  return tf.model({inputs: model.inputs, outputs: layer.output});});// With promisesfunction loadMobilenet() {  return tf.loadModel('https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json').then(function (mobilenet) {    // Return a model that outputs an internal activation.    const layer = mobilenet.getLayer('conv_pw_13_relu');    return tf.model({inputs: model.inputs, outputs: layer.output});  });});

Both of these language features — import/export and async/await — make writing JavaScript more pleasant. Let's see the tools we need to use them in our own code.

这两种语言功能( import / exportasync / await )使编写JavaScript变得更加愉快。 让我们看看在我们自己的代码中使用它们所需的工具。

JavaScript工具 (JavaScript Tooling)

In the Getting Started docs, you’ll see this note:

在“入门”文档中,您将看到以下说明:

Note: because we use ES2017 syntax (such as import), this workflow assumes you are using a bundler/transpiler to convert your code to something the browser understands. See our examples to see how we use Parcel to build our code. However you are free to use any build tool that you prefer.

注意:因为我们使用ES2017语法(例如import ),所以此工作流程假定您使用捆绑程序/编译器将代码转换为浏览器可以理解的内容。 请参阅示例,了解如何使用Parcel构建代码。 但是,您可以自由使用任何喜欢的构建工具。

Let’s talk about build tools.

让我们谈谈构建工具。

捆绑包 (Bundlers)

Bundlers have taken on the role of conductor of the orchestra of growing front-end codebases. A bundler is a program that takes your JavaScript code and “bundles” it up into a compatible file for the browser.

捆绑软件已经扮演了不断发展的前端代码库的乐队指挥的角色。 捆绑程序是一种程序,它将您JavaScript代码并将其“捆绑”成浏览器的兼容文件。

Bundlers will also transpile code (convert ES2018 code to ES5, along with other dialects like React or Typescript, using something like ), set up "hot reloading" to refresh the browser with code changes without reloading the page, and many other things to make front-end development better.

捆绑程序还将转换代码(使用东西将ES2018代码与其他方言(如React或Typescript)一起转换为ES5,以及其他方言),设置“热重载”以通过更改代码刷新浏览器而无需重载页面,以及其他许多操作使前端开发更好。

and used to be popular bundlers, but have recently fallen out of favor to . Other bundlers include and . The Tensorflow.js examples use parcel.

和曾经是流行的捆绑器,但是最近对 。 其他捆绑器包括 。 Tensorflow.js示例使用parcel

包装经理 (Package managers)

Often, when encountering a JavaScript library, you’ll see installation instructions like yarn add @tensorflow/tfjs or npm install @tensorflow/tfjs.

通常,在遇到JavaScript库时,您会看到安装说明,例如yarn add @tensorflow/tfjsnpm install @tensorflow/tfjs

and are both package managers. They're command line tools used to install and keep track of your third party JavaScript dependencies.

都是程序包管理器。 它们是用于安装和跟踪第三方JavaScript依赖项的命令行工具。

yarn and npm are pretty similar, and the decision of which one to use is largely up to personal preference (though you'll find plenty of hot debates online if you're into that sort of thing).

yarnnpm非常相似,使用哪种决定很大程度上取决于个人喜好(尽管如果您喜欢这种东西,您会在网上找到很多热门话题)。

Either one will save your dependencies into a package.json file which should be checked into your git repository. This file will enable other developers to quickly install all the necessary dependencies for your project and get things running quickly.

任何一种都将您的依赖项保存到package.json文件中,该文件应检入git存储库中。 该文件将使其他开发人员可以快速安装项目所需的所有依赖项,并使它们快速运行。

To get all these goodies, the first step is to install npm or yarn, along with Node.js. Once those are in place, you can follow the instructions on any of the Tensorflow.js examples and they should work out of the box. Usually, getting set up with a new front-end project using these tools is a one step process.

要获得所有这些优点,第一步是安装npmyarn以及Node.js 一旦安装到位,您就可以按照任何Tensorflow.js示例中的说明进行操作,它们应该立即可用。 通常,使用这些工具来设置新的前端项目是一个一步的过程。

结语 (Wrapping up)

Again, you don’t need any of these tools to work with these examples, but using them makes things so much easier. If you intend to do any sort of serious JavaScript development, I would encourage you to play with these tools, along with other popular JavaScript tools like and , which make handling larger codebases much better.

同样,您不需要这些工具中的任何一个来处理这些示例,但是使用它们会使事情变得更加容易。 如果您打算进行任何认真JavaScript开发,我建议您使用这些工具,以及其他流行JavaScript工具(如和 ,它们可以更好地处理较大的代码库。

Originally published at

最初发布于

Special thanks to .

特别感谢 。

翻译自:

转载地址:http://hikzd.baihongyu.com/

你可能感兴趣的文章
valgrind检测linux程序内存泄露
查看>>
Hadoop以及组件介绍
查看>>
1020 Tree Traversals (25)(25 point(s))
查看>>
第一次作业
查看>>
“==”运算符与equals()
查看>>
单工、半双工和全双工的定义
查看>>
Hdu【线段树】基础题.cpp
查看>>
时钟系统
查看>>
BiTree
查看>>
5个基于HTML5的加载动画推荐
查看>>
水平权限漏洞的修复方案
查看>>
静态链接与动态链接的区别
查看>>
Android 关于悬浮窗权限的问题
查看>>
如何使用mysql
查看>>
linux下wc命令详解
查看>>
敏捷开发中软件测试团队的职责和产出是什么?
查看>>
在mvc3中使用ffmpeg对上传视频进行截图和转换格式
查看>>
python的字符串内建函数
查看>>
Spring - DI
查看>>
微软自己的官网介绍 SSL 参数相关
查看>>