How to create a simple TensorFlow.js project

This instruction shows how to create a simple project to predict the y value of equation y = 1.2x + 5 based on TensorFLow.js

Create a webpage

Create a webpage ‘predict.html’:

<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Traffic Flow Predictor</title>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
</head>
<body>
    <div id="output"></div>
    <script>
        // Create Training Data
        const xs = tf.tensor([0, 1, 2, 3, 4]);
        const ys = xs.mul(1.2).add(5);

        // Output xs and ys
        document.getElementById('output').innerText = xs.dataSync();
        document.getElementById('output').innerText+= "\n" + ys.dataSync();
    </script>
</body>
</html>

Use web browser to open ‘predict.html’, if the TensorFlow.js is loaded correctly, you should see the following text:

0,1,2,3,4
5,6.199999809265137,7.400000095367432,8.600000381469727,9.800000190734863

Train the model

Use the following code to train the model.

    // Define a Linear Regression Model
    const model = tf.sequential();
    model.add(tf.layers.dense({ units: 1, inputShape: [1] }));

    // Specify Loss and Optimizer
    model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });

    // Train the Model
    model.fit(xs, ys, { epochs: 500 }).then(() => { trainingCompleted() });

    // Training completed
    function trainingCompleted() {
        document.getElementById('output').innerText += "\n" + "Model training completed!";
    }

Use the model to predict the value of y when x = 10

// Use the model
function predict() {
    let result = model.predict(tf.tensor([Number(10)]));
    result.data().then(y => {
        document.getElementById('output').innerText += "\n" + Number(y);
    });
}

Source Code

<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Traffic Flow Predictor</title>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
</head>
<body>
    <div id="output"></div>
    <script>
        // Create Training Data
        const xs = tf.tensor([0, 1, 2, 3, 4]);
        const ys = xs.mul(1.2).add(5);

        // Output xs and ys
        document.getElementById('output').innerText = xs.dataSync();
        document.getElementById('output').innerText += "\n" + ys.dataSync();
        
        // Define a Linear Regression Model
        const model = tf.sequential();
        model.add(tf.layers.dense({ units: 1, inputShape: [1] }));

        // Specify Loss and Optimizer
        model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });

        // Train the Model
        model.fit(xs, ys, { epochs: 500 }).then(() => { trainingCompleted() });

        // Training completed
        function trainingCompleted() {
            document.getElementById('output').innerText += "\n" + "Model training completed!";

            predict();
        }

        // Use the model
        function predict() {
            let result = model.predict(tf.tensor([Number(10)]));
            result.data().then(y => {
                document.getElementById('output').innerText += "\n" + Number(y);
            });
        }
    </script>
</body>
</html>

How to install TensorFlow on Windows 11 (WSL2, Ubuntu 22.04) with CUDA and cuDNN

This instruction shows how to install TensorFlow on Windows 11 (WSL2, Ubuntu 22.04) with CUDA and cuDNN.

Lod in

Reference: https://codensync.com/blog/2023/11/23/how-to-install-ubuntu-22-04-on-wsl2-on-windows-11/

Install virtual environment management system Miniconda

Run the following command to install the latest 64-bit version of the installer and then clean up after themselves.

mkdir -p ~/miniconda3
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh
bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3
rm -rf ~/miniconda3/miniconda.sh

After installing, run the following commands initialize for bash and zsh shells:

~/miniconda3/bin/conda init bash
~/miniconda3/bin/conda init zsh

You need to close and re-open the current shell for changes to take effect. First, exit the shell:

exit

Then, run the following command to enter the shell:

ubuntu

Run the following command to verify the installation:

conda --version

Create a virtual environment with Python 3.11

Run this command to create a virtual environment ‘tf’ with python version 3.11

conda create --name tf python=3.11

Activate virtual environment ‘tf’

conda activate tf

There will be a ‘(tf)’ prefix in the command line. If you want to deactivate current virtual environment, run the following command:

conda deactivate

Activate virtual environment ‘tf’, install gcc and g++, install CUDA11.8

conda activate tf

Install gcc and g++

sudo apt update
sudo apt install gcc g++

Run the following commands to download and install CUDA 11.8

wget https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda_11.8.0_520.61.05_linux.run
sudo sh cuda_11.8.0_520.61.05_linux.run

Install cuDNN 8.6

Install cuDNN 8.6.0.163

pip install nvidia-cudnn-cu11==8.6.0.163

To check the installation location of cudnn:

python -c "import nvidia.cudnn;print(nvidia.cudnn.__file__)"

Add environment variables

Add environment variables:

# Need to adapt to your cudnn installation location:
export CUDNN_PATH="$HOME/miniconda3/envs/tf/lib/python3.11/site-packages/nvidia/cudnn"
export LD_LIBRARY_PATH="$CUDNN_PATH/lib":"/usr/local/cuda/lib64"

export PATH="$PATH":"/usr/local/cuda/bin"

Check CUDA version:

nvcc --version

Install TensorFlow 2.14.1

Install TensorFlow 2.14.1

pip install tensorflow==2.14.1

Check installation version

pip show tensorflow

Check if GPU acceleration can be enabled:

python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"

If you see the following text, the GPU acceleration can be enabled.

[PhysicalDevice(name=’/physical_device:GPU:0′, device_type=’GPU’)]

How to install Ubuntu 22.04 on WSL2 on Windows 11

This instruction shows how to install Ubuntu 22.04 on WSL2 on Windows 11.

Check available Linux distros

The first step is to check the available Linux distros on your system. Right-click the Windows icon and choose Terminal (Admin) to open Terminal and run the following command:

wsl -l -o

The command should return all the available Linux distros:

The following is a list of valid distributions that can be installed.
Install using ‘wsl.exe –install ‘.

NAME FRIENDLY NAME
Ubuntu Ubuntu
Debian Debian GNU/Linux
kali-linux Kali Linux Rolling
Ubuntu-18.04 Ubuntu 18.04 LTS
Ubuntu-20.04 Ubuntu 20.04 LTS
Ubuntu-22.04 Ubuntu 22.04 LTS
OracleLinux_7_9 Oracle Linux 7.9
OracleLinux_8_7 Oracle Linux 8.7
OracleLinux_9_1 Oracle Linux 9.1
openSUSE-Leap-15.5 openSUSE Leap 15.5
SUSE-Linux-Enterprise-Server-15-SP4 SUSE Linux Enterprise Server 15 SP4
SUSE-Linux-Enterprise-15-SP5 SUSE Linux Enterprise 15 SP5
openSUSE-Tumbleweed openSUSE Tumbleweed

Install Ubuntu 22.04

You can install a distro using the NAME by running:

wsl --install -d Ubuntu-22.04

After installation, you can enter a UNIX username and password. This username could be different than the Windows username and will be used in Ubuntu. Windows will launch the installed Ubuntu and enter the command line mode.

List installed Ubuntu

If you want to check the installed Linux distros, run the following command:

wsl -l -v

Launch Ubuntu

To manually launch Ubuntu on WSL2, run the following command:

ubuntu2204

Log out Ubuntu

Run the following command to log out Ubuntu.

exit

Unregister Ubuntu

If you want to uninstall an installed system, run the following command:

wsl --unregister <DistroName>

In this case, run the following command will uninstall Ubuntu 22.04:

wsl --unregister Ubuntu-22.04