{"id":1480,"date":"2019-02-18T01:13:23","date_gmt":"2019-02-18T01:13:23","guid":{"rendered":"http:\/\/kusuaks7\/?p=1085"},"modified":"2023-06-30T10:32:34","modified_gmt":"2023-06-30T10:32:34","slug":"how-to-build-a-neural-network-with-keras","status":"publish","type":"post","link":"https:\/\/www.experfy.com\/blog\/ai-ml\/how-to-build-a-neural-network-with-keras\/","title":{"rendered":"How to build a Neural Network with Keras"},"content":{"rendered":"<p><strong>Keras is one of the most popular Deep Learning libraries out there at the moment and made a big contribution to the\u00a0commoditization of artificial intelligence. It is simple to use and it enables you to build powerful Neural Networks in just a few lines of code. In this post, you will discover how you can build a Neural Network with Keras that predicts the sentiment of user reviews by categorizing them into two categories: positive or negative. This is called Sentiment Analysis and we will do it with the famous imdb review dataset. The model we will build can also be applied to other Machine Learning problems with just a few changes.<\/strong><\/p>\n<p>Note that we will not go into the details of Keras or Deep Learning. This post is intended to provide you with a blueprint of a Keras Neural Network and to make you familiar with its implementation.<\/p>\n<p>&nbsp;<\/p>\n<h2>Table of Contents:<\/h2>\n<ul>\n<li>What is Keras?<\/li>\n<li>What\u00a0is Sentiment Analysis?<\/li>\n<li>The imdb Dataset<\/li>\n<li>Import Dependencies and get the Data<\/li>\n<li>Exploring the Data<\/li>\n<li>Data Preparation<\/li>\n<li>Building and Training the Model<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<h2>What is Keras?<\/h2>\n<p>Keras is an open source python library that enables you to easily build Neural Networks. The library is capable of running on top of TensorFlow, Microsoft Cognitive Toolkit, Theano, and MXNet. Tensorflow and Theano are the most used numerical platforms in Python to build Deep Learning algorithms but they can be quite complex and difficult to use. In comparison, Keras provides an easy and convenient way to build deep learning models. It\u2019s creator\u00a0Fran\u00e7ois Chollet\u00a0developed it to enable people to build Neural Networks as fast and easy as possible. He laid his focus on extensibility, modularity, minimalism and the support of python. Keras can be used with GPUs and CPUs and it supports both Python 2 and 3. Google Keras made a big contribution to the commoditization of deep learning and artificial intelligence since it has commoditized powerful, modern Deep Learning\u00a0algorithms that previously were not only inaccessible but also unusable as well.<\/p>\n<h2>What\u00a0is Sentiment Analysis?<\/h2>\n<p>With Sentiment Analysis, we want to determine the attitude\u00a0(e.g the sentiment) of for example a speaker or writer\u00a0with respect to a document, interaction, or event. Therefore it is a natural language processing problem where text needs to be understood, to predict the underlying intent.\u00a0 The sentiment is mostly categorized into positive, negative and neutral categories. With the use of Sentiment Analysis, we want to predict for example a customers opinion and attitude about a product\u00a0based on a review he wrote about it. Because of that, Sentiment Analysis is widely applied to things like reviews, surveys, documents and much more.<\/p>\n<h2>The imdb Dataset<\/h2>\n<p>The imdb sentiment classification dataset consists of 50,000 movie reviews from imdb users that are labeled as either positive (1) or negative (0).\u00a0The reviews are preprocessed and each one is encoded as a sequence of word indexes in the form of integers. The words within the reviews are indexed by their overall frequency within the dataset. For example, the integer \u201c2\u201d encodes the second most frequent word in the data. The 50,000 reviews are split into 25,000 for training and 25,000 for testing. The dataset was created by researchers\u00a0of the Stanford University and published in a paper in 2011, where they achieved 88.89% accuracy. It was also used within the\u00a0\u201cBag of Words Meets Bags of Popcorn\u201d Kaggle\u00a0competition in 2011.<\/p>\n<h2>Import Dependencies and get the Data<\/h2>\n<p>We start by importing the required dependencies to preprocess our data and to build our model.<\/p>\n<p>&nbsp;<\/p>\n<div>We continue with downloading the imdb dataset, which is fortunately already built into Keras. Since we don\u2019t\u00a0want to have a 50\/50 train test split, we will immediately merge the data into data and targets after downloading, so that we can do an 80\/20 split later on.<\/div>\n<div><\/div>\n<div><\/div>\n<div><\/div>\n<h2>Exploring the Data<\/h2>\n<p>Now we can start exploring the dataset:<\/p>\n<div><\/div>\n<div><\/div>\n<div>You can see in the output above that the dataset is labeled into\u00a0two categories, either 0 or 1, which represents the sentiment of the review. The whole dataset contains 9998 unique words and the average review length is 234 words, with a standard deviation of 173 words.<\/div>\n<p>Now we will look at a single training example:<\/p>\n<p>&nbsp;<\/p>\n<div><\/div>\n<p>Above you see the first review of the dataset which is labeled as positive (1). The code below\u00a0retrieves the dictionary mapping word indices back into the original\u00a0words so that we can read them. It replaces every unknown word with a \u201c#\u201d. It does this by using the\u00a0<a href=\"http:\/\/get_word_index\/\" target=\"_blank\" rel=\"noopener noreferrer\">get_word_index()<\/a>\u00a0function.<\/p>\n<div><\/div>\n<h2>Data Preparation<\/h2>\n<p>Now it is time to prepare our data. We will vectorize every review and fill it with zeros so that it contains exactly 10,000 numbers. That means we fill every review that is shorter than 10,000 with zeros. We do this because the biggest review is nearly that long and every input for our neural network needs to have the same size. We also transform the targets into floats.<\/p>\n<p>&nbsp;<\/p>\n<div>Now we split our data into a training and a testing set. The training set will contain 40,000 reviews and the testing set 10,000.<\/div>\n<div><\/div>\n<div><\/div>\n<div><\/div>\n<p>&nbsp;<\/p>\n<h2>Building and Training the Model<\/h2>\n<p>We can now build our simple Neural Network. We start by defining the type of model we want to build. There are two types of models available in Keras:\u00a0<a href=\"https:\/\/keras.io\/models\/sequential\" rel=\"noopener\">the Sequential model<\/a>\u00a0and\u00a0<a href=\"https:\/\/keras.io\/models\/model\" rel=\"noopener\">the Model class used with functional API<\/a>.<\/p>\n<p>Then we simply add the input-, hidden- and output-layers. Between them, we are using dropout to prevent overfitting. Note that you should always use a dropout rate between 20% and 50%. At every layer, we use \u201cDense\u201d which means that the units are fully connected. Within the hidden-layers, we use the relu\u00a0function, because this is always a good start and yields a satisfactory result most of the time. Feel free to experiment with other activation functions. And at the output-layer, we use the sigmoid function, which maps the values between 0 and 1. Note that we set the input-shape to 10,000 at the input-layer, because our reviews are 10,000 integers long. The input-layer takes 10,000 as input and outputs it with a shape of 50.<\/p>\n<p>Lastly, we let Keras print a summary of the model we have just built.<\/p>\n<div><\/div>\n<p>Now we need to compile our model, which is nothing but configuring the model for training.\u00a0We use the \u201cadam\u201d optimizer.\u00a0The optimizer is the algorithm that changes the weights and biases during training. We also choose\u00a0binary-crossentropy\u00a0as loss (because we deal with binary classification) and accuracy as our evaluation metric.<\/p>\n<div><\/div>\n<p>We are now able to train our model. We do this with a batch_size of 500 and only for two epochs because I recognized that the model overfits if we train it longer. The\u00a0Batch size\u00a0defines the\u00a0number of samples that will be propagated through the network and an epoch is an iteration over the entire training data.\u00a0<em>In general a l<\/em>arger batch-size results in faster training, but don\u2019t always converges fast. A smaller batch-size is slower in training but it\u00a0<em>can<\/em>\u00a0converge faster. This is definitely problem dependent and you need to try out a few different values. If you start with a problem for the first time, I would you recommend to you to first use a batch-size of 32, which is the standard size.<\/p>\n<div><\/div>\n<p>It is time to evaluate our model:<\/p>\n<div><\/div>\n<p>Awesome! With this simple model, we already beat the accuracy of the 2011 paper that I mentioned in the beginning. Feel free to experiment with the hyperparameters and the number of layers.<\/p>\n<p>You can see the code for the whole model below:<\/p>\n<div><\/div>\n<h2>Summary<\/h2>\n<p>In this Post you learned what Sentiment Analysis is and why Keras is one of the most used Deep Learning libraries. On top of that you learned that Keras made a big contribution to the commoditization of deep learning and artificial intelligence. You learned how to build a simple Neural Network with six layers that can predict the sentiment of movie reviews, which achieves a 89% accuracy. You can now use this model to also do binary sentiment analysis on other sources of text but you need to change them all to a length of 10,000 or you change the input-shape of the input layer. You can also apply this model to other related machine learning problems with only a few changes.<\/p>\n<h2>Sources:<\/h2>\n<div><a href=\"https:\/\/keras.io\/datasets\/\" rel=\"nofollow noopener\">https:\/\/keras.io\/datasets\/<\/a><\/div>\n<div><a href=\"https:\/\/en.wikipedia.org\/wiki\/Sentiment_analysis\" rel=\"nofollow noopener\">https:\/\/en.wikipedia.org\/wiki\/Sentiment_analysis<\/a><\/div>\n<div><a href=\"https:\/\/machinelearningmastery.com\/introduction-python-deep-learning-library-keras\/\" rel=\"nofollow noopener\">https:\/\/machinelearningmastery.com\/introduction-python-deep-learning-library-keras\/<\/a><\/div>\n<div><a href=\"https:\/\/keras.io\/\" rel=\"nofollow noopener\">https:\/\/keras.io\/<\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Keras is one of the most popular Deep Learning libraries out there at the moment and made a big contribution to the&nbsp;commoditization of artificial intelligence. It is simple to use and it enables you to build powerful Neural Networks in just a few lines of code. In this post, you will discover how you can build a Neural Network with Keras that predicts the sentiment of user reviews by categorizing them into two categories: positive or negative.&nbsp;<\/p>\n","protected":false},"author":413,"featured_media":23777,"comment_status":"open","ping_status":"open","sticky":false,"template":"single-post-2.php","format":"standard","meta":{"content-type":"","footnotes":""},"categories":[183],"tags":[97],"ppma_author":[2327],"class_list":["post-1480","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ai-ml","tag-artificial-intelligence"],"authors":[{"term_id":2327,"user_id":413,"is_guest":0,"slug":"niklas-donges","display_name":"Niklas Donges","avatar_url":"https:\/\/secure.gravatar.com\/avatar\/?s=96&d=mm&r=g","user_url":"","last_name":"Donges","first_name":"Niklas","job_title":"","description":"<a href=\"https:\/\/www.linkedin.com\/in\/niklas-donges\/\">Niklas Donges<\/a>&nbsp;is Machine Learning Engineer at SAP. He is a Technical Blogger for the &#039;Towards Data Science&#039; publication"}],"_links":{"self":[{"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/posts\/1480","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/users\/413"}],"replies":[{"embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/comments?post=1480"}],"version-history":[{"count":4,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/posts\/1480\/revisions"}],"predecessor-version":[{"id":28997,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/posts\/1480\/revisions\/28997"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/media\/23777"}],"wp:attachment":[{"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/media?parent=1480"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/categories?post=1480"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/tags?post=1480"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/ppma_author?post=1480"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}