bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/AI/TensorFlow
AI•TensorFlow

TensorFlow Operations

  • Add
  • Subtract
  • Multiply
  • Divide
  • Square
  • Reshape

Tensor Addition

You can add two tensors using tensorA.add(tensorB) :

Example

const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);
// Tensor Addition
const tensorNew = tensorA.add(tensorB);
// Result: [ [2, 1], [5, 2], [8, 3] ]

Tensor Subtraction

You can subtract two tensors using tensorA.sub(tensorB) :

Example

const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);
// Tensor Subtraction
const tensorNew = tensorA.sub(tensorB);
// Result: [ [0, 3], [1, 6], [2, 9] ]

Tensor Multiplication

You can multiply two tensors using tensorA.mul(tensorB) :

Example

const tensorA = tf.tensor([1, 2, 3, 4]);
const tensorB = tf.tensor([4, 4, 2, 2]);
// Tensor Multiplication
const tensorNew = tensorA.mul(tensorB);
// Result: [ 4, 8, 6, 8 ]

Tensor Division

You can divide two tensors using tensorA.div(tensorB) :

Example

const tensorA = tf.tensor([2, 4, 6, 8]);
const tensorB = tf.tensor([1, 2, 2, 2]);
// Tensor Division
const tensorNew = tensorA.div(tensorB);
// Result: [ 2, 2, 3, 4 ]

Tensor Square

You can square a tensor using tensor.square() :

Example

const tensorA = tf.tensor([1, 2, 3, 4]);
// Tensor Square
const tensorNew = tensorA.square();
// Result [ 1, 4, 9, 16 ]

Tensor Reshape

The number of elements in a tensor is the product of the sizes in the shape.

Since there can be different shapes with the same size, it is often useful to reshape a tensor to other shapes with the same size.

You can reshape a tensor using tensor.reshape() :

Example

const tensorA = tf.tensor([[1, 2], [3, 4]]);
const tensorB = tensorA.reshape([4, 1]);
// Result: [ [1], [2], [3], [4] ]

Previous

TensorFlow.js Tutorial

Next

TensorFlow Models

This chapter

Overview
4

Lessons

16m

Read time

1. TensorFlow.js Tutorial2. TensorFlow Operations3. TensorFlow Models4. TensorFlow.js Visor

On this page

Tensor AdditionTensor SubtractionTensor MultiplicationTensor DivisionTensor SquareTensor Reshape