Ir al contenido principal

House price prediction 2/4: Using Tensorflow.js, Vue.js and Javascript

A series about creating a model using Python and Tensorflow and then importing the model and making predictions using Javascript in a Vue.js application, above is the vid and below you will find some useful notes.
  • Here, in part 2 of this series, I will take the model, the data for pre and post processing and finally predict using Vue.js.
    In the first post, called House price prediction 1/4: Using Keras/Tensorflow and python, I talked about how to create a model in python, pre-process a dataset I've already created, train a model, post-process, predict, and finally about creating different files for sharing some information about the data for use on the second part.
    Then in part 3 I will show how does one hot encoding works.
    And finally in part 4 normalizing the inputs and its importance.
    If you want to see a simpler model and how it integrates with a javascript application using Tensorflow.js and Vue.js you can check my previous post: How to import a Keras model into a Vue.js application using Tensorflow.Js, where I also show how to publish the web site into Github Pages.
  1. 1.


  2. 2.

    Loading the data generated in python

      import neighborhoods from '~/static/shared/neighborhoods.json'
        ["envigado", "envigado abadia", "envigado aburra sur", "envigado alcal", "envigado alcala", "envigado alquerias de san isidro", "envigado alto de las flores", "envigado alto de misael", "envigado altos de misael", "envigado andalucia", "envigado antillas", "envigado av poblado", "envigado b margaritas", "envigado barrio mesa", "envigado barrio obrero"
      import meanX from '~/static/shared/scaler-mean-x.json'
      import varX from '~/static/shared/scaler-var-x.json'
        [114.6902816399287, 3.4014260249554367, 2.3436720142602496, 0.5928698752228164]
        [572.865809011588, 0.37646855468812057, 0.2255615608745523, 0.4053680561513214]
      import meanY from '~/static/shared/scaler-mean-y.json'
      import varY from '~/static/shared/scaler-var-y.json'
  3. 3.

    The Html and Data Object for getting the inputs for the model

      <div class="train-controls">
        <h2 class="section-header">House/Apartment parameters</h2>
          <div class="col-sm-12">
            <div class="col-sm-6 field-label">Size (mts)</div>
            <input class="col-sm-6 field field-x"
            <div class="col-sm-6 field-label">Rooms</div>
            <input class="col-sm-6 field field-x"
            <div class="col-sm-6 field-label">Baths</div>
            <input class="col-sm-6 field field-x"
            <div class="col-sm-6 field-label">Parking</div>
            <input class="col-sm-6 field field-x"
            <div class="col-sm-6 field-label">Neighborhood</div>
            <select class="col-sm-6 neighborhood field" v-model="neighborhood">
              <option disabled value="">Please select one</option>
              <option v-for="(item, index) in neighborhoods" v-bind:key="index" v-html="item" :value="index"></option>
      <div class="predict-controls">
        <h2 class="section-header">Predicting</h2>
        <div class="col-sm-6 field-label">Predicted Value</div>
        <div class="col-sm-6 element field" v-html="predictedValue"></div>
        <button class="col-sm-12 element button--green" v-on:click="predict" :disabled="!modelReady">Predict</button>
        data() {
          return {
            modelReady: false,
            rooms: 5,
            baths: 2,
            parking: 0,
            neighborhood: 0,
            predictedValue:'Model not loaded!',
            selected: '',
            neighborhoods: neighborhoods
  4. 4.

    Methods for initializing the model

    • Initialize everything when the vue.js component is mounted
        mounted() {
      Load the Keras Model
        methods: {
          async loadModel() {
            this.model = await tf.loadLayersModel('shared/model/model.json');
            this.modelReady = true;
            this.predictedValue = 'Ready for making predictions';
  5. 5.

    Methods for pre/post processing the data

    • These are the methods needed for pre or post processing the data
          initializeOneHotEncoder() {
          scale(value, mean, deviation) {
          unscale(value, mean, deviation) {
      The methods below are in charge of defining which pre or post processing methods to call and on which features
          preProcessInputs(inputs, neighborhood) {
            let modelInput = tf.tensor1d(inputs);
            let neighborhoodTensor = tf.tensor1d(this.dictionary[this.neighborhoods[neighborhood]]);
            modelInput = this.scale(modelInput, this.meanX, this.deviationX);
            modelInput = modelInput.concat(neighborhoodTensor)
            return modelInput;
          postProcessResults(outputs) {
            return this.unscale(outputs, this.meanY, this.deviationY);
  6. 6.

    Making predictions

          predict() {
            //Transform Inputs
            let modelInput = this.preProcessInputs([
                                                   ], this.neighborhood);
            //Get prediction
            const prediction = this.model.predict(modelInput);
            //Transform Outputs
            this.predictedValue = Math.ceil(this.postProcessResults(prediction).dataSync()[0]);
            console.log(this.neighborhoods[this.neighborhood], prediction.dataSync()[0], this.predictedValue);
  7. 7.

    Add the House price prediction web page using tensorflow.js and vue.js into github pages

    • Generate the tensorflow.js app into a subfolder
      npm run generate:use-subfolder
    • To make it a bit easier clone your repo into another folder
      git clone http://YOUR-REPO.git REPO-NAME-gh-pages
    • Create a branch named gh-pages that is not connected to the master branch
      git checkout --orphan gh-pages
    • Delete everything and copy the contents of the dist folder here
    • Finally add all the files and commit and push the changes
      git add -A
      git commit -m "gh pages branch"
      git push origin gh-pages
    • Go into your account
  8. 8.


Entradas populares de este blog

Creating a Mongo replicaset using docker: Mongo replicaset + Nodejs + Docker Compose

This is a Docker tutorial for creating a Mongo replica set using docker compose and also a couple more containers to experiment with the replica set, above is the vid and below you will find some of the steps followed.
StepsPre-reqsHave node.js installedAnd docker installed (make sure you have docker-compose as well)Create a container for defining configurations for a mongo instanceCreate a container for setting up the replica setCreate a simple node app using expressjs and mongoose (A modified version from the previous video)Create a docker-compose file with the mongo and setup containers and two additional containers for experimenting with the replica setBuild, Run and experiment with your new containers Create a dockerfile for the first mongo container (not really needed but you could configure more stuff if needed)Include container with mongo preinstalled: FROM mongoCreate default/working directory: WORKDIR /usr/src/configsCopy mongo's configurations file into the container

Creating a Docker container for a NodeJs application: Express + Mongo + Docker Compose

This is a Docker tutorial for creating a NodeJs container using expressjs and mongoose, above is the vid and below you will find the steps followed.
StepsPre-reqsHave node.js installedAnd docker installed (make sure you have docker-compose as well)Create an simple node app using expressjs and mongooseModify your container and create a docker-compose fileBuild and Run your new container Create your simple node appInitialize the node appnpm initInstall the dependencies for our appnpm install --save express mongoose Create the database.jsCreate the index.js Create a dockerfileInclude container with node preinstalled: FROM nodeCreate default/working directory: WORKDIR /usr/src/appCopy package.json to workdir and install dependencies (which we will need in this case😊): COPY package.json .RUN npm install Copy the rest of the app (just the index.js file in this case)COPY . .Expose the port required for reaching our expressjs appEXPOSE 3000Add a command to run when this container is star…

Creating a tensorflow.js + vue.js simple application in javascript

This is a Tensorflow.js tutorial for creating a simple application using Vue.js, above is the vid and below you will find some of the steps followed. Steps Pre-reqs Have node.js installed Create the Vue.js application using nuxt.js Add support for tensorflow.js in vue.js and add a simple model Add the simple tensorflow.js model using vue.js into github pages Create the Vue.js application using nuxt.js Install vue.js cli npm install -g vue-cli Create a base Vue.js app using the starter kit from Nuxt vue init nuxt-community/starter-template simple-vue-tensorflow Start the dev server npm run dev Create empty component components/TensorflowExample.vue Add the component into the page pages/index.vue …