TensorFlow Tensor Operations (math)

JS
S
JavaScript

Concise guide to mathematical operations on tensors in TensorFlow, essential for implementing machine learning algorithms and neural network computations.

1/*
2  Operations are functions that run on Tensors and return other Tensors.
3*/
4console.log('== Create a Tensor ==');
5const a = tf.tensor([1, 2, 3]); //1D Tensor shape 3
6console.log(a.rank, a.shape);
7console.log(a);
8console.log(a.print()); // data inside tensor
9
10// Data Only
11let data = a.dataSync();
12console.log(data);
13
14// Explicit shape&rank
15const explicit = tf.tensor([1, 2, 3, 4], [2,2]); //2D Tensor, Rank 2
16let explicitData = explicit.dataSync();
17console.log('explicitData', explicitData)
18
19// Test
20// [100,640,480,1] [sample, h, w, colors] // Shape 1 (colors), Rank 4
21const data1D = Array(100*640*480).fill(1);
22const ImageTensor = tf.tensor4d(data1D, [100, 640, 480, 1]);
23console.log('ImageTensor', ImageTensor)
24
25const xpto = tf.tensor([1, 2, 3,7], [4]); // Rank1, shape [4]
26console.log('xpto', xpto.print());
27
28// Tensor Operations
29// Addition
30const aOpPlus = tf.tensor([3, 8, 4, 6], [2, 2]); //Rank2, Shape[2,2]
31const bOpPlus = tf.tensor([4, 0, 1, -9], [2, 2]);
32/*
33  [[7, 8 ],
34  [5, -3]]
35*/
36aOpPlus.add(bOpPlus).print();
37console.log(aOpPlus.add(bOpPlus).shape);
38
39// Broadcasting
40/*
41  [[3, 8],
42  [4, 6]]
43     +
44  [[3, 0],
45  [8, 0]]
46*/
47const aOpPlusBroadcast = tf.tensor([3, 8, 4, 6], [2, 2]); //2d
48const bOpPlusBroadcast = tf.tensor([3, 8], [2]); //1d => brodcasted to [3, 0, 8, 0], [2, 2])
49aOpPlusBroadcast.add(bOpPlusBroadcast).print();
50
51// Scalar Broadcast
52/*
53  [[3, 8],
54  [4, 6]]
55     +
56  [[2, 2],
57  [2, 2]]
58*/
59const aOpScalarBroadcast = tf.tensor([3, 8, 4, 6], [2, 2]);
60const bOpScalarBroadcast = tf.scalar(2); // 2
61bOpScalarBroadcast.print();
62aOpScalarBroadcast.add(bOpScalarBroadcast).print();
63
64// Mean Squared Error (compare 2 similar images)
65console.log('Mean Squared Error');
66const aMse = tf.tensor([200, 176, 3, 34], [2,2]);
67const bMse = tf.tensor([213, 132, 0, 98], [2,2]);
68aMse.sub(bMse).print();
69// Mean of all values
70aMse.sub(bMse).mean().print(); // -7.5 *different
71aMse.sub(aMse).mean().print(); // 0 *exactly the same
72
73// We want all the numbers to be positive
74aMse.sub(bMse).square().mean().print();
75

Created on 8/18/2020