šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

First machine learning app with TensorflowJs and Javascript – house price prediction

Let's build the first tiny machine-learning app with Javascript. We will use TensorflowJs, a Javascript machine-learning library developed by Google.

The scope of the app will be to predict the price of a house based on the number of rooms. We will just input the number of rooms and it will try to guess what will be the approximate price for that house.

Checkout the below video to see the app in action:

Setting up the basic UI

The markup is quite simple. Just a button and the input for the room number.

<p>How many rooms should your house have?</p>
<input type="number" />
<button disabled>Predict price</button>

Let's now look a bit at the starting Javascript.

The machine learning model training will be async, so we will need to first wait for that model to be ready. Therefore, we will have the button disabled until the model is fully trained:

const input = document.querySelector('input')
const button = document.querySelector('button')

const trainModel = ()=> {
  // train the Tensorflow model here
}

const enableUi = ()=> {
  // enable the button when the model is ready
  button.disabled = false
  button.addEventListener('click', () => {
    let numberOfRooms = parseInt(input.value)
    // predict the price based on numberOfRooms
  })
}

trainModel().then(enableUi)

Using the CSS attribute selector we will style the button to show it as disabled until the execution of the trainModel() function is ready.

TensorflowJs sample app

Importing the TensorflowJs library

Before we actually start we will need to import the TensorflowJs library.

For this example, I've used codepen so went to Settings / Js and imported TensorflowJs.

In case, you want to use npm you can do:

import * as tf from '@tensorflow/tfjs'

Training the TensorflowJs model

From here the actual machine learning part starts. The first step will be to configure the model.

Next, we will define the training data. Basically, we will just give it some current [number_of_rooms - price] values so that the model will have some sense of how to do the data prediction.

Of course, the more training data we give it, the better. In normal circumstances, this training data will come from huge data sources but will only use just a few of them for the simplicity of the example.

Both the data and labels will be stored as tensors structures:

const numberOfRooms = tf.tensor1d([2,4,3,8,5,6])
const prices = tf.tensor1d([190,374,245,732,420,560])

Finally, we will use this data to train the model.

model.fit(numberOfRooms, prices, {epochs: 1000})

The epochs parameter will set how many times our training datasets will be taken to train our model. Wrote more about TensorflowJs epochs here.

At the end of this step the full code of the trainModel() function will look as below:

const buildModel = ()=> {
  // define and configure the model
  model = tf.sequential()
  model.add(tf.layers.dense({
    units: 1,
    inputShape: [1]
  }))

  model.compile({
    optimizer: 'sgd',
    loss: 'meanSquaredError'
  })

  // define the training data
  const numberOfRooms = tf.tensor1d([2,4,3,8,5,6])
  const prices = tf.tensor1d([190,374,245,732,420,560])

  // train the model
  return model.fit(numberOfRooms, prices, {epochs: 1000})
}

Making a prediction with TensorflowJs

The final step will be to use the model that we trained. We will read the number of rooms and will predict the price.

let numberOfRooms = parseInt(input.value)
const prediction = model.predict(tf.tensor1d([numberOfRooms]))

After that we will store the response from model.predict() in a javascript variable and display it:

const expectedPrice = parseInt(prediction.arraySync()[0])
alert(`You should expect a rent of approx: ${expectedPrice} $` )

Below are some examples of the outputs based on the inputs:

number_of_rooms: 2 -> price: 173$
number_of_rooms: 8 -> price: 728$
number_of_rooms: 1 -> price: 81$

Keep in mind that the price prediction was generated without explicit programming of how to perform that task. We did not give any direct formula for this calculation.

Below is the code for the button's action listener:

  button.addEventListener('click', () => {
    let numberOfRooms = parseInt(input.value)
    const prediction = model.predict(tf.tensor1d([numberOfRooms]))
    const expectedPrice = parseInt(prediction.arraySync()[0])
    alert(`You should expect a rent of approx: ${expectedPrice} $` )
  })

Here is the link for the full working codepen

Next, you can check out an example of how to use a pre-trained TensorflowJs model in Javascript to do object detection for images.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *