

{"id":98002,"date":"2021-07-12T09:00:03","date_gmt":"2021-07-12T03:30:03","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=98002"},"modified":"2026-06-01T12:28:07","modified_gmt":"2026-06-01T06:58:07","slug":"python-sentiment-analysis","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/","title":{"rendered":"Sentiment Analysis in Python using Machine Learning"},"content":{"rendered":"<p>Sentiment analysis or opinion mining is a simple task of understanding the emotions of the writer of a particular text. What was the intent of the writer when writing a certain thing?<\/p>\n<p>We use various natural language processing (NLP) and text analysis tools to figure out what could be subjective information. We need to identify, extract and quantify such details from the text for easier classification and working with the data.<\/p>\n<p><strong>But why do we need sentiment analysis?<\/strong><\/p>\n<p>Sentiment analysis serves as a fundamental aspect of dealing with customers on online portals and websites for the companies. They do this all the time to classify a comment as a query, complaint, suggestion, opinion, or just love for a product. This way they can easily sort through the comments or questions and prioritize what they need to handle first and even order them in a way that looks better. Companies sometimes even try to delete content that has a negative sentiment attached to it.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-98174\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment.jpg\" alt=\"sentiment\" width=\"480\" height=\"264\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment.jpg 480w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment-320x176.jpg 320w\" sizes=\"auto, (max-width: 480px) 100vw, 480px\" \/><\/a><\/p>\n<p>It is an easy way to understand and analyze public reception and perception of different ideas and concepts, or a newly launched product, maybe an event or a government policy.<\/p>\n<p>Emotion understanding and sentiment analysis play a huge role in collaborative filtering based recommendation systems. Grouping together people who have similar reactions to a certain product and showing them related products. Like recommending movies to people by grouping them with others that have similar perceptions for a certain show or movie.<\/p>\n<p>Lastly, they are also used for spam filtering and removing unwanted content.<\/p>\n<h2>How does sentiment analysis work?<\/h2>\n<p><strong>NLP<\/strong> or natural language processing is the basic concept on which sentiment analysis is built upon. Natural language processing is a superclass of sentiment analysis that deals with understanding all kinds of things from a piece of text.<\/p>\n<p>NLP is the branch of AI dealing with texts, giving machines the ability to understand and derive from the text. For tasks such as virtual assistant, query solving, creating and maintaining human-like conversations, summarizing texts, spam detection, sentiment analysis, etc. it includes everything from counting the number of words to a machine writing a story, indistinguishable from human texts.<\/p>\n<p>Sentiment analysis can be classified into various categories based on various criteria. Depending upon the scope it can be classified into document-level sentiment analysis, sentence level sentiment analysis, and sub sentence level or phrase level sentiment analysis.<\/p>\n<p>Also, a very common classification is based on what needs to be done with the data or the reason for sentiment analysis. Examples of which are<\/p>\n<ul>\n<li>Simple classification of text into positive, negative or neutral. It may also advance into fine grained answers like very positive or moderately positive.<\/li>\n<li>Aspect-based sentiment analysis- where we figure out the sentiment along with a specific aspect it is related to. Like identifying sentiments regarding various aspects or parts of a car in user reviews, identifying what feature or aspect was appreciated or disliked.<\/li>\n<li>The sentiment along with an action associated with it. Like mails written to customer support. Understanding if it is a query or complaint or suggestion etc<\/li>\n<\/ul>\n<p>Based on what needs to be done and what kind of data we need to work with there are two major methods of tackling this problem.<\/p>\n<ul>\n<li><strong>Matching rules based sentiment analysis:<\/strong> There is a predefined list of words for each type of sentiment needed and then the text or document is matched with the lists. The algorithm then determines which type of words or which sentiment is more prevalent in it.<br \/>\nThis type of rule based sentiment analysis is easy to implement, but lacks flexibility and does not account for context.<\/li>\n<li><strong>Automatic sentiment analysis:<\/strong> They are mostly based on supervised machine learning algorithms and are actually very useful in understanding complicated texts. Algorithms in this category include support vector machine, linear regression, rnn, and its types. This is what we are gonna explore and learn more about.<\/li>\n<\/ul>\n<p><strong>In this machine learning project, we will use recurrent neural network for sentiment analysis in python.<\/strong><\/p>\n<h3>Understanding the sentiment analysis system<\/h3>\n<p>Recurrent neural networks or RNNs are the go-to method for sequential data. Recurrent neural networks have a memory of their own and remember the input that was given to each node. In a normal feed forward neural network data or information given in the form of input moves forward and never moves backward in any nodes, from the input layer to the hidden layer and out from the output layer. Because these kinds of networks have no memory they do not remember the last input or predict the next input.<\/p>\n<p>When giving out an output an rnn considers what input it is given and also the input that it had received previously, because the information moves in a cycle in an rnn.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/rnn-vs-fnn.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-98175\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/rnn-vs-fnn.jpg\" alt=\"rnn vs fnn\" width=\"864\" height=\"502\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/rnn-vs-fnn.jpg 864w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/rnn-vs-fnn-768x446.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/rnn-vs-fnn-720x418.jpg 720w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/rnn-vs-fnn-520x302.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/rnn-vs-fnn-320x186.jpg 320w\" sizes=\"auto, (max-width: 864px) 100vw, 864px\" \/><\/a><\/p>\n<p>What a recurrent neural network does is creates a copy of the output and loops it back through the network. For example when a sentence is passed through a feedforward network and it takes it word by word, till it reaches the last word. It has no memory of what was fed to it before that. But rnns know the previous inputs as well and can thus also predict what can come next. They are widely used in sequential data.<\/p>\n<p>Recurrent neural networks are not new, were first introduced in the 1980s, but have become a lot popular with the growth of deep learning and its use in sequential data. Still, rnn have their own set of problems, one of the major ones being the vanishing gradient problem. The answer to that being the lstm model.<\/p>\n<p>LSTM or long short term memory models are used to solve these problems. Lstms are a special kind of rnn model that has the capability of learning long term dependencies. They are made to remember long term data. What makes lstm models special is the addition of a memory cell, which is an extra recurrent state and each cell has multiple gates that control the flow of information in and out of the memory cell.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/lstm-diagram.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-98176\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/lstm-diagram.jpg\" alt=\"lstm for sentiment analysis\" width=\"960\" height=\"661\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/lstm-diagram.jpg 960w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/lstm-diagram-768x529.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/lstm-diagram-720x496.jpg 720w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/lstm-diagram-520x358.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/lstm-diagram-320x220.jpg 320w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p>There are three types of gates in an lstm: an input gate, an output gate and a forget gate. The input gate is used to update the cell status, the forget state decides which information is to be stored and which needs to be discarded. The output gate determines the values for the next hidden gates.<\/p>\n<h2>Building Sentiment Analysis System<\/h2>\n<p>Now that we have a basic understanding of what we need to build we will try implementing it in an easy way.<\/p>\n<p>We will be building a simple sentiment analysis classifier on top of movie reviews, that will classify if the user review of the movie was positive, negative or neutral. For this sentiment analysis python project, we are going to use the imdb movie review dataset.<\/p>\n<h3>What is Sentiment Analysis<\/h3>\n<p>Sentiment analysis is the process of finding users&#8217; opinions towards a brand, company, or product. It defines the subject behind the social data, after launching a product we can find whether people are liking the product or not. There are many use-cases for sentiment analysis apart from opinion mining.<\/p>\n<h3>Download Sentiment Analysis Python Code<\/h3>\n<p>Please download the source code sentiment analysis in Python: <a href=\"https:\/\/drive.google.com\/file\/d\/1rGGkf_ogbsJdGUUGD7bHcvdNfmDRGqT9\/view?usp=drive_link\"><strong>Sentiment Analysis Python ML Code<\/strong><\/a><\/p>\n<h3>Sentiment Analysis Dataset<\/h3>\n<p>The dataset which we will use in sentiment analysis is the International Movie Database(IMDb) reviews for 50,000 reviews of movies from all over the world, its a binary classification dataset categorizing each review in a positive or negative. It has 25000 samples for training and 25000 for testing.<\/p>\n<p>You don&#8217;t need to download it separately for this project but you can have a look at it on its <a href=\"http:\/\/ai.stanford.edu\/~amaas\/data\/sentiment\/\">official website<\/a>. Because it is a text dataset it is very lightweight around 80MB.<\/p>\n<p>We are going to code all this up in a jupyter notebook on google colab to make use of the free gpu. If you follow along on your own system everything will be pretty much the same except for mounting the google drive for use as a persistent storage option.<\/p>\n<ul>\n<li>So we begin by mounting our google drive and navigating to the folder where we wanna work.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\r\nfrom google.colab import drive\r\ndrive.mount('\/content\/drive')\r\n \r\nos.chdir('\/content\/drive\/My Drive\/DataFlair\/Sentiment')\r\n!ls<\/pre>\n<h3><strong>Preparation of data<\/strong><\/h3>\n<p>We are going to use pytorch for this project and luckily it comes preinstalled with some functionalities for helping us speeding up our work<\/p>\n<p>The torch.text library is a great tool for nlp projects. It has a loader for some common nlp datasets like the one we are going to use today, also complete pipeline for abstraction of vectorization of data, data loaders and iteration of data.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import random\r\nimport torch\r\nfrom torchtext.legacy import data\r\nfrom torchtext.legacy import datasets\r\n \r\nseed = 42\r\n \r\ntorch.manual_seed(seed)\r\ntorch.backends.cudnn.deterministic = True\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n \r\ntxt = data.Field(tokenize = 'spacy',\r\n                  tokenizer_language = 'en_core_web_sm',\r\n                  include_lengths = True)\r\n \r\nlabels = data.LabelField(dtype = torch.float)\r\n<\/pre>\n<p>We are going to use the field method of the data class to decide how data needs to be preprocessed. The parameters we pass in there will determine the preprocessing, we are just going to tweak some parameters and leave the rest to default.<\/p>\n<p>The first parameter, our tokenizer(that determines how the sentences are going to be broken down or tokenized in nlp standard) is spacy, which is a powerful tool for one line tokenization. We recommend using this, but the default is just tokenizing the string based on blank spaces. Also we need to tell the spacy tokenizer which language model to use for the task.<\/p>\n<p>We also set the random seed to a certain number, which could be any but we mention it just for reproducibility purposes. You could change it or even omit it without any significant effect. We also want to use cuda and also the gpu available to us so we use swt that as well.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">train_data, test_data = datasets.IMDB.splits(txt, labels)\r\ntrain_data, valid_data = train_data.split(random_state = random.seed(seed))\r\nnum_words = 25_000\r\n \r\ntxt.build_vocab(train_data, \r\n                 max_size = num_words, \r\n                 vectors = \"glove.6B.100d\", \r\n                 unk_init = torch.Tensor.normal_)\r\n \r\nlabels.build_vocab(train_data)\r\n<\/pre>\n<p>Here we have downloaded the imdb dataset for python sentiment analysis and divided it into train test and validation split. The dataset is already divided into a train and test set, we further create a validation set from it.<\/p>\n<p>We further limit the number of words the model will learn to 25000, this will choose the most used 25000 words from the dataset and use them for training. Significantly reducing the work of the model without any real loss in accuracy.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">btch_size = 64\r\n \r\ntrain_itr, valid_itr, test_itr = data.BucketIterator.splits(\r\n    (train_data, valid_data, test_data), \r\n    batch_size = btch_size,\r\n    sort_within_batch = True,\r\n    device = device)\r\n<\/pre>\n<p>We are now creating a training, testing and validation batch from the data that we have for preparing it to be fed to the model in the form of batches of 64 samples at a time. Reduce this if you get out of memory error.<\/p>\n<h3>Defining python sentiment analysis model<\/h3>\n<p>We now prepare the model and define its architecture. For our task, we are using a lstm rnn. We will be using a multi layer bidirectional rnn. That means there will be multiple rnn layers stacked on top of each other.<\/p>\n<p>Bidirectional RNNs have an advantage of having more context than a single directional network. For example, in a sentence flowing forward through a model, if a model has to guess the next word, it would do so on the basis of previous knowledge. But in a bidirectional network it will also have the knowledge of what&#8217;s next due to two networks flowing in opposite directions stacked on top of each other. The input flows in the opposite direction as well as sequence. A sentence \u201ci love DataFlair\u201d will flow in the first network as \u201ci\u201d , \u201clove\u201d , \u201cDataFlair\u201d but in the second it will flow like \u201cDataFlair\u201d , \u201clove\u201d , \u201ci\u201d. This provides better context and relation in the data to the network.<\/p>\n<p>The hidden state output from the first layer will be the input to the next layer, also each layer has its independent hidden nodes.<\/p>\n<p>We use nn.LSTM layers instead of normal nn.RNN layers<\/p>\n<p>We pass everything through an embedding layer which is just a representation of words in lower-dimensional space. Simply put to place the words such that similar words are grouped together.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import torch.nn as nn\r\n \r\nclass RNN(nn.Module):\r\n    def __init__(self, word_limit, dimension_embedding, dimension_hidden, dimension_output, num_layers, \r\n                 bidirectional, dropout, pad_idx):\r\n        \r\n        super().__init__()\r\n        \r\n        self.embedding = nn.Embedding(word_limit, dimension_embedding, padding_idx = pad_idx)\r\n        \r\n        self.rnn = nn.LSTM(dimension_embedding, \r\n                           dimension_hidden, \r\n                           num_layers=num_layers, \r\n                           bidirectional=bidirectional, \r\n                           dropout=dropout)\r\n        \r\n        self.fc = nn.Linear(dimension_hidden * 2, dimension_output)\r\n        \r\n        self.dropout = nn.Dropout(dropout)\r\n        \r\n    def forward(self, text, len_txt):\r\n        \r\n        \r\n        embedded = self.dropout(self.embedding(text))\r\n               \r\n \r\n        packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, len_txt.to('cpu'))\r\n        \r\n        packed_output, (hidden, cell) = self.rnn(packed_embedded)\r\n        \r\n        output, output_lengths = nn.utils.rnn.pad_packed_sequence(packed_output)\r\n \r\n        \r\n        hidden = self.dropout(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1))\r\n                            \r\n        return self.fc(hidden)\r\n<\/pre>\n<p>We define the parameters for python sentiment analysis model and pass it to an instance of the model class we just defined. The number of input parameters, hidden layer, and the output dimension along with throughput rate and bidirectionality boolean is defined. We also pass the pad token index from the vocabulary that we created earlier.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">dimension_input = len(txt.vocab)\r\ndimension_embedding = 100\r\ndimension_hddn = 256\r\ndimension_out = 1\r\nlayers = 2\r\nbidirectional = True\r\ndropout = 0.5\r\nidx_pad = txt.vocab.stoi[txt.pad_token]\r\n \r\nmodel = RNN(dimension_input, \r\n            dimension_embedding, \r\n            dimension_hddn, \r\n            dimension_out, \r\n            layers, \r\n            bidirectional, \r\n            dropout, \r\n            idx_pad)\r\n<\/pre>\n<p>Now we print some details about our model. Getting the number of trainable parameters that are present there in the model.<\/p>\n<p>We then get the pre-trained embedding weights and copy them to our model so that it does not need to learn the embeddings, and can directly focus on the job at hand that is learning the sentiments related to those embeddings.<\/p>\n<p>Pretrained embedding weights are placed in place of the initial ones.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def count_parameters(model):\r\n    return sum(p.numel() for p in model.parameters() if p.requires_grad)\r\n \r\nprint(f'The model has {count_parameters(model):,} trainable parameters')\r\npretrained_embeddings = txt.vocab.vectors\r\n \r\nprint(pretrained_embeddings.shape)\r\nunique_id = txt.vocab.stoi[txt.unk_token]\r\n \r\nmodel.embedding.weight.data[unique_id] = torch.zeros(dimension_embedding)\r\nmodel.embedding.weight.data[idx_pad] = torch.zeros(dimension_embedding)\r\n \r\nprint(model.embedding.weight.data)\r\n<\/pre>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/pre-trained-embedding-output.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-98177\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/pre-trained-embedding-output.png\" alt=\"pre trained embedding output\" width=\"1429\" height=\"751\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/pre-trained-embedding-output.png 1429w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/pre-trained-embedding-output-768x404.png 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/pre-trained-embedding-output-720x378.png 720w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/pre-trained-embedding-output-520x273.png 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/pre-trained-embedding-output-320x168.png 320w\" sizes=\"auto, (max-width: 1429px) 100vw, 1429px\" \/><\/a><\/p>\n<p>Now we define some parameters regarding the model, that is the optimizer we are going to use and the criterion of loss we need. We chose adam optimizer for fast convergence of the model along with logistic loss function. We place the model and the criterion on the gpu.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import torch.optim as optim\r\n \r\noptimizer = optim.Adam(model.parameters())\r\ncriterion = nn.BCEWithLogitsLoss()\r\n \r\nmodel = model.to(device)\r\ncriterion = criterion.to(device)\r\n<\/pre>\n<h3>Training of the model<\/h3>\n<p>We now begin the necessary functions for training and evaluation of sentiment analysis model.<\/p>\n<p>The first one being the binary accuracy function, which we\u2019ll use for getting the accuracy of the model each time.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def bin_acc(preds, y):\r\n   \r\n    predictions = torch.round(torch.sigmoid(preds))\r\n    correct = (predictions == y).float() \r\n    acc = correct.sum() \/ len(correct)\r\n    return acc\r\n<\/pre>\n<p>We define the function for training and evaluating the models. The process here is standard. We start by looping through the number of epochs and the number of iterations in each epoch is according to the batch size that we defined. We pass the text to the model, get the predictions from it, calculate the loss for each iteration and then backward propagate that loss.<\/p>\n<p>The only major change in the evaluating function from the training function is that we do not backward propagate the loss through the model and use torch.nograd basically signifying no gradient descent while evaluating.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def train(model, itr, optimizer, criterion):\r\n    \r\n    epoch_loss = 0\r\n    epoch_acc = 0\r\n    \r\n    model.train()\r\n    \r\n    for i in itr:\r\n        \r\n        optimizer.zero_grad()\r\n        \r\n        text, len_txt = i.text\r\n        \r\n        predictions = model(text, len_txt).squeeze(1)\r\n        \r\n        loss = criterion(predictions, i.label)\r\n        \r\n        acc = bin_acc(predictions, i.label)\r\n        \r\n        loss.backward()\r\n        \r\n        optimizer.step()\r\n        \r\n        epoch_loss += loss.item()\r\n        epoch_acc += acc.item()\r\n        \r\n    return epoch_loss \/ len(itr), epoch_acc \/ len(itr)\r\n \r\ndef evaluate(model, itr, criterion):\r\n    \r\n    epoch_loss = 0\r\n    epoch_acc = 0\r\n    \r\n    model.eval()\r\n    \r\n    with torch.no_grad():\r\n    \r\n        for i in itr:\r\n \r\n            text, len_txt = i.text\r\n            \r\n            predictions = model(text, len_txt).squeeze(1)\r\n            \r\n            loss = criterion(predictions, i.label)\r\n            \r\n            acc = bin_acc(predictions, i.label)\r\n \r\n            epoch_loss += loss.item()\r\n            epoch_acc += acc.item()\r\n        \r\n    return epoch_loss \/ len(itr), epoch_acc \/ len(itr)\r\n\r\n<\/pre>\n<p>We build a helper function epoch_time for calculating the time each epoch takes to complete its run and print it. We set the number of epochs to 5 and then begin our training. Adding the training and validation loss at each stage, if we need to understand or plot the training curve at a later point. We save the python sentiment analysis model that has the best validation loss.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import time\r\n \r\ndef epoch_time(start_time, end_time):\r\n    used_time = end_time - start_time\r\n    used_mins = int(used_time \/ 60)\r\n    used_secs = int(used_time - (used_mins * 60))\r\n    return used_mins, used_secs\r\nnum_epochs = 5\r\n \r\nbest_valid_loss = float('inf')\r\n \r\nfor epoch in range(num_epochs):\r\n \r\n    start_time = time.time()\r\n    \r\n    train_loss, train_acc = train(model, train_itr, optimizer, criterion)\r\n    valid_loss, valid_acc = evaluate(model, valid_itr, criterion)\r\n    \r\n    end_time = time.time()\r\n \r\n    epoch_mins, epoch_secs = epoch_time(start_time, end_time)\r\n    \r\n    if valid_loss &lt; best_valid_loss:\r\n        best_valid_loss = valid_loss\r\n        torch.save(model.state_dict(), 'tut2-model.pt')\r\n    \r\n    print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')\r\n    print(f'\\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%')\r\n    print(f'\\t Val. Loss: {valid_loss:.3f} |  Val. Acc: {valid_acc*100:.2f}%')\r\n\r\n\r\n100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 398630\/400000 [00:30&lt;00:00, 25442.01it\/s]Epoch: 01 | Epoch Time: 0m 37s\r\n  Train Loss: 0.658 | Train Acc: 60.15%\r\n   Val. Loss: 0.675 |  Val. Acc: 60.89%\r\nEpoch: 02 | Epoch Time: 0m 38s\r\n  Train Loss: 0.653 | Train Acc: 60.98%\r\n   Val. Loss: 0.606 |  Val. Acc: 68.85%\r\nEpoch: 03 | Epoch Time: 0m 40s\r\n  Train Loss: 0.490 | Train Acc: 77.06%\r\n   Val. Loss: 0.450 |  Val. Acc: 80.64%\r\nEpoch: 04 | Epoch Time: 0m 40s\r\n  Train Loss: 0.390 | Train Acc: 83.21%\r\n   Val. Loss: 0.329 |  Val. Acc: 86.56%\r\nEpoch: 05 | Epoch Time: 0m 40s\r\n  Train Loss: 0.321 | Train Acc: 86.95%\r\n   Val. Loss: 0.432 |  Val. Acc: 81.71%\r\n<\/pre>\n<h3>Testing sentiment analysis model<\/h3>\n<p>We load the saved checkpoint of the model and test it on the test set that we created earlier. During the dry run of python sentiment analysis model, we achieved a decent accuracy score of 85.83%.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">model.load_state_dict(torch.load('tut2-model.pt'))\r\n \r\ntest_loss, test_acc = evaluate(model, test_itr, criterion)\r\n \r\nprint(f'Test Loss: {test_loss:.3f} | Test Acc: {test_acc*100:.2f}%')\r\n<\/pre>\n<p>We can also check the model on our data. This is trained to classify the movie reviews into positive, negative, and neutral, therefore we will pass to it relatable data for checking. So for that we will import and load spacy for tokenizing the data we need to give to the model. In the beginning, while defining the preprocessing we used spacy built-in torch.text, but here we are not using batches, and the preprocessing that we need to do can be handled by the spacy library. We define a predict sentiment function for this. After the preprocessing, we convert it into tensors and ready to be passed to the model<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import spacy\r\nnlp = spacy.load('en_core_web_sm')\r\n \r\ndef pred(model, sentence):\r\n    model.eval()\r\n    tokenized = [tok.text for tok in nlp.tokenizer(sentence)]\r\n    indexed = [txt.vocab.stoi[t] for t in tokenized]\r\n    length = [len(indexed)]\r\n    tensor = torch.LongTensor(indexed).to(device)\r\n    tensor = tensor.unsqueeze(1)\r\n    length_tensor = torch.LongTensor(length)\r\n    prediction = torch.sigmoid(model(tensor, length_tensor))\r\n    return prediction.item()\r\n<\/pre>\n<p>We define another helper function that will print the sentiment of the comment based on the score that the model provides.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">sent=[\"positive\",\"neutral\",\"negative\"]\r\ndef print_sent(x):\r\n  if (x&lt;0.3): print(sent[0])\r\n  elif (x&gt;0.3 and x&lt;0.7): print(sent[1])\r\n  else: print(sent[2])<\/pre>\n<p>Now we just pass any data and test what does the model think about it<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">print_sent(pred(model, \"This film was great\"))\r\npositive\r\n<\/pre>\n<h3>Python Sentiment Analysis Output<\/h3>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/python-sentiment-analysis-output.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-98178\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/python-sentiment-analysis-output.png\" alt=\"python sentiment analysis output\" width=\"1605\" height=\"660\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/python-sentiment-analysis-output.png 1605w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/python-sentiment-analysis-output-768x316.png 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/python-sentiment-analysis-output-1536x632.png 1536w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/python-sentiment-analysis-output-720x296.png 720w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/python-sentiment-analysis-output-520x214.png 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/python-sentiment-analysis-output-320x132.png 320w\" sizes=\"auto, (max-width: 1605px) 100vw, 1605px\" \/><\/a><\/p>\n<h3>Summary<\/h3>\n<p>Sentiment analysis is about finding if a sentence is positive, negative, or neutral. It is often used in social media, reviews, or customer feedback. In this project, we use Python and machine learning to build a model that reads a sentence and tells the mood behind it. For example, the sentence \u201cI love this product!\u201d is positive, while \u201cI hate this service\u201d is negative.<\/p>\n<p>We have successfully developed python sentiment analysis model based on lstm techniques that is pretty robust and highly accurate. As discussed earlier, sentiment analysis has many use-cases based on requirements we can use it.\u00a0We can similarly train it on any other kind of data just by changing the dataset according to our needs. We can use this sentiment analysis model in all different ways possible.<\/p>\n<p>This project is useful for businesses and apps that handle customer feedback. It teaches Natural Language Processing (NLP), text cleaning, feature extraction, and classification. You can also build a live app that reads tweets or reviews and shows emotions in real time. It\u2019s a powerful and simple project for beginners.<span hidden class=\"__iawmlf-post-loop-links\" data-iawmlf-links=\"[{&quot;id&quot;:2538,&quot;href&quot;:&quot;https:\\\/\\\/drive.google.com\\\/file\\\/d\\\/1rGGkf_ogbsJdGUUGD7bHcvdNfmDRGqT9\\\/view?usp=drive_link&quot;,&quot;archived_href&quot;:&quot;http:\\\/\\\/web-wp.archive.org\\\/web\\\/20260601065826\\\/https:\\\/\\\/drive.google.com\\\/file\\\/d\\\/1rGGkf_ogbsJdGUUGD7bHcvdNfmDRGqT9\\\/view?usp=drive_link&quot;,&quot;redirect_href&quot;:&quot;&quot;,&quot;checks&quot;:[{&quot;date&quot;:&quot;2026-06-02 06:51:35&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-06 05:34:03&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-10 10:54:01&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-13 14:43:15&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-17 09:33:02&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-20 13:27:51&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-25 14:54:00&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-29 10:45:39&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-03 03:55:27&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-08 07:57:18&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-11 09:43:03&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-14 11:05:36&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-18 18:47:42&quot;,&quot;http_code&quot;:200}],&quot;broken&quot;:false,&quot;last_checked&quot;:{&quot;date&quot;:&quot;2026-07-18 18:47:42&quot;,&quot;http_code&quot;:200},&quot;process&quot;:&quot;done&quot;},{&quot;id&quot;:348,&quot;href&quot;:&quot;http:\\\/\\\/ai.stanford.edu\\\/~amaas\\\/data\\\/sentiment&quot;,&quot;archived_href&quot;:&quot;http:\\\/\\\/web-wp.archive.org\\\/web\\\/20250820232753\\\/https:\\\/\\\/ai.stanford.edu\\\/~amaas\\\/data\\\/sentiment\\\/&quot;,&quot;redirect_href&quot;:&quot;&quot;,&quot;checks&quot;:[{&quot;date&quot;:&quot;2025-12-08 07:49:10&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2025-12-11 08:09:29&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2025-12-14 08:52:46&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2025-12-17 08:54:43&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2025-12-20 08:55:42&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2025-12-23 09:15:48&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2025-12-26 09:23:36&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2025-12-29 09:27:42&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-01 09:34:21&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-04 09:54:56&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-07 09:58:48&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-10 10:13:26&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-13 11:37:14&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-16 11:47:49&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-19 11:55:04&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-22 12:01:33&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-25 12:13:50&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-28 14:07:58&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-31 14:37:07&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-03 14:45:25&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-06 15:06:58&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-09 15:46:51&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-12 16:24:53&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-15 16:47:27&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-18 16:47:56&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-21 17:08:14&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-24 17:52:16&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-02-27 18:30:16&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-03 04:54:08&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-06 05:35:39&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-09 06:00:18&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-12 06:13:53&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-15 10:29:59&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-18 11:49:31&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-21 13:03:44&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-24 13:26:13&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-27 13:59:28&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-03-30 15:49:26&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-02 16:07:05&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-05 18:10:10&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-08 21:01:33&quot;,&quot;http_code&quot;:503},{&quot;date&quot;:&quot;2026-04-12 02:12:07&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-15 06:10:15&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-18 06:54:00&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-21 06:56:30&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-24 07:04:29&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-27 09:11:52&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-30 09:36:21&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-03 10:13:41&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-06 10:35:51&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-09 12:13:11&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-12 13:39:49&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-15 13:50:43&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-18 14:37:18&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-22 04:29:06&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-25 11:19:34&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-28 12:19:20&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-31 12:52:52&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-03 14:12:32&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-06 14:16:14&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-09 14:54:59&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-12 15:17:26&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-15 15:20:35&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-18 16:18:55&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-21 16:56:43&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-24 16:59:32&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-28 06:29:57&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-07-01 06:31:00&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-07-04 06:45:20&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-07-07 06:49:27&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-07-10 08:49:54&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-07-13 08:54:39&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-07-16 09:21:04&quot;,&quot;http_code&quot;:206}],&quot;broken&quot;:false,&quot;last_checked&quot;:{&quot;date&quot;:&quot;2026-07-16 09:21:04&quot;,&quot;http_code&quot;:206},&quot;process&quot;:&quot;done&quot;}]\"><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sentiment analysis or opinion mining is a simple task of understanding the emotions of the writer of a particular text. What was the intent of the writer when writing a certain thing? We use&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":98173,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[36],"tags":[20697,20542,24628,24630],"class_list":["post-98002","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-machine-learning","tag-machine-learning-project","tag-machine-learning-sentiment-analysis","tag-python-sentiment-analysis","tag-sentiment-analysis"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Sentiment Analysis in Python using Machine Learning - DataFlair<\/title>\n<meta name=\"description\" content=\"Sentiment Analysis in Python using LSTM to classify whether users are saying positive, negative or neutral about the company or a brand\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Sentiment Analysis in Python using Machine Learning - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Sentiment Analysis in Python using LSTM to classify whether users are saying positive, negative or neutral about the company or a brand\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-12T03:30:03+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-06-01T06:58:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment-analysis-in-python-using-ml.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"14 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Sentiment Analysis in Python using Machine Learning - DataFlair","description":"Sentiment Analysis in Python using LSTM to classify whether users are saying positive, negative or neutral about the company or a brand","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/","og_locale":"en_US","og_type":"article","og_title":"Sentiment Analysis in Python using Machine Learning - DataFlair","og_description":"Sentiment Analysis in Python using LSTM to classify whether users are saying positive, negative or neutral about the company or a brand","og_url":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2021-07-12T03:30:03+00:00","article_modified_time":"2026-06-01T06:58:07+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment-analysis-in-python-using-ml.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"14 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Sentiment Analysis in Python using Machine Learning","datePublished":"2021-07-12T03:30:03+00:00","dateModified":"2026-06-01T06:58:07+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/"},"wordCount":2705,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment-analysis-in-python-using-ml.jpg","keywords":["machine learning project","machine learning Sentiment analysis","python sentiment analysis","sentiment analysis"],"articleSection":["Machine Learning Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/","url":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/","name":"Sentiment Analysis in Python using Machine Learning - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment-analysis-in-python-using-ml.jpg","datePublished":"2021-07-12T03:30:03+00:00","dateModified":"2026-06-01T06:58:07+00:00","description":"Sentiment Analysis in Python using LSTM to classify whether users are saying positive, negative or neutral about the company or a brand","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment-analysis-in-python-using-ml.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/sentiment-analysis-in-python-using-ml.jpg","width":1200,"height":628,"caption":"sentiment analysis in python using ml"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-sentiment-analysis\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Machine Learning Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/machine-learning\/"},{"@type":"ListItem","position":3,"name":"Sentiment Analysis in Python using Machine Learning"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/98002","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=98002"}],"version-history":[{"count":8,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/98002\/revisions"}],"predecessor-version":[{"id":148612,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/98002\/revisions\/148612"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/98173"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=98002"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=98002"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=98002"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}