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.

    Pre-reqs

  2. 2.

    Loading the data generated in python

    •   
      import neighborhoods from '~/static/shared/neighborhoods.json'
        
      
        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'
        
      
        scaler-mean-x.json
        [114.6902816399287, 3.4014260249554367, 2.3436720142602496, 0.5928698752228164]
      
        scaler-var-x.json
        [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'
        
      
        scaler-mean-y.json
        [281340671.3761141]
      
        scaler-var-y.json
        [3091863947148531.5]
      
  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>
          <div class="col-sm-12">
            <div class="col-sm-6 field-label">Size (mts)</div>
            <input class="col-sm-6 field field-x"
                  v-model="size"
                  type="number">
      
            <div class="col-sm-6 field-label">Rooms</div>
            <input class="col-sm-6 field field-x"
                  v-model="rooms"
                  type="number">
      
            <div class="col-sm-6 field-label">Baths</div>
            <input class="col-sm-6 field field-x"
                  v-model="baths"
                  type="number">
      
            <div class="col-sm-6 field-label">Parking</div>
            <input class="col-sm-6 field field-x"
                  v-model="parking"
                  type="number">
      
            <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>
            </select>
          </div>
        </div>
      </div>
      
      <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>
      </div>
      
        
      
        
        data() {
          return {
            modelReady: false,
            size:180,
            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() {
          this.initializeScaler();
      
          this.initializeOneHotEncoder();
      
          this.loadModel();
        },
        
      
      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
        
      
          //Prediction
          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)
                                   .expandDims();
      
            return modelInput;
          },
        
      
        
      
          postProcessResults(outputs) {
            return this.unscale(outputs, this.meanY, this.deviationY);
          },
        
      
  6. 6.

    Making predictions

    •   
      
          ...
      
          predict() {
            //Transform Inputs
            let modelInput = this.preProcessInputs([
                                                     parseFloat(this.size),
                                                     parseFloat(this.rooms),
                                                     parseFloat(this.baths),
                                                     parseFloat(this.parking)
                                                   ], 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
      https://YOUR-USERNAME.github.io/YOUR-REPO/
      
  8. 8.

Comentarios

Entradas populares de este blog

Exposing Reactjs component methods to Javascript or non-reactjs applications

blog-static-generator-new If you want to integrate your javascript or non-reactjs application with a reactjs app and be able to access reactjs components and call their methods to execute actions or get information out of them, in this quick tips episode, you will learn how. Above is the vid and below you will find some useful notes. 1. Pre-reqs Have node.js installed 2. Exposing React JS to Javascript or non-reactjs applications ...

How to copy files from and to a running Docker container

Sometimes you want to copy files to or from a container that doesn’t have a volume previously created, in this quick tips episode, you will learn how. Above is the vid and below you will find some useful notes. 1. Pre-reqs Have Docker installed 2. Start a Docker container For this video I will be using a Jenkins image as an example, so let’s first download it by using docker pull docker pull jenkins/jenkins:lts ...

Brighten Up Your AEM Assets: How to Configure Default Backgrounds and Transparent Modes in Adobe Dynamic Media

Introduction The Importance of a Good Background Defining Your Default Background in AEM Defining Your Default Background in Dynamic Media Classic Transparent Images with fmt=png-alpha Explicit Background Colors with ?bgc Final Thoughts Introduction Welcome to our deep dive into the wonderful world of image backgrounds! In this post, we're going to explore how to configure Dynamic Media Classic in Adobe Experience Manager (AEM) to not only define a default background image but also how to get your images to pop with ...