iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
0
自我挑戰組

Tensorflow.js初學筆記系列 第 12

Day11 TensorFlow 有關tensor本身的操作

  • 分享至 

  • xImage
  •  

這幾天寫下來,大致了解運作過程後,先回到基本了解一下TensorFlow.js
From TensorFlow Guide

Tensors and operations

首先最基本的在TensorFlow裡面,最重要的就是不同維度向量與矩陣資料結構的定義,在TensorFlow裡面的資料稱之為tensor,使用tf.tensor(value,shape,dtype)進行定義
value要放入資料,可以藉由巢狀的陣列來定義資料的維度
shape定義美個維度資料的大小
dtype資料的型別

以下是tensor的基本使用

const t1 =tf.tensor([[2,3],[1,3],[4,3]]);
console.log(t1.shape);
//[3, 2]
const shape = [2, 2];
const t2 = tf.tensor([1, 2, 3, 4], shape);
console.log(t2.shape);
//[2, 2]
const t3 = t1.reshape([2,3]);
console.log(t3.shape);
//[2, 3]
t3.array().then(array=>console.log(array));
//[[2, 3, 1],[3, 4, 3]]
t3.data().then(data=>console.log(data));
//[2, 3, 1, 3, 4, 3]
console.log(t3.arraySync());
//[[2, 3, 1],[3, 4, 3]]
console.log(t3.dataSync());
//[2, 3, 1, 3, 4, 3]

接下來就是利用TensorFlow.js內建的 Operations對tensor的基本數學操作
這些數學操作都不會改到原來tensor
而是會將結果作為回傳值回傳

const t1 =tf.tensor([[1,2],[3,4],[5,6]]);
const t2 =tf.tensor([[10,20],[30,40],[50,60]]);
t2.add(t1).print();
//Tensor[[11, 22],[33, 44],[55, 66]]
t2.sub(t1).print();
//Tensor[[9 , 18],[27, 36],[45, 54]]
t2.mul(t1).print();
//TensorTensor[[10 , 40 ],[90 , 160],[250, 360]]
t2.div(t1).print();
//Tensor[[10 , 10],[10, 10],[10, 10]]
const t3 = tf.tensor([1, 2, 4, -1]);
t3.sqrt().print();
//Tensor[1, 1.4142135, 2, NaN]

因為這些資料都很大,會佔據很多記憶體空間,所以必須要對記憶體內的資料進行管理
(這裡面淺扯到,TensorFlow適用WebGL當底,tensor所掌管的資料,其實都是在WebGL那處理的,所以必須自己做記憶體管理,有點像是一個人(tensor區域變數)往銀行(WebGL)裡存錢(tensor的擁有的資料),隨然人死了(在js內區域的tensor變數因為出函式掛掉),但錢(tensor的擁有的資料)還是會在銀行(WebGL)裡,所以要主動去註銷掉那些錢(tensor的擁有的資料)
釋放tensor內記憶體的資料的方式有兩種
一種是透過tf.dispose()另一種是透過tensor自帶的dispose()

const t1 =tf.tensor([[1,2],[3,4],[5,6]]);
t1.dispose();
const t2 =tf.tensor([[10,20],[30,40],[50,60]]);
tf.dispose(t2);

記住t1,t2再js定義此變數的scope還是存在,只是內部資料從記憶體中移除而已

因為可能會常常對tensor做數學操作,那中間過度的暫時資料肯定是要被棄用的,為了防止忘記釋放,所以tf內提供了tf.tidy()這樣的函式,這個函式在前幾converToTensor()裡面都有用到,除了回傳值外的所有內部宣告的tensor所掌控的記憶體都會被釋放。
可以透過tf.memory來查看記憶體狀況

//y=2x^2+12x+5
const x=tf.tensor([1,2,3,4,5])
const y = tf.tidy(() => {
    const x_squre=x.square();
    const x_squre_weight=tf.scalar(2)
    const x_weight=tf.scalar(12)
    const constant_num=tf.scalar(5)
    console.log('numTensors (in tidy): ' + tf.memory().numTensors);
    //numTensors (in tidy): 5
    return x_squre.mul(x_squre_weight).add(x.mul(x_weight)).add(constant_num);
})
console.log('numTensors (end tidy): ' + tf.memory().numTensors);
//numTensors (end tidy): 2
y.print();
//Tensor[19, 37, 59, 85, 115]

上一篇
Day10 TensorFlow.js: MNIST手寫數字辨識2
下一篇
Day12 TensorFlow.js 簡單的Model的設定、儲存、載入
系列文
Tensorflow.js初學筆記27
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言