Artificial Intelligence 7 min read

Mastering Tensors in TensorFlow.js: From Scalars to Neural Networks

This guide explains the fundamentals of tensors in TensorFlow.js—including scalars, vectors, and higher‑dimensional tensors—demonstrates how to convert real‑world data such as the Titanic dataset into tensors, and shows how to build, compile, and train a simple neural network model using appropriate layers, loss functions, and optimizers.

Taobao Frontend Technology
Taobao Frontend Technology
Taobao Frontend Technology
Mastering Tensors in TensorFlow.js: From Scalars to Neural Networks

Tensor is the most basic data structure in TensorFlow, similar to one‑dimensional or multi‑dimensional arrays. In TensorFlow.js a JavaScript array can be directly converted to a Tensor. A Tensor has three parts: values (the actual numbers or array), shape (the dimensions, inferred from values if not provided), and dtype (data type such as 'float32', 'int32', 'bool').

Scalar – 0D Tensor

A Tensor that contains a single number is called a scalar.

<code>scalar = tf.tensor(3.14);
// scalar is better defined with tf.scalar
tf.scalar(3.14).print();</code>

Vector – 1D Tensor

A one‑dimensional array is a vector.

<code>vector = tf.tensor([1, 2, 3], [3]);
vector = tf.tensor1d([1, 2, 3]).print();</code>

Common Tensor Operations

TensorFlow.js also provides semantic methods such as tf.tensor2d, tf.tensor3d, tf.tensor4d, tf.tensor5d, and tf.tensor6d.

<code>const a = tf.tensor([[1,2],[3,4]],[2,2],'int32');
console.log('shape:', a.shape);
console.log('dtype', a.dtype);
a.reshape([4]).print();</code>

Real‑world Data Tensor Conversion – Data Preprocessing

Using the classic Kaggle Titanic dataset as an example, we illustrate common data representation and preprocessing steps.

Feature Binarization

Convert categorical values such as gender (male/female) into 0 and 1.

Integer Encoding

Encode ports of embarkation (C, Q, S) as 1, 2, 3.

Data Imputation

Missing values in the Age column can be filled using the mean, class‑wise mean, or model‑based prediction.

Feature Discretization

Continuous values like age can be bucketed (e.g., 0‑5 → 1, 6‑10 → 2, etc.) to simplify modeling.

Other Tensor Data Examples

3D tensors are common for time‑series data such as stock prices.

4D tensors are used for image data (width, height, channels, samples).

5D tensors are used for video data (width, height, channels, frames, samples).

Neural Network Model

A model consists of Input, Layer, Loss, Optimizer, and Output.

Layer – Model Layer

Most data can be processed with a dense (fully‑connected) layer; images use convolutional layers; sequential data such as text use LSTM layers.

Loss Function

The loss function measures the difference between predictions and true values. Use mean‑squared error for regression and binary cross‑entropy for binary classification.

Optimizer

Optimizers adjust the network based on the loss, e.g., gradient descent or Adam.

Example

<code>const model = tf.sequential();
model.add(tf.layers.dense({units: 250, inputShape: [8]}));
model.add(tf.layers.dense({units: 175}));
model.add(tf.layers.dense({units: 150}));
model.add(tf.layers.dense({units: 10, activation: 'softmax'}));
model.compile({
  optimizer: tf.train.adam(),
  loss: 'sparseCategoricalCrossentropy',
  metrics: ['accuracy']
});</code>

Visualize and experiment with neural networks using the TensorFlow Playground.

JavaScriptneural networkdata preprocessingtensorflow.jstensors
Taobao Frontend Technology
Written by

Taobao Frontend Technology

The frontend landscape is constantly evolving, with rapid innovations across familiar languages. Like us, your understanding of the frontend is continually refreshed. Join us on Taobao, a vibrant, all‑encompassing platform, to uncover limitless potential.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.