<?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 Animesh Sharma on Medium]]></title>
        <description><![CDATA[Stories by Animesh Sharma on Medium]]></description>
        <link>https://medium.com/@animeshsharma97?source=rss-3ff71065eb21------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*W1X_TbZlq60Jn0xH.</url>
            <title>Stories by Animesh Sharma on Medium</title>
            <link>https://medium.com/@animeshsharma97?source=rss-3ff71065eb21------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:25:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@animeshsharma97/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[Music Generation using LSTMs in Keras]]></title>
            <link>https://medium.com/intel-student-ambassadors/music-generation-using-lstms-in-keras-9ded32835a8f?source=rss-3ff71065eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ded32835a8f</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Animesh Sharma]]></dc:creator>
            <pubDate>Fri, 28 Dec 2018 13:16:19 GMT</pubDate>
            <atom:updated>2019-01-03T19:16:05.436Z</atom:updated>
            <content:encoded><![CDATA[<p>Music is food for the soul. It is our constant companion during depressing times as well as in happiness. Talented musicians leave us in awe with their performances and have a lasting impression on our lives. This was my motivation to make this project with an A.I. flavor mixed into it. I want to generate a beautiful piece of music that will make people awed by how well a machine can mimic a human artist.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fdigitalaridboar&amp;url=https%3A%2F%2Fgfycat.com%2Fdigitalaridboar&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FDigitalAridBoar-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="320" height="240" frameborder="0" scrolling="no"><a href="https://medium.com/media/88f1cdb6e58725ca4f57b4258d3b5982/href">https://medium.com/media/88f1cdb6e58725ca4f57b4258d3b5982/href</a></iframe><p>But how can we use music for model training? What kind of preprocessing does music data need before going into a model? We will try to answer these questions in this article and then try to use the power of Deep Learning to generate some cool music.</p><p>First of all, what is music data?</p><p>Music is just an analog signal having two components, Amplitude and Frequency. We are going to explore the amplitude part of the music signal to predict the amplitude of the notes of a song based on the previous notes.</p><p>LSTMs are a variant of Recurrent Neural Networks and work well in cases of sequential data. They make predictions based on the current input as well as the previous inputs instead of treating every beat independently. Since a beat in music also depends on the previous beats, it is also a type of sequential data and an LSTM model is best suited for it.</p><p>Let’s get started!!</p><p>First of all, import the necessary modules and functions.</p><pre>import numpy as np<br>import pandas as pd<br>import pydub</pre><pre>from keras.layers import Dense, LSTM, LeakyReLU<br>from keras.models import Sequential, load_model<br>from scipy.io.wavfile import read, write</pre><p>If you want to train your model on mp3 files, the following lines of code will do the trick.</p><pre># converting mp3 file to wav file<br>sound = pydub.AudioSegment.from_mp3(&quot;Numb_piano.mp3&quot;)<br>sound.export(&quot;Numb.wav&quot;, format=&quot;wav&quot;)<br>sound = pydub.AudioSegment.from_mp3(&quot;Eminem.mp3&quot;)<br>sound.export(&quot;Eminem.wav&quot;, format=&quot;wav&quot;)</pre><p>If you already have your songs in wav format, then your code can be spared of the previous lines and you can directly load the data using the scipy read function.</p><pre># loading the wav files<br>rate, music1 = read(‘Numb.wav’)<br>rate, music2 = read(‘Eminem.wav’)</pre><p>Music files can become huge amounts of data as they are sampled and converted into discrete signals after reading from the wav files. Each second of music corresponds to around thousands of samples. The number of samples depends on the sampling rate used. By default, scipy will generate 44100 samples per second. We will not train on such a huge amount of data for now as we would like to observe how well a model can learn music by feeding it only some seconds of music.</p><pre># taking only some part of the songs and converting to a dataframe<br>music1 = pd.DataFrame(music1[0:400000, :])<br>music2 = pd.DataFrame(music2[0:400000, :])</pre><p>Now, let’s take a look at our data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b217196004ab273715e2638a210fc0d/href">https://medium.com/media/1b217196004ab273715e2638a210fc0d/href</a></iframe><p>We can clearly see that the music dataframe has two columns, namely the two channels of our song and it is of integer type. What we are going to do is train two models on the two channels and make predictions separately for both the channels and then concatenate the results to generate a piece of music.</p><h4>Data Pre-processing:</h4><p>To prepare our data for an LSTM network, we must first clear out how are we going to feed the data into our neural network. Since we are making two models for each channel, each model has access to one column of the music dataframe. Thus, to convert this into a supervised learning problem or rather a regression problem, we have to arrange our data in such a manner that using the data of first 3 rows, we can predict the value of the 4th row and by using the data of 2nd, 3rd, and 4th rows, we can make predictions for the 5th row and so on. Let us define a helper function to do this for us.</p><pre># function to create training data by shifting the music data <br>def create_train_dataset(df, look_back, train=True):<br>    dataX1, dataX2 , dataY1 , dataY2 = [],[],[],[]<br>    for i in range(len(df)-look_back-1):<br>        dataX1.append(df.iloc[i : i + look_back, 0].values)<br>        dataX2.append(df.iloc[i : i + look_back, 1].values)<br>        if train:<br>            dataY1.append(df.iloc[i + look_back, 0])<br>            dataY2.append(df.iloc[i + look_back, 1])<br>    if train:<br>        return np.array(dataX1), np.array(dataX2), np.array(dataY1), np.array(dataY2)<br>    else:<br>        return np.array(dataX1), np.array(dataX2)</pre><p>The function takes three arguments, the dataframe to shift, the number of features or samples you want in your data to predict the next sample and whether you want to generate training or test data. X1 and X2 represent the features of channels 1 and 2. Its dimension will depend on the <em>look_back </em>variable. If <em>look_back </em>is 3, it will be a numpy array of ( ,3) dimension. y1 and y2 are the dependent values for channels 1 and 2. Thus we have converted our music data into a form in which most machine learning algorithms operate on, i.e. a feature vector (X1 and X2) and labels or dependent variable (y1 and y2).</p><p>To generate our training data, let’s use some samples from both the songs with <em>look_back</em> of 3. Also, <em>train=True </em>will tell the function to generate training data, i.e. features as well as labels.</p><pre>X1, X2, y1, y2 = create_train_dataset(pd.concat([music1.iloc[0:160000, :],music2.iloc[0:160000, :]], axis=0), look_back=3, train=True)</pre><p>We had to use pd.concat to concatenate the music1 and music2 dataframes to generate training data having two different songs.</p><p>Now to prepare our test data, we just have to pass <em>train=False</em> to our helper function and we also pass different samples from the dataframes.</p><pre>test1, test2 = create_test_data(pd.concat([music1.iloc[160001 : 400000, :],music2.iloc[160001 : 400000, :]], axis=0), look_back=3, train=False)</pre><p>Let’s reshape our 2-d data into a 3-d vector as LSTMs expect the data to be 3d.</p><pre>X1 = X1.reshape((-1, 1, 3))<br>X2 = X2.reshape((-1, 1, 3))<br>test1 = test1.reshape((-1, 1, 3))<br>test2 = test2.reshape((-1, 1, 3))</pre><h4>Model Training:</h4><p>Now that our train and test data are completely ready, let’s use the Keras API to build our LSTM model.</p><pre># LSTM Model for channel 1 of the music data<br>rnn1 = Sequential()<br>rnn1.add(LSTM(units=100, activation=&#39;relu&#39;, input_shape=(None, 3)))<br>rnn1.add(Dense(units=50, activation=&#39;relu&#39;))<br>rnn1.add(Dense(units=25, activation=&#39;relu&#39;))<br>rnn1.add(Dense(units=12, activation=&#39;relu&#39;))<br>rnn1.add(Dense(units=1, activation=&#39;relu&#39;))</pre><pre>rnn1.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;)<br>rnn1.fit(X1, y1, epochs=20, batch_size=100)</pre><p>Thus we have an LSTM layer, 3 hidden layers, and an output layer. Adam optimizer is used with mean squared error as the loss criterion as it is one of the best choices for a regression task. We train our model for 20 epochs and batch size of 100 using ReLu activation function in each layer. Similarly, we can train our 2nd model (rnn2) for channel 2 in a similar manner.</p><p>We can then make predictions on our training data using the predict method of our models.</p><pre># making predictions for channel 1 and channel 2<br>pred_rnn1 = rnn1.predict(test1)<br>pred_rnn2 = rnn2.predict(test2)</pre><p>Let us now save our prediction and our test data into wav format for comparison.</p><pre># saving the LSTM predicitons in wav format<br>write(&#39;pred_rnn.wav&#39;, rate, pd.concat([pd.DataFrame(pred_rnn1.astype(&#39;int16&#39;)), pd.DataFrame(pred_rnn2.astype(&#39;int16&#39;))], axis=1).values)</pre><pre># saving the original music in wav format<br>write(&#39;original.wav&#39;,rate, pd.concat([music1.iloc[160001 : 400000, :], music2.iloc[160001 : 400000, :]], axis=0).values</pre><ul><li><a href="https://drive.google.com/open?id=1ujWxJUnHhHfEK_HypZZJVQpT3Fs0kXI9">pred_rnn_relu.wav</a></li><li><a href="https://drive.google.com/open?id=1VjzwaF5caFIc_OaAUw2JBNsQ_XEWflDP">original.wav</a></li></ul><p>You will see that the output generated has captured the music pretty well but it comes out to be distorted. To overcome this, I thought of various methods like increasing epochs, adding more layers, but these didn’t work. Then I observed that the predictions made are always positive values due to the ReLu activation but the original music data has some negative values too. Thus, I thought of using the LeakyReLu activation so that I can have some negative values in my predictions too and it worked like a charm. Let us edit our model building step to incorporate LeakyReLu.</p><pre>rnn1 = Sequential()<br>rnn1.add(LSTM(units=100, activation=&#39;linear&#39;, input_shape=(None, 3)))<br>rnn1.add(LeakyReLU())<br>rnn1.add(Dense(units=50, activation=&#39;linear&#39;))<br>rnn1.add(LeakyReLU())<br>rnn1.add(Dense(units=25, activation=&#39;linear&#39;))<br>rnn1.add(LeakyReLU())<br>rnn1.add(Dense(units=12, activation=&#39;linear&#39;))<br>rnn1.add(LeakyReLU())<br>rnn1.add(Dense(units=1, activation=&#39;linear&#39;))<br>rnn1.add(LeakyReLU())</pre><pre>rnn1.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;)<br>rnn1.fit(X1, y1, epochs=20, batch_size=100)</pre><p>Making the same changes in rnn2 and then running the predict method will give you the new predictions. Save them and compare them with the original piece of music. The distortion has disappeared and now it is quite difficult to differentiate between the original and the generated work.</p><p><a href="https://drive.google.com/open?id=1uWgtK9in3P3UkPCzUKLlzV0FrOFAFnaP">pred_rnn_leakyrelu.wav</a></p><p>Right now, I have tried to generate samples of two songs together due to hardware restrictions. If a lot of computing power is at your disposal, you can try to build a model for a lot of songs and also by increasing the <em>look_back </em>variable to increase the number of samples used to learn the next sample. You can also ask your friends and family to volunteer for a Turing test of your model for some fun!!</p><p>Let me know if you liked this article and if you have any suggestions or other cool ideas in the comments.</p><p><em>The complete code can be found </em><a href="https://github.com/animeshsharma97/Music-Generation"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ded32835a8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intel-student-ambassadors/music-generation-using-lstms-in-keras-9ded32835a8f">Music Generation using LSTMs in Keras</a> was originally published in <a href="https://medium.com/intel-student-ambassadors">Intel Student Ambassadors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Stack to decide your future]]></title>
            <link>https://medium.com/@animeshsharma97/a-stack-to-decide-your-future-2d64b1f314a5?source=rss-3ff71065eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d64b1f314a5</guid>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Animesh Sharma]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 13:30:16 GMT</pubDate>
            <atom:updated>2018-08-22T13:30:16.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvoJ5LaHksQSqVL1XArPwg.png" /></figure><p>Yesterday, I was discussing with my friend about the significance of our college grades in getting a job and I was really astonished to notice that our education system follows a very important concept which was hiding in plain sight all along. I am talking about ‘Stacks’, specifically in the context of Computer Science.<br>For those who are not familiar with stacks, here is what you need to know.<br>Stack is a simple data structure which supports operations in only one particular order, i.e. First In Last Out(FILO) or Last In First Out (LIFO). When we push data, it goes into the stack and the next data can be visualized as going on top of the previously pushed data. For example, in a stack of plates, you can only access the top element at a time. For accessing the second element you have to take out one of the plates. These figures will give you a clear understanding of what’s going on in stack operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dDdLRj7z_-bh-MIks4jerQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*3MtqW8HN_kLv8nXtuXkxDg.jpeg" /></figure><p>Now that all the geeky stuff is out of the way, let’s focus on the topic in hand.</p><p>We all have a stack named &#39;grades’. And all our marks get pushed into this stack as we go into higher classes in our school. Finally, when we are applying for admission in high school, our secondary school grade is seen from the stack of marks that have piled up since we joined school. Some students were excellent in Class 1 but that doesn’t matter in a stack. You can only access the top element at any time. So, your childhood marks are useless now, because what matters is just the top of the stack. When we pass high school, our marks are again pushed into this stack and while applying for colleges, only the top of the stack decides your future. Your secondary school grades are now irrelevant and only serve as a memoir of the (un)ideal student you once used to be. Colleges don’t care about that person, they care who you are right now and again the &#39;grades&#39; stack comes to their rescue as they assess you by a single grades.top() which is done in constant time instead of going through all your marks and wasting O(n) of their time.<br>After that comes the placement season and now, even the companies assess you by your GPAs in the years that you spent in your college. Your cumulative GPA gets pushed into the stack and is then seen by the recruiters to select or reject you. If you thought this was too monotonous, then wait, there’s more to come.<br>After you join your company, you gain valuable experience, gain new skills, be it technical or communication skills. These get pushed onto your stack and when you apply for another company, then guess what the recruiters would do! Is it an O(1) or an O(n) approach that they take? <br>I leave for you to decide the optimal solution. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d64b1f314a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Movie Ratings Prediction Server using Flask and LSTM in Keras (Part 2)]]></title>
            <link>https://medium.com/@animeshsharma97/movie-ratings-prediction-server-using-flask-and-lstm-in-keras-part-2-b0a84fb30ab7?source=rss-3ff71065eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0a84fb30ab7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Animesh Sharma]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 21:21:36 GMT</pubDate>
            <atom:updated>2018-08-11T21:22:02.849Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@animeshsharma97/movie-ratings-prediction-server-using-flask-and-lstm-in-keras-part-1-90933e8dbf88">part 1</a> of this series of posts, we focused on the NLP part of the problem and now it’s time to make try something even cooler by turning this machine learning problem to a web application.</p><p>We are going to use Flask and Python to setup our web server. Our choice of flask is based on the fact that it is very easy to setup and has many extensions which makes deploying small scale web applications like ours very easy and efficient. According to the main page of Flask:</p><blockquote><em>Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.</em></blockquote><p>For more information on how to setup and use flask, refer the <a href="http://flask.pocoo.org/docs/1.0/">official flask doc</a>. I would highly recommend checking out <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world">this</a> blog if you want to dive deep into the world of flask. It has some very awesome articles ranging from getting you started with flask to making full fledged applications.</p><p>In this article, I will not be covering the HTML and CSS aspects of the application. We will be focusing on building the it’s backend.</p><p>The folder structure of our app will be something like this:</p><pre>movie_ratings_app/<br>    __init__.py<br>    forms.py<br>    movie_ratings_server.py<br>    output.py<br>    rnn.h5<br>    routes.py<br>    train.tsv<br>    vocab.txt<br>    templates/<br>        &lt;html pages&gt;</pre><pre># __init__.py</pre><pre>from flask import Flask</pre><pre>app = Flask(__name__)<br>app.config[&#39;SECRET_KEY&#39;] = &#39;any secret string&#39;</pre><pre>from movie_ratings_app import routes</pre><p>In these four simple lines, we have configured flask by creating the application object as an instance of class Flask imported from the flask package. We have set a ‘SECRET_KEY’ as we are working with wtf-forms which uses csrf tokens for increasing security of our apps. For knowing how csrf protects our apps, refer <a href="http://kylebebak.github.io/post/csrf-protection">this</a> page.</p><pre># movie_ratings_server.py</pre><pre>from movie_ratings_app import app</pre><p>This single line imports the application instance defined in __init__.py file. That in turn calls the routes.py where our endpoint for the index page is defined. We also have to create a simple forms.py for our user input form.</p><pre># forms.py</pre><pre>from flask_wtf import FlaskForm<br>from wtforms import TextAreaField , SubmitField<br>from wtforms.validators import DataRequired</pre><pre>class Form(FlaskForm):<br>    review = TextAreaField(&#39;Your review goes here : &#39;, validators=[DataRequired()])<br>    submit = SubmitField(&#39;Predict rating&#39;)</pre><p>Before defining routes.py, there is still one final thing to do. For our app to make use of the saved model weights that we calculated in part 1, we have to import those too. So, we have to create a python script which loads the data, does the same pre-processing that we talked about in the last post and loads the saved model. For more information on this part, refer <a href="https://medium.com/@animeshsharma97/movie-ratings-prediction-server-using-flask-and-lstm-in-keras-part-1-90933e8dbf88">part 1</a> of this post.</p><p>Suppose we have created the aforementioned file with the name output.py, it’s time to finally write our endpoint.</p><pre># routes.py</pre><pre>import numpy as np</pre><pre>from flask import render_template</pre><pre>from movie_ratings_app import app</pre><pre>#importing Form class from forms.py<br>from movie_ratings_app.forms import Form</pre><pre>#importing model and tokenizer from output.py<br>from movie_ratings_app.output import tokenizer, model_rnn</pre><pre>@app.route(&#39;/&#39;,methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def index():<br>    form = Form()<br>    if form.validate_on_submit():<br>        # extracting text from the form<br>        text = form.review.data</pre><pre>        # converting text to bag of words<br>        matrix = tokenizer.texts_to_matrix([text])<br>        # making predictions<br>        pred = np.argmax(model_rnn.predict(matrix.reshape((1, 1, n_words))) ) + 1</pre><pre>        # rendering star.html which loads different images on the           basis of prediction<br>        if pred == 1:<br>            return render_template(&#39;star.html&#39;, user_image=&quot;<a href="https://dublinbookworm.files.wordpress.com/2015/07/1-star2.jpg?w=300&amp;h=60">https://dublinbookworm.files.wordpress.com/2015/07/1-star2.jpg?w=300&amp;h=60</a>&quot;)<br>        elif pred == 2:<br>            return render_template(&#39;star.html&#39;, user_image=&quot;<a href="https://dublinbookworm.files.wordpress.com/2015/07/2-star2.jpg?w=300&amp;h=60">https://dublinbookworm.files.wordpress.com/2015/07/2-star2.jpg?w=300&amp;h=60</a>&quot;)<br>        elif pred == 3:<br>            return render_template(&#39;star.html&#39;, user_image=&quot;<a href="https://dublinbookworm.files.wordpress.com/2015/07/3-star2.jpg?w=300&amp;h=60">https://dublinbookworm.files.wordpress.com/2015/07/3-star2.jpg?w=300&amp;h=60</a>&quot;)<br>        elif pred == 4:<br>            return render_template(&#39;star.html&#39;, user_image=&quot;<a href="https://dublinbookworm.files.wordpress.com/2015/07/4-star2.jpg?w=300&amp;h=60">https://dublinbookworm.files.wordpress.com/2015/07/4-star2.jpg?w=300&amp;h=60</a>&quot;)<br>        else:<br>            return render_template(&#39;star.html&#39;, user_image=&quot;<a href="https://dublinbookworm.files.wordpress.com/2015/07/5-star2.jpg?w=300&amp;h=60">https://dublinbookworm.files.wordpress.com/2015/07/5-star2.jpg?w=300&amp;h=60</a>&quot;)<br>    return render_template(&#39;index.html&#39;, form=form)</pre><p>And finally, we have built a simple web application which has a form on the index page and based on the text entered in the form, it makes predictions and displays the star rating in a different html page.</p><h3>Sample Ouputs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPFNCceNxdMtfBce0lQ45w.png" /><figcaption>A positive review</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8GYeNU5ELOOh9cy4KbLBw.png" /><figcaption>Star rating given to the positive review</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqjs0phw1LpoDS0zMeQkHw.png" /><figcaption>A negative review</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lhn4n9AJQnofjjOEj4UIw.png" /><figcaption>Star rating given to the negative review</figcaption></figure><p>Things which I am not covering in this post is how to make the html pages which you can check on my GitHub <a href="https://github.com/animeshsharma97/Movie-ratings-server">repo</a>. The code on my repo might look different than what it is here as I have added some extra features to it. I have changed some parts here for keeping things simple. You can also refer this <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world">blog</a> as I mentioned above to get a better understanding of how to work with Flask.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0a84fb30ab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Movie Ratings Prediction Server using Flask and LSTM in Keras (Part 1)]]></title>
            <link>https://medium.com/analytics-vidhya/movie-ratings-prediction-server-using-flask-and-lstm-in-keras-part-1-90933e8dbf88?source=rss-3ff71065eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/90933e8dbf88</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Animesh Sharma]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 21:14:23 GMT</pubDate>
            <atom:updated>2020-08-08T16:43:29.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_K4k4veirKKl5W5HGtMfg.jpeg" /></figure><p>Deep Learning is one of the most hyped buzzwords right now and the justification lies in its large number of applications and its power to solve complex problems ranging from Computer Vision to NLP and much more. In this series of posts, I would like to give you a brief introduction to using Deep Learning for solving a NLP problem. We are trying to predict the ratings (out of 5) for a movie based on its review. In this section we will look at basic pre-processing of text data that must be done in order to make our data ready to be used as an input into our LSTM model.</p><p>RNNs are a family of neural networks which are suitable for learning sequential data. Since our data consists of movie reviews, we know for sure that this is a type of sequential data — because the sentiment of a word depends on words before or after it. For example, ‘The movie is good’ and ‘The movie is not good’ portray opposite sentiments, but to find that out we have to keep track of the word before ‘good’. RNNs have been made to address this specific issue. LSTM is just a variant of RNN which has been observed to give better results in comparison to vanilla RNNs in a variety of problems. For in-depth analysis of LSTM, please refer to <a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/">this</a> awesome blog.</p><p>And for more applications of RNN, refer <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">this</a> blog.</p><h3><strong>Pre-processing</strong></h3><p>Let us start with importing the necessary modules in python.</p><pre>import numpy as np<br>import pandas as pd<br>import re</pre><pre>from collections import Counter<br>from keras.preprocessing.text import Tokenizer<br>from keras.utils import np_utils<br>from keras.models import Sequential, load_model<br>from keras.layers import Dense, Dropout, LSTM, Bidirectional<br>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br>from sklearn.cross_validation import train_test_split</pre><p>Next, let us define the functions to extract clean tokens from the text, add it to a vocabulary stored as a Counter in python, save the counter in a text file, load that text file and finally clean the data based on the loaded tokens. We also have to remove some words which are present as stopword in the default nltk stopwords. We also add some blank spaces as stopwords which can be found in the corpus after cleaning the data.</p><pre># removing some words and adding some to increase accuracy<br>stopwords = stopwords.words(&#39;english&#39;)<br>newStopWords = [&#39;&#39;, &#39; &#39;, &#39;  &#39;, &#39;   &#39;, &#39;    &#39;, &#39; s&#39;]<br>stopwords.extend(newStopWords)<br>stopwords.remove(&#39;no&#39;)<br>stopwords.remove(&#39;not&#39;)<br>stopwords.remove(&#39;very&#39;)<br>stop_words = set(stopwords)</pre><pre>def clean_doc(doc, vocab=None):<br>    tokens = word_tokenize(doc)<br>    # keeping only alphabets    <br>    tokens = [re.sub(&#39;[^a-zA-Z]&#39;, &#39; &#39;, word) for word in tokens] <br>    # converting to lowercase<br>    tokens = [word.lower() for word in tokens]<br>    # removing stopwords<br>    tokens = [w for w in tokens if not w in stop_words]<br>    # removing single characters if any<br>    tokens = [word for word in tokens if len(word) &gt; 1]<br>    if vocab:<br>        tokens = [w for w in tokens if w in vocab]<br>        tokens = &#39; &#39;.join(tokens)        <br>    return tokens</pre><pre>def add_doc_to_vocab(text, vocab):<br>    tokens = clean_doc(text)<br>    vocab.update(tokens)</pre><pre>def save_list(lines, filename):<br>    data = &#39;\n&#39;.join(lines)<br>    file = open(filename, &#39;w&#39;)<br>    file.write(data)<br>    file.close()<br>    <br>def load_doc(filename):<br>    file = open(filename, &#39;r&#39;)<br>    text = file.read()<br>    file.close()<br>    return text</pre><p>The dataset consists of 156060 rows and 4 columns out of which only two columns, i.e. ‘Phrase’ and ‘Sentiment’ are of importance to us. The ‘Phrase’ column contains various phrases and the ‘Sentiment’ column contains the sentiment number assigned to the corresponding phrase ranging from 0 to 4. 0 denoting extremely negative sentiment and 4 denoting highly positive sentiment.</p><p>After loading the dataset, we split the it into training and test data and then apply the various functions, that we have written earlier, on the loaded data. You can get the dataset <a href="https://drive.google.com/file/d/1aw3cItu0Cs-54qoYa1CFB09wECNySDlN/view?usp=sharing">here</a>.</p><pre>df = pd.read_csv(&#39;train.tsv&#39;, delimiter=&#39;\t&#39;)<br>X = df[&#39;Phrase&#39;]<br>y = df[&#39;Sentiment&#39;]<br>y = np_utils.to_categorical(y)</pre><pre># splitting into training and testing data<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 0)</pre><pre># removing unnecessary data<br>del df, X, y</pre><pre># creating a vocabulary of words<br>vocab = Counter()<br>len_train = len(X_train)<br>for i in range(len_train):<br>    text = X_train.iloc[i]<br>    add_doc_to_vocab(text , vocab)</pre><pre>print(len(vocab))<br># print the 20 most common words<br>print(vocab.most_common(20))</pre><pre># removing tokens which occur less than 3 times.<br>min_occurance = 2<br>tokens = [k for k,c in vocab.items() if (c &gt;= min_occurance &amp; len(k) &gt; 1)]</pre><pre># saving the vocabulary for futute use<br>save_list(tokens, &#39;vocab.txt&#39;)</pre><pre># loading the saved vocabulary<br>vocab = load_doc(&#39;vocab.txt&#39;)<br>vocab = vocab.split()<br>vocab = set(vocab)</pre><pre>train_doc = []<br>for i in range(len_train):<br>    text = X_train.iloc[i]<br>    doc = clean_doc(text, vocab)<br>    train_doc.append(doc)</pre><pre>test_doc = []<br>len_test = len(X_test)<br>for i in range(len_test):<br>    text = X_test.iloc[i]<br>    doc = clean_doc(text, vocab)<br>    test_doc.append(doc)</pre><p>We create a set of vocab so as to remove duplicates. We then use this set to clean our data and prepare it to be input into our LSTM model.</p><p>After the data is cleaned, I found that certain rows had no tokens in them as every token was removed after data cleaning. This is something that we should take care of before training our model.</p><pre># storing indexes where no tokens are present<br>index_train = []<br>for i in range(len(train_doc)):<br>    if len(train_doc[i]) == 0 :<br>        index_train.append(i)<br>    <br>index_test = []<br>for i in range(len(test_doc)):<br>    if len(test_doc[i]) == 0 :<br>        index_test.append(i)</pre><pre># dropping the unnecessary data<br>train_doc = np.delete(train_doc, index_train, 0)<br>test_doc = np.delete(test_doc, index_test, 0)<br>y_train = np.delete(y_train, index_train, 0)<br>y_test = np.delete(y_test, index_test, 0)</pre><p>After all the data has been cleaned we have to convert our text data to a form suitable for the LSTM model. For this, we can use the Keras Tokenizer class to convert our data into a bag of words model.</p><pre>tokenizer = Tokenizer()<br>tokenizer.fit_on_texts(train_doc)</pre><pre>X_train = tokenizer.texts_to_matrix(train_doc, mode=&#39;binary&#39;)<br>X_test = tokenizer.texts_to_matrix(test_doc, mode=&#39;binary&#39;)<br>n_words = X_test.shape[1]</pre><h3>Model Building</h3><p>Now for the final step. Let’s start building our model and find its accuracy on our test data. I have used Bidirectional LSTM as our model so that the model performs even better than vanilla LSTM. In Bidirectonal LSTM, both the previous and future inputs are taken into account for making predictions on the current input. For a detailed explanation of Bidirectonal networks, refer this <a href="https://en.wikipedia.org/wiki/Bidirectional_recurrent_neural_networks">wikipedia</a> page.</p><pre># LSTM Model<br>model = Sequential()<br>model.add(Bidirectional(LSTM(100, activation=&#39;relu&#39;), input_shape=(None,n_words)))<br>model.add(Dropout(0.2))<br>model.add(Dense(units=50, input_dim=100, activation=&#39;relu&#39;))<br>model.add(Dense(5, activation=&#39;softmax&#39;))<br>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><pre># fitting the LSTM model<br>model.fit(X_train.reshape((-1, 1, n_words)), y_train, epochs=20, batch_size=100)</pre><pre># finding test loss and test accuracy<br>loss_rnn, acc_rnn = model.evaluate(X_test.reshape((-1, 1, n_words)), y_test, verbose=0)</pre><pre># saving model weights<br>model.model.save(&#39;rnn.h5&#39;)</pre><pre># loading saved weights<br>model_rnn = load_model(&#39;rnn.h5&#39;)</pre><p>You can experiment by making the model deeper and adding different number of neurons in each layer. Using this model, we get an accuracy of around 60–65%. We also save the models so that we can use the model weights further to make predictions without training for future use or when you want to do real time predictions on a web application. For making such a web app using LSTM, stay tuned for the <a href="https://medium.com/@animeshsharma97/movie-ratings-prediction-server-using-flask-and-lstm-in-keras-part-2-b0a84fb30ab7">second part</a> of this post where we will explore how to convert your model into a web application.</p><p>You can find the complete implementation <a href="https://github.com/animeshsharma97/Movie-ratings-server">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90933e8dbf88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/movie-ratings-prediction-server-using-flask-and-lstm-in-keras-part-1-90933e8dbf88">Movie Ratings Prediction Server using Flask and LSTM in Keras (Part 1)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>