<jupyter_start><jupyter_text>A sentiment analyser will predict whether an input sentence has positive or negative sentiment.Sentiment analyser is a classification task in machine learning. The classifier need to classify a sentence into positive sentiment (eg: I love coffee) or negative sentiment (eg: I hate golddiggers)Lets start coding...PREREQUESTIES:PYTHON BASICS<jupyter_code>from sklearn.naive_bayes import GaussianNB
from sklearn.feature_extraction.text import CountVectorizer<jupyter_output><empty_output><jupyter_text>Imported a classifier from sklearn package in the first line and CountVectorizer in the second line. It all make sense in a minute.<jupyter_code>train = [
     ('I love this sandwich.', 'pos'), ('this is an amazing place!', 'pos'),
     ('I feel very good about these beers.', 'pos'),
     ('this is my best work.', 'pos'),
     ("what an awesome view", 'pos'),
     ('I do not like this restaurant', 'neg'),
     ('I am tired of this stuff.', 'neg'),
     ("I can't deal with this", 'neg'),
     ('he is my sworn enemy!', 'neg'),
     ('my boss is horrible.', 'neg'),
     ("i hate you.",'neg'),
     ("i love mangoes.",'pos'),
     ("i am sad.", 'neg')
]
test = [
     ('the cake was good.', 'pos'),
     ('I do not enjoy my job', 'neg'),
     ("I am not feeling good today.", 'neg'),
     ("I feel amazing!", 'pos'),
     ('Ebey is an amazing person.', 'pos'),
     ("I can't believe I'm doing this.", 'neg')

]<jupyter_output><empty_output><jupyter_text>We need dataset for building such a classifier.Here we initialized a training dataset and testing dataset with input sentences and its corresponding sentiments ('pos' or 'neg') in tuples. We will use the train dataset for training the model and check whether the classifier is correct using the test dataset.Test dataset contain sentences the classfier didnt saw while training.So lets take each dataset and seperate into features and labels.<jupyter_code>train_features = []
train_labels = []
for data in train:
    train_features.append(data[0])
    train_labels.append(data[1])<jupyter_output><empty_output><jupyter_text>We seperately stored the features and labels for training into two list, train_features and train_labels<jupyter_code>print("training features: ",train_features)

print("training labels: ",train_labels)<jupyter_output>training labels:  ['pos', 'pos', 'pos', 'pos', 'pos', 'neg', 'neg', 'neg', 'neg', 'neg', 'neg', 'pos', 'neg']<jupyter_text>We do the same thing to test dataset !<jupyter_code>test_features = []
test_labels = []
for data in test:
    test_features.append(data[0])
    test_labels.append(data[1])
print("testing features: ",test_features)
print("testing labels: ",test_labels)<jupyter_output>testing labels:  ['pos', 'neg', 'neg', 'pos', 'pos', 'neg']<jupyter_text>The dataset we have is in textual form. Machine leaarning algorithm will take only numerical data. So we convert this textual data into vectors. For that we will use CountVectorizer which will represent a sentence in vector based on frequency of words occured in the dataset.Lets see a small example first.Consider we have sentences like this<jupyter_code>["balu love mougli", "balu love bageera" ]<jupyter_output><empty_output><jupyter_text>Using the CountVectorizer() we can represent these sentences into vectors.First initilaizing the vectorizer.<jupyter_code>count_vect = CountVectorizer()<jupyter_output><empty_output><jupyter_text>The vectorizer will initialize a vocabulary and create vectors based on the frequency of words occur in the dataset. For initializing the vocabulary and vectorize using that vocabulary we use the function fit_transform()<jupyter_code>x = count_vect.fit_transform(["balu love mougli","balu love bageera"])<jupyter_output><empty_output><jupyter_text>Lets see the output.<jupyter_code>print(x.toarray())<jupyter_output>[[0 1 1 1]
 [1 1 1 0]]<jupyter_text>What the vectorizer did is it created a vocabulary with number of elements equal to the number of individual words in the above dataset in alphabetic order. That is 'bageera', 'balu', 'love' and 'mougli'.So as you can see the vector for a sentence contain four elements, each represents one word in the vocabulary. A sentence can be represented with the number of times the word occured in the sentence.For example,"balu love mougli" --> [0 1 1 1](First word in the vocabulary, 'bageera' is not present in the sentence so first element is zero. All other words in vocabulary are present once, so the elements in their postions are made one. If some words occur twice in a sentence then corresponding element is made two and so on) Now say we have a new sentence, we have to convert it to vector based on the vocabulary we created above.<jupyter_code>["balu love pikachu"]<jupyter_output><empty_output><jupyter_text>We use transform function in CountVectorizer for transforming the new input to vector based on the vocabulary we created.<jupyter_code>y = count_vect.transform(["balu love pikachu"])<jupyter_output><empty_output><jupyter_text>See we use the same object, count_vect to which we initialized the vocabulary. So calling transform() will vectorize the new input using that vocabulary.Lets see the output !<jupyter_code>print(y.toarray())<jupyter_output>[[0 1 1 0]]<jupyter_text>Verify the output yourself. Now lets vectorize our training dataset.<jupyter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
 [0 [...]<jupyter_text>Lets convert x_train to array for feeding it to the machine learning model.<jupyter_code>x_train = x_train.toarray()<jupyter_output><empty_output><jupyter_text>So we have the features in numerical format, now we need the labels also. One conventional practice is to label using 0,1,2... N for N labels.Here we have 2 labels, so lets represent 'pos' as 0 and 'neg' ad 1<jupyter_code>y_train = []
for i in train_labels:
    if i == 'pos':
        y_train.append(0)
    elif i == 'neg':
        y_train.append(1)
print(y_train)<jupyter_output>[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1]<jupyter_text>Done.Lets build the classifier now !<jupyter_code>classifier = GaussianNB()<jupyter_output><empty_output><jupyter_text>In sklearn a classifier has two functions, fit and predict.Function fit() will train the model using the dataset and after training we can use predict() for predicting the label giving a new input feature.<jupyter_code>classifier.fit(x_train,y_train)<jupyter_output><empty_output><jupyter_text>OK... Lets test the classifier using test dataset.<jupyter_code>x_test = count_vect.transform(test_features)<jupyter_output><empty_output><jupyter_text>The test features are transformed to vectors using the training dataset vocabulary.<jupyter_code>x_test = x_test.toarray()
k = classifier.predict(x_test)<jupyter_output><empty_output><jupyter_text>Now we predict the sentiments of test dataset ! If the predicted label is 0 that means corresponding sentence has positive sentiment, if 1 then its negative.<jupyter_code>for i,data in enumerate(test_features):
    print("input: ",data)
    if k[i] == 0:
        print("sentiment: ","positive")
    elif k[i] == 1:
        print("sentiment: ","negative")<jupyter_output>input:  the cake was good.
sentiment:  positive
input:  I do not enjoy my job
sentiment:  negative
input:  I am not feeling good today.
sentiment:  negative
input:  I feel amazing!
sentiment:  positive
input:  Ebey is an amazing person.
sentiment:  positive
input:  I can't believe I'm doing this.
sentiment:  negative
{'fraction_non_alphanumeric': 0.08982951205173427, 'fraction_numerical': 0.06043503821281599, 'mean_word_length': 4.081242532855436, 'pattern_counts': {'":': 0, '<': 74, '<?xml version=': 0, '>': 75, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 72, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '617093', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3261, 'n_tokens_neox': 2732, 'n_words': 1344, 'path': 'sentiment_analyzer.ipynb', 'repo_name': 'RITct-Learninghub/ritml-Aksh77', 'size': '8505'}