专业的编程技术博客社区

网站首页 > 博客文章 正文

7分钟了解:Tensorflow,两种方法引入TensorFlow.js

baijin 2024-10-23 08:44:11 博客文章 6 ℃ 0 评论

越来越多的开发者在他们的机器学习工程中使用TensorFlow。今年3月,Google的TensorFlow团队发布等待多时的JavaScript框架,TensorFlow.js(之前也叫做DeepLearn.js)

从TensorFlow开始

在介绍TensorFlow.js之前,我想先从TensorFlow开始。

TensorFlow在2011年开发于Google作为i他们的机器学习/深度学习app的API lib。这个API lib于2015年在Apache协议下开源。

TensorFlow由C++编写,这使得代码能够在底层运行。TensorFlow已同其他语言邦定在一起,如Python,R,Java。从而这些语言也能够作为TensorFlow的调用接口。

那么问题来了:关于JavaScript我们知道些什么呢?

在JavaScript中,ML/DL通过使用API接口来调用。使用这些框架来生成一个API,并在服务器上部署模型。客户端使用JavaScript发送一个请求从服务器中获取回复。

客户端服务器架构

在2017年,一个叫做DeepLearning.js的工程诞生了,旨在没有API的反烦扰下在JavaScript中推动ML/DL的发展。

但是有出现了速度的问题。都知道JS代码不能运行在GPU上。为了解决这个问题,引进WebGL。这是一个OpenGL的浏览器接口。WebGl能够在GPU上执行JS代码。

在2018年3月,DeepLearn.js团队与TensorFlow团队合并,重命名为TensorFlow.js。

TensorFlow.js

TensorFlow.js提供两样东西:

  • CoreAPI,来处理底层代码
  • 在CoreAPI之上编写的LayerAPI,通过增加层级的抽象性使coding更容易。

两种方法引入TensorFlow.js

在你的项目中有两种方法引入TensorFlow.js

1. 通过<script>标签

添加下列代码到一个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

使用yarn或者NPM把TensorFlow.js添加到你的项目。

yarn add @tensorflow/tfjs
npm install @tensorflow/tfjs

在你的主js文件:

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

核心API

1. 张量(Tensors)

所以,什么是张量?

  • 标量是单个数。例如,x = 1
  • 矢量是一组数字。例如,x =[1,2]
  • 矩阵是一个二维数组
  • ([[1, 2],
  • [3, 4],
  • [5, 6]])
  • 张量是一个n维数组,n>2

TensorFlow.js具有用于标量、一维、二维、三维和四维张量等常见情况的实用函数,以及一些用于初始化张量的函数,这些函数对机器学习非常有用。

代码示例

tf.tensor():

// Pass an array of values to create a vector.
tf.tensor([1, 2, 3, 4]).print();

tf.scalar():

tf.scalar(3.14).print();

2.变量 & 运算

张量是一种不能被改变的数据结构。这意味着一旦设置好它们的值就无法更改。

但是,TensorFlow.js中引入了tf.variable()。它的真正用例是当我们需要频繁更改数据时,例如在机器学习中调整模型权重时。

代码示例:

const x = tf.variable(tf.tensor([1, 2, 3]));
x.assign(tf.tensor([4, 5, 6]));
x.print();

运算

在TensorFlow.js中有各种各样的运算。为了对张量进行数学计算,我们使用运算。张量是不可变的,因此所有运算总是会返回新的张量,而从不修改输入的张量。在这我们可以使用tf.variable()来节省内存。

让我们来看看一些运算:

tf.add()——按元素添加两个tf张量

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)

在TensorFlow.js中还有很多其他运算。你可以查看文档来了解它们。我将在这里演示另一个操作:tf.matmul()

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)

观看下面的视频来深入了解变量和操作:

3. 内存管理

内存管理是机器学习/深度学习任务的关键,因为它们通常需要消耗大量计算资源。

TensorFlow.js提供了两种主要的内存管理方法:

  1. tf.dispose()
  2. tf.tidy()

它们用不同的方式做着差不多同样的事情。

tf.tidy()

它执行所提供的函数fn,在执行函数fn之后,清除fn分配的所有中间张量(fn返回的张量除外)。

tf.tidy() 有助于避免内存泄漏。通常, tf.tidy() 中包装了对运算的调用,以实现自动内存清理。

代码示例:

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.Tensors张量。

代码示例:

const two= tf.scalar(2);
two.dispose()

LayersAPI

层是构建ML/DL模型时的主要成分。每个层通常会执行一些计算,将输入转换为输出。每一层都使用Tensorflow.js的CoreAPI。

层将自动创建和初始化它们需要的各种内部变量/权重。因此它基本上通过增加抽象级别来使生活变得更容易。

我们将使用LayerAPI制作一个简单的前馈网络示例。我们将构建的前馈网络如下:

图是我自己的

代码:

Index.html

<html>
<head>
<title></title>
<script src=”"> </script>
<script src=”main.js” type=”text/javascript”></script>
</head>
<body>
Tensorflow JS Demo
</body>
</html>

main.js

const model = tf.sequential();
//config for layer
const config_hidden = {
 inputShape:[3],
 activation:'sigmoid',
 units:4
}
const config_output={
 units:2,
 activation:'sigmoid'
}
//defining the hidden and output layer
const hidden = tf.layers.dense(config_hidden);
const output = tf.layers.dense(config_output);
//adding layers to model
model.add(hidden);
model.add(output);
//define an optimizer
const optimize=tf.train.sgd(0.1);
//config for model
const config={
optimizer:optimize,
loss:'meanSquaredError'
}
//compiling the model
model.compile(config);
console.log('Model Successfully Compiled');
//Dummy training data
const 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 labels
const y_train = tf.tensor([
 [0.2,0.8],
 [0.9,0.10],
 [0.4,0.6],
 [0.5,0.5]
])
//Dummy testing data
const 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:

领取阿里云¥1888元限时红包

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表