<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ayush Bihani on Medium]]></title>
        <description><![CDATA[Stories by Ayush Bihani on Medium]]></description>
        <link>https://medium.com/@bihani37?source=rss-7fd58fd262a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8x9K7WxZ7dfaYeHU.</url>
            <title>Stories by Ayush Bihani on Medium</title>
            <link>https://medium.com/@bihani37?source=rss-7fd58fd262a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:44:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bihani37/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Training Your Tensorflow Model on Android]]></title>
            <link>https://medium.com/@bihani37/training-your-tensorflow-model-on-android-ed8d81bc559e?source=rss-7fd58fd262a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed8d81bc559e</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ayush Bihani]]></dc:creator>
            <pubDate>Sun, 30 Dec 2018 11:15:21 GMT</pubDate>
            <atom:updated>2018-12-30T11:15:21.822Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine Learning is a computationally intensive task. It requires large processing power for achieving state of the art accuracy. Training machine learning models are usually done on computers, clusters ( large scale networked computers ). In recent times, there has been great progress in harnessing mobile computing power to train machine learning models. One such project is <a href="http://ai.googleblog.com/2017/04/federated-learning-collaborative.html"><em>Federated Learning</em></a><em>, </em>enabling mobile phones to collaboratively learn a shared prediction model while keeping all the training data on device, decoupling the ability to do machine learning from the need to store the data in the cloud. This essentially involves training the model on the mobile device.</p><p>In this tutorial, I will be showing a simple representative example of training your tensorflow model on Android.</p><h4>Creating Model</h4><p>To get started with, we need to first create the model using Tensorflow. To keep the example simple, I will be creating a model that tries to find the coefficients of a straight line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/638be84a948e42c68bf9c29628870bc0/href">https://medium.com/media/638be84a948e42c68bf9c29628870bc0/href</a></iframe><p>The slope and constant ( W&amp;b) are initially assigned random values. These values will be fine-tuned based on the input training data which is done on an Android device.</p><p>The model is defined by the equation <em>“y=x*W+b”</em> representing a generic “<em>y=mx+c”</em> line equation. Lines 14–16 define the loss function and the optimizer which are used to fit the model to the training data with minimal error. Notice there is a no training involved. The above code snippet only defines the model. To use this model in android, we have to freeze the graph. Lines 35–36 save the model into a protocol buffer format.</p><p>Save and run the program. This will generate a “graph.pb” file containing the model.</p><h4>Creating Android Application</h4><p>Create a new Android Project on Android studio and add the following dependency in Gradle build file of your project. This dependency includes all the libraries needed to use tensorflow on android. Add the “graph.pb” in the assets directory and sync your android project.</p><pre>compile &#39;org.tensorflow:tensorflow-android:+</pre><p>Once gradle is finished syncing the project with the above dependency, you can start using the tensorflow library on android.</p><p>Below is the UI we will be making for the application. I will not be focusing much on Android code such as creating UI, Activities, rather just focus on the training part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vxElmpZYmV1yb2tlxIXTw.jpeg" /></figure><p>There are two inputs, slope and the constant. The user needs to supply these inputs. These inputs are used to generate random training data for the model. For any arbitrary X value, we evaluate Y based on the equation (Y = Mx+c ). We had assigned random values in the python model (-5, 10 for W and b respectively). Eventually what we intend to do is supply the randomly generated data to the model and hope it learns the slope(W) and constant(b) of the line as close as possible to the values input by the user.</p><p>To use the model, we first need to load the model. The following code snippet loads the model and returns a tensorflowInferenceInterface instance which contains the graph definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d629a0de87f3fe527d46f32b887a6f9f/href">https://medium.com/media/d629a0de87f3fe527d46f32b887a6f9f/href</a></iframe><p>All we need to supply it is the asset manager and model path ( present in the assets directory).</p><p>Once the model is loaded, it can be used for training and prediction. In the function <em>“train”,</em> the model is fed with randomly generated data. In the following code snippet, we first create generate a serialized representation of the loaded model as a graph. Line 3 creates a serialized graph. A tensorflow graph represents the flow of computations in the model. The Session instance encapsulates the environment in which a <a href="https://www.tensorflow.org/api_docs/java/reference/org/tensorflow/Graph.html">Graph</a>is executed to compute tensors. The serialized model graph (<em>def</em>) is loaded into the new Graph instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/255ba7fe2a62afd65a8c29f4b707b914/href">https://medium.com/media/255ba7fe2a62afd65a8c29f4b707b914/href</a></iframe><p>We can now start training the model. By using the “<em>Random” </em>function in Java, we can generate random number X and correspondingly Y using the equation Y=Mx+c.<em> </em>Tensorflow expects input training data as tensors. Hence we first create tensors (line 12–13) that contain randomly generated data. The values defined by “m” and “c” are the slope and constant the user enters. It is important to feed it the type of data as defined in the python model, here “<em>Float</em>”.</p><p>All the computations in tensorflow are performed within a session. A session runner runs the necessary graph fragments to execute every operation required to evaluate the <a href="https://www.tensorflow.org/api_docs/java/reference/org/tensorflow/Tensor.html">Tensor</a>s. We then feed the data to the model using the “<em>session.runner()” </em>with the corresponding name of the placeholders, here “<em>input</em>” and “<em>target</em>” which are the input and output placeholder in the python model. All that is left to do is to add the operation we want to perform. If you’re unaware of what operation is, it is a Graph node that performs computation on Tensors. Our operation here is “train” as defined in the model. The addTarget method makes run() to execute the operation we just added. Periodically, I am adding the weights as the training occurs to display it on the UI. This wraps up the main code pertaining to the training of model in android.</p><p>The entire source code is available on <a href="https://github.com/ayushbihani/Training-TensorflowModel-On-Android"><em>github</em></a><em>. </em>Below is an example of how close the model comes to predicting the slope and constant of a line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GF3qECBpAFbPg7Nfn2nopg.jpeg" /><figcaption>Main Activity that requires slope and constant input.</figcaption></figure><p>The above input represents a line “Y=4x + 5”. These values are used to randomly generate (X, Y) points for the given line. When we click on the train button, the application takes these input values, generates random data and trains the model with it, hoping to learn the slope and constant of the line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jN7S5ias5R5VsP3sYSXYyQ.jpeg" /><figcaption>Output</figcaption></figure><p>The above image shows the outcome of the training. The model has almost learned the parameters of the line. Initially, the model had the parameters -5 and 10 as the slope and constant of the line and at each interval (500 iterations) it moves closer to the actual parameters of the line (y=4x+5). At the end of 3500 iterations, it has almost learned the parameters. The constant is nearly there and hopefully, after a few more iterations, the slope will most likely converge as close to 4 as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed8d81bc559e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying TensorFlow model on Android]]></title>
            <link>https://medium.com/@bihani37/deploying-tensorflow-model-on-android-726d01659636?source=rss-7fd58fd262a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/726d01659636</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deploy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ayush Bihani]]></dc:creator>
            <pubDate>Tue, 24 Oct 2017 19:10:25 GMT</pubDate>
            <atom:updated>2017-10-24T19:10:25.159Z</atom:updated>
            <content:encoded><![CDATA[<p>Part2</p><p>Welcome to the part 2 of deploying Tensorflow Model on Android. The prerequisite for this tutorial is part 1. If you haven’t checked it out, please do before proceeding as we will be using code from part 1. In this part of the series, we will focus on creating the neural network model.</p><p>We will be using TensorFlow to write our neural network model. There are variants of neural network architecture but the one I’ll be using is a feed forward neural network. If you’re unfamiliar with the concept of neural network, refer to this <a href="https://brilliant.org/wiki/feedforward-neural-networks/">post</a>. A feed forward neural network is an artificial neural network where in connections between nodes (neurons) do not form a cycle. The flow of data occurs in a forward fashion. The simplest kind of neural network is a <em>single-layer perceptron</em> network, which consists of a single layer of output nodes; the inputs are fed directly to the outputs via a series of weights. In this way it can be considered the simplest kind of feed-forward network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*hczvrCYgU_JQt5sx-UGM1A.gif" /><figcaption>A one layer perceptron model. [Source: Wikipedia]</figcaption></figure><p>Without wasting any time, let’s build our very own perceptrons. So open up a new file called <em>‘neuralNetworkModel.py’</em> and add the following imports. Make sure all your imports are working.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/722ab5374b52bfe05c0cb353951e1d62/href">https://medium.com/media/722ab5374b52bfe05c0cb353951e1d62/href</a></iframe><p>Our first function would be to retrieve training data from ‘<em>dataHelpers.py’</em> . This function just imports data and logs any error if any.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06e70037ccaccfc2c73f4d95f92214fa/href">https://medium.com/media/06e70037ccaccfc2c73f4d95f92214fa/href</a></iframe><p>We have already converted all the feature dataset from text to integer but our labels(Y) are still categorical in nature. Some machine learning algorithms inherently work well with one hot encoding, hence we convert our labels into a one hot representation vector. The length of the vector is equal to the number of classes( in our case, 6). Each column of the vector is a unique label. Suppose if the class label is 4, the one hot vector would have a “1” in the column “4” and the rest will be zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*0PU2g_ZMVpr4WCm51U4uhw.png" /><figcaption>one hot representation example.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e324f040ce816108136b97086953017/href">https://medium.com/media/0e324f040ce816108136b97086953017/href</a></iframe><p>The <em>“getBatch” </em>function just returns a part of the dataset after converting labels into one hot vectors. We’ll see why we return batches of dataset while training our neural network.</p><p>We’re done with the helper functions we need for our neural network model and only left with defining our model. Our neural network model will be a simple feed forward network with two hidden layers. Each hidden layer will have 800 nodes. Feel free to change the number of nodes in the hidden layers. You can also add more hidden layers without changing much except for defining the new hidden layer. These changes will affect the accuracy of our model, so finding the optimal number of nodes and hidden layers can greatly improve our model’s performance. Apart from the hidden layers, there is an input layer and an output layer. The number of nodes in the input layer is equal to the length of our feature vector and the number of nodes in the output layer is 6 (number of classes). There are few more model parameters such as learning rate, number of training cycles, amount of data to feed into the model at each iteration(batch Size). You can change these value to see which gives you the best result ( a learning rate of 0.01 is optimal).</p><p>We define two placeholders, <em>“inputTensor”</em> and <em>“outputTensor”</em>. These are used to feed data to the neural network while training. The inputTensor is for feeding feature vectors and the <em>“outputTensor”</em> is for feeding the one hot label vector. Next, we define our weights and biases(randomly assigned a value) for each hidden layer. For example, if our input layer had 10 nodes and the first hidden layer has 5 nodes, then the total number of weights assigned between input layer and hidden layer would be 50. That is each node of a layer is connected to all the nodes of the next layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245de4dd5e17ded79fe8bb184483a91b/href">https://medium.com/media/245de4dd5e17ded79fe8bb184483a91b/href</a></iframe><p>Next we will create our perceptrons. These are simple linear equations of the form “<em>f(x) = Wx + b”, </em>where W is weight, b is bias and x is the input (feature vector). We will use a reLu activation function on the output of <em>“f(x)”. </em>Activation function in simplest terms is<em> </em>used to scale the value of “<em>f(x)</em>” to either 0 or 1 ( output depends on the kind of function used). A threshold is used to determine the output, that is, if “f(x)” is above a certain value, the output is 1 else 0. “<em>output”</em> is the layer we pull our predictions on. It has a softmax activation that scales the output on every output node between 0 and 1. After defining our loss function and optimizer, we can begin with the training of the model. Since we want to deploy this model on android, we would like to save the model. Tensorflow uses graphs to represent your computation in terms of the dependencies between individual operations. The nodes and edges of the graph, indicate how individual operations are composed together. We save the graph using tensorflow function in line 42.</p><p>Similarly the Saver class adds ops to save and restore variables to and from <em>checkpoints</em>. It also provides convenience methods to run these ops.Checkpoints are binary files in a format which map variable names to tensor values. These checkpoints files contain weight values. The line 40–60 deal with model training. While training we do not feed the entire dataset to the model at once, rather we do it in batches ( large batches seems to have a degrading effect on the quality of model). Hence we feed 100 data points at one time using the <em>“getBatch” </em>function. The data is fed into placeholders we earlier defined.By the end of training you should be getting an accuracy of 60% (bad, but works for now).</p><blockquote>A placeholder is simply a variable that we will assign data to at a later date. It allows us to create our operations and build our computation graph, without needing the data. In Tensorflow terminology, we then <em>feed</em> data into the graph through these placeholders.</blockquote><p>After finishing training the model, we freeze the model. What do we mean by freezing? From the tensorflow documentation, we have “ <em>weights are held in separate checkpoint files, and there are </em><em>Variable ops in the graph that load the latest values when they&#39;re initialized. It&#39;s often not very convenient to have separate files when you&#39;re deploying to production, so there&#39;s the </em><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py"><em>freeze_graph.py</em></a><em> script that takes a graph definition and a set of checkpoints and freezes them together into a single file.</em></p><p><em>What this does is load the </em><em>GraphDef, pull in the values for all the variables from the latest checkpoint file, and then replace each </em><em>Variable op with a </em><em>Const that has the numerical data for the weights stored in its attributes It then strips away all the extraneous nodes that aren&#39;t used for forward inference, and saves out the resulting </em><em>GraphDef into an output file” . </em>The output file is in a proprietary file format “ProtoBufs”. For a deeper understanding of how saving the model works, refer to <a href="https://blog.metaflow.fr/tensorflow-saving-restoring-and-mixing-multiple-models-c4c94d5d7125"><em>this</em></a><em> </em>excellent post<em>.</em></p><p>One important point to note while saving the graph is the variable name of our input to the model and the output from the model. Notice the line 90–92, where we define our entry to the model’s input node(<em>“inputTensor”</em>) and the output node(<em>“output”</em>). We will be using the same variable names in the android application when we used the model to predict.</p><p>So now we have defined our model and other helper functions. Now all we need to do is call these functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffd36df901fdce6915aacd805571a7ea/href">https://medium.com/media/ffd36df901fdce6915aacd805571a7ea/href</a></iframe><p>In the above code, we split the data into training and testing sets. This is a simple split of the dataset. A better split would be to use the cross_validation from sklearn. I leave this as an exercise. After running the entire code, you should have several files in your directory which includes your model<em>(“optimizedTfModel.pb”</em>) , checkpoints, etc. Our main focus will be the protoBuf files which will be used in android application.</p><p>That’s it for Part 2 of the series. In the next part we will be looking at how to setup our android application, load necessary libraries and finish writing the android application boilerplate. Hope this was helpful and stay tuned for part 3 :D .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=726d01659636" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Tensorflow Model on Android,]]></title>
            <link>https://medium.com/@bihani37/deploying-tensorflow-model-on-android-310a906e599?source=rss-7fd58fd262a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/310a906e599</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ayush Bihani]]></dc:creator>
            <pubDate>Mon, 16 Oct 2017 14:35:02 GMT</pubDate>
            <atom:updated>2017-10-16T14:35:02.075Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*x9HTNZkMWpiiaieUOB1b5A.jpeg" /></figure><p>Hey Everyone! Welcome to a tutorial series on deploying Tensorflow models on Android. Fortunately there are enough blogs, tutorials on deploying Tensorflow models on the cloud but there aren’t many on deploying models on Android phones especially for models related to text Classification. So here I attempt to bridge the gap and show an example on how to do Question classification and deploy the model on Android to classify further locally. Lets get in!</p><p>This series will be divided into 4 parts.</p><ul><li>Part 1 will be writing the model in python.</li><li>Part 2 will be writing our neural network model.</li><li>Part 3 will be to setup android application with necessary libraries.</li><li>Part 4 will be implementing the complete android application.</li></ul><p>For Question classification data, I will be using the dataset from <a href="http://cogcomp.org/Data/QA/QC/train_1000.label">cogcomp</a>. The format of the questions are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*HyUKX9MXE_lmbKwDVNDhFw.png" /><figcaption>Sample dataset questions</figcaption></figure><p>The first word represent a label(called as class also). The questions and the label is separated by “:”. The questions can belong to one of the 5 categories( ABBR, ENTY, DESC, HUM, LOC and NUM). These abbreviations stand for:</p><ul><li>ABBR- Abbreviation</li><li>LOC- Location</li><li>DESC- Description</li><li>ENTY- Entity</li><li>NUM- Numeric</li><li>HUM- Human</li></ul><p>Next open up a new file and call it “DataHelpers.py”. This file will have functions that load, manipulate, clean data before feeding it into any Machine-Learning algorithms.</p><p>Go ahead and add these imports.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e57ba771a752693b0601b947dfe4bee/href">https://medium.com/media/7e57ba771a752693b0601b947dfe4bee/href</a></iframe><p>To start off with data manipulation, we need to first import data from the text file<em> ‘data.txt</em>’, you previously saved. The function ‘readData’ reads from the text file where the dataset is stored and splits each sentence into label(Y), that is the class it belongs to and the question itself and stores them into two lists(<em>‘labels’</em> and<em> ‘questions’</em>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0da9a456d1a8abfcff7e135f3daddc7c/href">https://medium.com/media/0da9a456d1a8abfcff7e135f3daddc7c/href</a></iframe><p>Our first step in data cleaning would be to remove stop-words (words such as ‘the’, ’if’, ‘a’….) that do not contribute to the meaning of a sentence. The function ‘<em>remove_stopwords’ </em>removes unnecessary words from the dataset. The function ‘<em>cleanInput’ </em>removes unnecessary characters such as apostrophes, question marks, white spaces, commas, slashes, etc from a string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/291d051c4e43040f7ce321cc09d1bfee/href">https://medium.com/media/291d051c4e43040f7ce321cc09d1bfee/href</a></iframe><p>But wait! Will the machine learning algorithm understand text data? Can it perform mathematical operations on Strings? No. So how do we represent a text in numeric format that can be understood by the algorithm? Well, One way of doing this would be to create a vocabulary. A vocabulary can be thought of as a set containing of all the unique words it has come across, in the dataset( <em>here, the questions dataset).</em> We could do this by using a <em>Counter </em>in Python which make sure there are no duplicate words stored. Simultaneously we would also want to just add English words and not random characters, or special symbols, etc.<em> NLTK</em> provides a wordNet lexicon containing a large subset of the English dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17788c8f1cb559979542bd9fb96b0f2d/href">https://medium.com/media/17788c8f1cb559979542bd9fb96b0f2d/href</a></iframe><p>You might have also noticed that we are saving the words in a text file. Why should we do this? This is the trick part for deploying the model in Android. We would want our vocabulary to be the same in Python and Android implementation, that is we want a consistent vocabulary. There has to be an exact same implementation of <em>‘DataHelpers.py’ </em>in Android as well ( of-course its Java counterpart) because our model is built in python with the data-Format received from <em>‘DataHelpers.py’</em> and will require the same format in Android as well. We’ll get into this deeper in part 3 and 4.</p><p>Okay so now we have successfully created our vocabulary but it does not solve our problem with numeric representation of words. How do we link a word with an index of sort? The lines 14–16 do exactly that. <em>‘word2index’ </em>is a dictionary where the key is word and the value is an index( some arbitrary number assigned). Each word is arbitrarily assigned an index ranging from 1 to the total number of words.</p><p>Another way of representing the text data would be to count the no of occurrences of words in the sentence. I’ll be showing both the methods of representing text data.</p><blockquote>To make this more clear, take a look at this example where words are assigned an ID. Notice that same words have the same index assigned.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*HB2lHaLGIWYt4hVrFme5Jg.png" /><figcaption>An example of how a sentence split into individual words.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*RiIbI8kN2vFb39pHmzqEig.png" /><figcaption>Assigning index to each word.</figcaption></figure><blockquote>Here is another example of representing text data where words are assigned a count (number of times the word has occurred in a sentence).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*HB2lHaLGIWYt4hVrFme5Jg.png" /><figcaption>Taking similar example.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*xX48uvw-X4ostRRuD2meog.png" /><figcaption>Frequency of each word appearing in the above sentence.</figcaption></figure><p>We now have a mapping between each word in the vocabulary and an assigned integer. The next step would be to map the text data with a numeric(Integer) value( called <strong>word embedding</strong>). The words may also be called as <strong>features</strong>. Each question in the dataset is converted into a vector containing word embedding. There are various representation of word vectors as show in the above diagrams. ID’s can be assigned to each by referencing ‘word2index’ dictionary, and for frequency based vectors the count for each word in the sentence. The length of all word vectors must be uniform( same length). For this exercise, i will be assuming the length of the word vector equal to the total no of words in our vocabulary set. That is,</p><blockquote>length of WordVector = len(vocabularySet)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01590a31205e144357655d1614cc7b11/href">https://medium.com/media/01590a31205e144357655d1614cc7b11/href</a></iframe><p>The function ‘<em>featureExtractionFrequency</em>’ converts all the sentences in the dataset into word vectors using frequency based(Count) representation of word. Every sentence has a fixed vector length(value of <em>lengthOfVector</em>). For every word in the sentence, <em>word2index</em> dictionary is used to retrieve the index of the word. Hence it is certain that the index of the last word in <em>word2index</em> is equal to <em>lengthOfVector. </em>This index can be used to access an element in the word vector(here newFeatureVector) and add 1 to it ( increase count everytime the word is encountered)<em>.</em></p><blockquote>Think of the index as an identity of the word and if the word is present in a sentence, we use this identity and change its property(here, add 1). It is as simple as adding 1 at the index assigned to a word(word2index) in the ‘newFeatureVector’.</blockquote><p>In the below code snippet, index based representation is used. The length of the word vector should be uniform as said earlier. We fix the length of each word vector to length(number of words) of the longest sentence in the dataset and use <em>‘word2index’</em> to map the words in the sentence with their respective indexes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*rJKCiQqVdilXDvvs9o5wVg.png" /><figcaption>Example of word vector using index representation.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e74f776631abef0ecd73124b02475c1/href">https://medium.com/media/4e74f776631abef0ecd73124b02475c1/href</a></iframe><p>You can use either of the two functions for feature extraction. In this example I will be using the count based representation. Now all we have to do is call these functions. So lets go ahead and do that!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e227d0e06cac476084bcda8dab5c1916/href">https://medium.com/media/e227d0e06cac476084bcda8dab5c1916/href</a></iframe><p>This concludes part 1 of the series. The other parts will be published soon. So Stay Tuned !</p><p>You can find the entire code on my <a href="https://github.com/ayushbihani/TensorflowOnAndroid">github</a>. Any feedback would be helpful to improve the content :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=310a906e599" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>