<?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 Dilara Özcerit on Medium]]></title>
        <description><![CDATA[Stories by Dilara Özcerit on Medium]]></description>
        <link>https://medium.com/@dilaraozcerit?source=rss-5eeb42b9de17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hl-d01NhHTJsy--_uF63lA.png</url>
            <title>Stories by Dilara Özcerit on Medium</title>
            <link>https://medium.com/@dilaraozcerit?source=rss-5eeb42b9de17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:01:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dilaraozcerit/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[NLP Application with Machine Learning]]></title>
            <link>https://medium.com/@dilaraozcerit/nlp-application-with-ml-873b10e99f3c?source=rss-5eeb42b9de17------2</link>
            <guid isPermaLink="false">https://medium.com/p/873b10e99f3c</guid>
            <dc:creator><![CDATA[Dilara Özcerit]]></dc:creator>
            <pubDate>Wed, 22 Jun 2022 14:22:36 GMT</pubDate>
            <atom:updated>2022-06-22T14:23:54.701Z</atom:updated>
            <content:encoded><![CDATA[<p>NLP and Machine Learning are both subsets of Artificial Intelligence. They have common and different properties. While we are creating a model, we can use them together.</p><p>In this article, I am going to show you the notebook in which I made NLP application with Machine Learning. But, before diving into the notebook and codes, let&#39;s take a glance at what ML and NLP are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Rk0mKL9Ee73EKh7xt4HfUA.png" /></figure><h3>What is NLP?</h3><p>Natural language processing (NLP) is the ability of a computer program to understand human language as it is spoken and written. NLP enables computers to understand natural language as humans do.</p><p>Some of the most popular applications of NLP include:</p><ul><li>Search</li><li>Information extraction</li><li>Sentiment analysis</li><li>Machine Translation</li><li>Auto-Predict</li><li>Spam Filter</li></ul><h3>What is ML?</h3><p>Machine learning (ML) is a method of data analysis that automates analytical model building. Thanks to machine learning, systems can learn from data, identify patterns and make decisions without requiring human intervention.</p><p>Some of the most popular applications of machine learning include:</p><ul><li>Self-driving cars</li><li>Fraud detection</li><li>Vision-based research</li><li>Price prediction</li></ul><p>Let&#39;s dive into the codes!</p><h3>About the Dataset and Notebook</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*zLjB2lcmhS13gBtHY12QUw.png" /></figure><p>The project is a sentiment analysis job about the problems of each major U.S. airline. Twitter data was scraped from February of 2015 and contributors were asked to first classify positive, negative, and neutral tweets, followed by categorizing negative reasons (such as “late flight” or “rude service”).</p><p>In the notebook, I am going to analyze airline tweets with machine learning models. I will use models, such as Naive Bayes, SVM, Random Forest, and XG Boost. Firstly, I will use count vectorizer for the models. Then, I will use TF-IDF. I will get both of them scores. Afterward, I will compare them.</p><p>In fact, Deep learning and pre-trained models are used more commonly in sentiment analysis jobs; however, since I will solve a classification problem (negative, positive, neutral), I can get predictions with machine learning models. The machine learning model scores will likely be lower than deep learning and pre-trained models. Nevertheless, machine learning models are easier to implement and they don’t require powerful machines like TPU / GPU.</p><p>First of all, I imported the necessary libraries.</p><pre><strong><br>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> seaborn <strong>as</strong> sns<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> nltk<br><strong>from</strong> nltk.tokenize <strong>import</strong> sent_tokenize, word_tokenize<br><strong>from</strong> nltk.corpus <strong>import</strong> stopwords<br><strong>from</strong> nltk.stem <strong>import</strong> WordNetLemmatizer<br><strong>from</strong> collections <strong>import</strong> Counter<br><strong>import</strong> warnings<br>warnings<strong>.</strong>filterwarnings(&quot;ignore&quot;)<br>plt<strong>.</strong>rcParams[&quot;figure.figsize&quot;] <strong>=</strong> (10,6)<br>pd<strong>.</strong>set_option(&#39;display.max_columns&#39;, 50)</pre><p><strong>(Natural Language Toolkit) NLTK</strong>: NLTK is a popular open-source package in Python. It provides us various text processing libraries with a lot of test datasets. A variety of tasks can be performed using NLTK such as tokenizing, parse tree visualization, etc…</p><h3>EDA (Exploratory Data Analysis)</h3><p>I read the data. The dataset has many features, including unnecessary ones, such as tweet_id, name, tweet_location, etc. However, in NLP just 2 features are used: target(airline_sentiment) and text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M59OebEv55OY6jJao_o4Sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIvnTz3-Fpjr_tG3fCqhVw.png" /></figure><p>I visualized the target variable according to airline names intending to show which airline business has the most negative comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*xK2SYulgSG_rYhq2f3ey8Q.png" /></figure><p>Next, I visualized negative reasons. From the graph, it can be understood that most of the negative comments are about customer service issues and late flights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*IkO5hvpMgurGhShD_7m7Hw.png" /></figure><p>I visualized the targets and their numbers, and I understood that the data is imbalanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pY5fO68zEsOU-SuEVfD0mw.png" /></figure><p>Before the cleaning stage I got a copy of the data and named it <em>df2</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*g2M8iBzbuFc6xdxdMA6RRA.png" /></figure><h3>Cleaning</h3><p>Now I will clean the data. I will remove the URLs, stopwords, and punctuations in this stage, and make the text clear.</p><pre>stop_words <strong>=</strong> stopwords<strong>.</strong>words(&#39;english&#39;)<br><br><strong>for</strong> i <strong>in</strong> [&quot;not&quot;, &quot;no&quot;]:<br>        stop_words<strong>.</strong>remove(i)</pre><p>Since I will do sentiment analysis, I removed ‘not’ and ‘no’ from stop words with the code above.</p><p>If I had given the code above inside the cleaning function, it would have given an error because it tries to remove ‘not’ and ‘no’ in every single sentence again and again. Therefore, I took this code outside of the cleaning function.</p><pre><strong>def</strong> cleaning(data):<br>    <br>    <strong>import</strong> re<br>    <br>    <em># To remove URLS</em><br>    data <strong>=</strong> re<strong>.</strong>sub(&#39;http\S+&#39;, &#39;&#39;, data)<strong>.</strong>strip()<br>    data <strong>=</strong> re<strong>.</strong>sub(&#39;www\S+&#39;, &#39;&#39;, data)<strong>.</strong>strip()<br><br>    <em># To remove Tags</em><br>    data <strong>=</strong> re<strong>.</strong>sub(&#39;#\S+&#39;, &#39;&#39;, data)<strong>.</strong>strip()<br><br>    <em># To remove Mentions</em><br>    data <strong>=</strong> re<strong>.</strong>sub(&#39;@\S+&#39;, &#39;&#39;, data)<strong>.</strong>strip()<br>    <br>    <em># To remove upper brackets to keep negative auxiliary verbs in text</em><br>    data <strong>=</strong> data<strong>.</strong>replace(&quot;&#39;&quot;, &quot;&quot;)<br>    <br>    <em># Tokenizing</em><br>    text_tokens <strong>=</strong> word_tokenize(data<strong>.</strong>lower())<br>    <br>    <em># To remove Puncs and number</em><br>    tokens_without_punc <strong>=</strong> [w <strong>for</strong> w <strong>in</strong> text_tokens <strong>if</strong> w<strong>.</strong>isalpha()]<br>    <br>    <em># To removing Stopwords</em><br>    tokens_without_sw <strong>=</strong> [t <strong>for</strong> t <strong>in</strong> tokens_without_punc <strong>if</strong> t <strong>not</strong> <strong>in</strong> stop_words]<br>    <br>    <em># Lemmatization</em><br>    text_cleaned <strong>=</strong> [WordNetLemmatizer()<strong>.</strong>lemmatize(t) <strong>for</strong> t <strong>in</strong> tokens_without_sw]<br>    <br>    <em>#joining</em><br>    <strong>return</strong> &quot; &quot;<strong>.</strong>join(text_cleaned)</pre><p>After creating the cleaning function, I applied it to the text data and renamed it “cleaning_text”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-7-qilg-3ajJoV0AJjOgSw.png" /></figure><p>I’ve cleaned the data with the cleaning function and saved it. I will use it for the word cloud stage.</p><p>Now, I got the main features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*qddyjz0-95RFri4jzd-91g.png" /></figure><p>I got the uncleaned version of the text because I will do the cleaning with a parameter inside the vectorizer function below.</p><h3>Train Test Split</h3><p>In this part, I will split the data into test and train. I split 25% of the data for test and 75% of it for training. Since the data is imbalanced, I used “<em>stratify=y”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7p5oV22xWY4nOLkS3KlU9g.png" /></figure><h3>Models with Vectorization</h3><p>In simple terms,<strong><em> Vectorization</em></strong> is the process of converting text into numerical representation. Since machines do not understand letters but numbers, we should convert texts into numbers.</p><h3>Count Vectorizer</h3><h4>preprocessor</h4><p>In CountVectorizer, there is a parameter as “<em>preprocessor</em>” which cleans the data automatically. I have created a “cleaning” function above, and I will use it here.</p><p>CountVectorizer does the cleaning automatically, so I don’t need to do the cleaning manually as I did above.</p><h4><em>min_df</em></h4><p><em>min_df </em>is used for removing terms that appear too frequently. For example:</p><p>min_df = 0.3 means &quot;ignore terms that appear in less than 3% of the documents&quot;.</p><p>min_df = 3means &quot;ignore terms that appear in less than 3 documents&quot;.</p><pre><strong>from</strong> sklearn.feature_extraction.text <strong>import</strong> CountVectorizer</pre><pre>vectorizer <strong>=</strong> CountVectorizer(preprocessor<strong>=</strong>cleaning, min_df<strong>=</strong>3)<br>X_train_count <strong>=</strong> vectorizer<strong>.</strong>fit_transform(X_train)<br>X_test_count <strong>=</strong> vectorizer<strong>.</strong>transform(X_test)</pre><p>I converted X_train_count to an array.</p><pre>X_train_count<strong>.</strong>toarray()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*YNSAaP9ta_xeR--bmsv9sw.png" /></figure><p>Next, I got the unique token names and converted them into a data frame.</p><pre>pd<strong>.</strong>DataFrame(X_train_count<strong>.</strong>toarray(), columns <strong>=</strong> vectorizer<strong>.</strong>get_feature_names_out())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZ-WSl4RM6n6QKudMh5IFQ.png" /></figure><p>It is time to get scores.</p><p>I imported the libraries.</p><pre><strong>from</strong> sklearn.metrics <strong>import</strong> confusion_matrix, classification_report, f1_score, recall_score</pre><p>Then I defined the evaluation function.</p><pre><strong>def</strong> eval(model, X_train, X_test):<br>    y_pred <strong>=</strong> model<strong>.</strong>predict(X_test)<br>    y_pred_train <strong>=</strong> model<strong>.</strong>predict(X_train)<br>    print(confusion_matrix(y_test, y_pred))<br>    print(&quot;Test_Set&quot;)<br>    print(classification_report(y_test,y_pred))<br>    print(&quot;Train_Set&quot;)<br>    print(classification_report(y_train,y_pred_train))</pre><h4><strong>Naive Bayes</strong></h4><p>I’ve created the model and got the first scores.</p><pre><strong>from</strong> sklearn.naive_bayes <strong>import</strong> MultinomialNB, BernoulliNB <em>#BernoulliNB for binary model</em></pre><pre>nb <strong>=</strong> MultinomialNB(alpha<strong>=</strong>2)<br>nb<strong>.</strong>fit(X_train_count,y_train)</pre><pre>print(&quot;NB MODEL&quot;)<br>eval(nb, X_train_count, X_test_count)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*8R23bvO0YM-ODdn2cinbOA.png" /></figure><p>I aimed to reveal negative comments, so I looked at the negative comments’ scores specifically. I wanted test and train scores to be as close to each other as possible.</p><p>Next, I made cross-validation to decide whether the scores are consistent or not.</p><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> cross_validate<br><strong>from</strong> sklearn.metrics <strong>import</strong> make_scorer<br><strong>from</strong> sklearn.metrics <strong>import</strong> f1_score, accuracy_score, precision_score, recall_score<br>scoring <strong>=</strong> {&#39;accuracy&#39;: make_scorer(accuracy_score),<br>            &#39;precision-neg&#39;: make_scorer(precision_score, average<strong>=None</strong>, labels<strong>=</strong>[&quot;negative&quot;]),<br>            &#39;recall-neg&#39;: make_scorer(recall_score, average<strong>=None</strong>, labels <strong>=</strong> [&quot;negative&quot;]),<br>            &#39;f1-neg&#39;: make_scorer(f1_score, average<strong>=None</strong>, labels <strong>=</strong> [&quot;negative&quot;])}<br><br>model <strong>=</strong> MultinomialNB(alpha=2)<br>scores <strong>=</strong> cross_validate(model, X_train_count, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*WkSVKePQ2Tphb9NkuGJj0A.png" /></figure><p>I verified that the scores are consistent.</p><p>Since the data is imbalanced, I should see the Precision and Recall curve.</p><pre><strong>from</strong> yellowbrick.classifier <strong>import</strong> PrecisionRecallCurve<br><br>viz <strong>=</strong> PrecisionRecallCurve(<br>    MultinomialNB(alpha<strong>=</strong>2),  <br>    classes<strong>=</strong>nb<strong>.</strong>classes_,  <br>    per_class<strong>=True</strong>,   <br>    cmap<strong>=</strong>&quot;Set1&quot; <br>)<br>viz<strong>.</strong>fit(X_train_count,y_train)<br>viz<strong>.</strong>score(X_test_count, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*mz5FYECZa0c5mXC6V-QM0w.png" /></figure><p>As I am going to compare the scores of each model at the end, I saved the scores.</p><pre>y_pred <strong>=</strong> nb<strong>.</strong>predict(X_test_count)<br>nb_count_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>nb_count_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>nb_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>— — — — — — — — — — — — — — — — — —</p><p><strong>Now, I will apply all these codes to each model. (Logistic Regression, SVM, Random Forest, and XGBoost)</strong></p><p>— — — — — — — — — — — — — — — — — —</p><h4>Logistic Regression</h4><pre><strong>from</strong> sklearn.linear_model <strong>import</strong> LogisticRegression<br>log <strong>=</strong> LogisticRegression(C <strong>=</strong> 0.03, max_iter<strong>=</strong>1500) <br>log<strong>.</strong>fit(X_train_count,y_train)</pre><pre>print(&quot;LOGISTIC MODEL&quot;)<br>eval(log, X_train_count, X_test_count)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*aqlKJU-IWwAgTiiWkboVqQ.png" /></figure><pre>model <strong>=</strong> LogisticRegression(C <strong>=</strong> 0.03, max_iter<strong>=</strong>1500)<br>scores <strong>=</strong> cross_validate(model, X_train_count, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*8m7DwRu6hGsYkRppkuu8Lw.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    LogisticRegression(C <strong>=</strong> 0.03, max_iter<strong>=</strong>1500),<br>    classes<strong>=</strong>log<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_count,y_train)<br>viz<strong>.</strong>score(X_test_count, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*A3aL9HfNq4a1mf9PjW31rw.png" /></figure><pre>y_pred <strong>=</strong> log<strong>.</strong>predict(X_test_count)<br>log_count_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>log_count_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>log_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>I could add “class_weight=balanced” into our parameters to get better scores for 3 of them, but, since I aim to reveal negative comments especially, I didn’t use it in the models.</p><p>— — — — — — — — — — — — — — — — — —</p><h4>SVM</h4><pre><strong>from</strong> sklearn.svm <strong>import</strong> LinearSVC<br>svc <strong>=</strong> LinearSVC(C<strong>=</strong>0.2)<br>svc<strong>.</strong>fit(X_train_count,y_train)</pre><pre>print(&quot;SVC MODEL&quot;)<br>eval(svc, X_train_count, X_test_count)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*TG-_fFPn7n0wiYoemtg3GQ.png" /></figure><pre>model <strong>=</strong> LinearSVC(C<strong>=</strong>0.2)<br>scores <strong>=</strong> cross_validate(model, X_train_count, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*KhU-lUAvFD2KAuL-Is622Q.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    LinearSVC(C<strong>=</strong>0.2),<br>    classes<strong>=</strong>svc<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_count,y_train)<br>viz<strong>.</strong>score(X_test_count, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*RG_TLzXo5YHR3fGoFCVerg.png" /></figure><pre>y_pred <strong>=</strong> svc<strong>.</strong>predict(X_test_count)<br>svc_count_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>svc_count_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>svc_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>— — — — — — — — — — — — — — — — — — — —</p><h3>Random Forest</h3><pre><strong>from</strong> sklearn.ensemble <strong>import</strong> RandomForestClassifier<br>rf <strong>=</strong> RandomForestClassifier(max_depth <strong>=</strong> 42, random_state <strong>=</strong> 10) <br>rf<strong>.</strong>fit(X_train_count, y_train)</pre><pre>print(&quot;RF MODEL&quot;)<br>eval(rf, X_train_count, X_test_count)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*WUP-kBGrI0dB2G8hRRyAyg.png" /></figure><pre>model <strong>=</strong> RandomForestClassifier(max_depth <strong>=</strong> 42, random_state <strong>=</strong> 10)<br>scores <strong>=</strong> cross_validate(model, X_train_count, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*7WpoyeBpb6zYHjJ3keC2fw.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    RandomForestClassifier(max_depth <strong>=</strong> 42, random_state <strong>=</strong> 10),<br>    classes<strong>=</strong>rf<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_count,y_train)<br>viz<strong>.</strong>score(X_test_count, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*02TpKfINoIGE8MMdoUNM7w.png" /></figure><pre>y_pred <strong>=</strong> rf<strong>.</strong>predict(X_test_count)<br>rf_count_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>rf_count_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>rf_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><h3>XG Boost</h3><pre><strong>from</strong> xgboost <strong>import</strong> XGBClassifier<br>xgb <strong>=</strong> XGBClassifier(random_state<strong>=</strong>10, max_depth <strong>=</strong> 7)<br>xgb<strong>.</strong>fit(X_train_count, y_train)</pre><pre>print(&quot;XG Boost MODEL&quot;)<br>eval(xgb, X_train_count, X_test_count)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*hp5uVsePAnQKE9BCYxYPlw.png" /></figure><pre>model <strong>=</strong> XGBClassifier(random_state<strong>=</strong>10, max_depth <strong>=</strong> 7)<br>scores <strong>=</strong> cross_validate(model, X_train_count, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*tRRmxTnb_9lepSyo9yf3hA.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    XGBClassifier(random_state<strong>=</strong>10, max_depth <strong>=</strong> 7),<br>    classes<strong>=</strong>xgb<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_count,y_train)<br>viz<strong>.</strong>score(X_test_count, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*in2MHkKKALcQjZZG3Dvptw.png" /></figure><pre>y_pred <strong>=</strong> xgb<strong>.</strong>predict(X_test_count)<br>xgb_count_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>xgb_count_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>xgb_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>— — — — — — — — — — — — — — — — — — — — — —</p><p><strong>I got the models’ scores after applying Count Vectorizer to the dataset. Now I will get each model’s scores after applying TF-IDF.</strong></p><p>— — — — — — — — — — — — — — — — — — — — —</p><h3>Models with TF ( Time-Frequency ) — IDF ( Inverse Document Frequency )</h3><p>Before moving on to the coding phase, let&#39;s talk about what TF and IDF are.</p><p><strong>TF</strong> measures how frequently a term occurs in a document</p><p><em>TF = (Number of repetitions of word in a document) / (# of words in a document)</em></p><p><strong>IDF </strong>measures how important a term is.</p><p><em>IDF =Log[(# Number of documents) / (Number of documents containing the word)] and</em></p><p>TF-IDF is better than Count Vectorizers because it not only focuses on the frequency of words present in the corpus but also provides the importance of the words.</p><p>Now, I will apply TF-IDF to the text.</p><pre><strong>from</strong> sklearn.feature_extraction.text <strong>import</strong> TfidfVectorizer</pre><pre>tf_idf_vectorizer <strong>=</strong> TfidfVectorizer(preprocessor<strong>=</strong>cleaning, min_df<strong>=</strong>3)<br>X_train_tf_idf <strong>=</strong> tf_idf_vectorizer<strong>.</strong>fit_transform(X_train)<br>X_test_tf_idf <strong>=</strong> tf_idf_vectorizer<strong>.</strong>transform(X_test)</pre><pre>X_train_tf_idf<strong>.</strong>toarray()</pre><pre>pd<strong>.</strong>DataFrame(X_train_tf_idf<strong>.</strong>toarray(), columns <strong>=</strong> tf_idf_vectorizer<strong>.</strong>get_feature_names_out())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbGKdMK5vBTer2nfCBjLHg.png" /></figure><p>I’ve applied tf_idf to our data and I will get scores of each model, just as I did for the count vectorization.</p><h4>Naive Bayes</h4><pre><strong>from</strong> sklearn.naive_bayes <strong>import</strong> MultinomialNB, BernoulliNB<br>nb <strong>=</strong> MultinomialNB(alpha<strong>=</strong>2)<br>nb<strong>.</strong>fit(X_train_tf_idf,y_train)</pre><pre>print(&quot;NB MODEL&quot;)<br>eval(nb, X_train_tf_idf, X_test_tf_idf)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*fzcEV0oD1rcT6N0UZh8g5A.png" /></figure><pre>model <strong>=</strong> MultinomialNB(alpha<strong>=</strong>2)<br>scores <strong>=</strong> cross_validate(model, X_train_tf_idf, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*2hONnuyQj5yN6FuZ1Obb-Q.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    MultinomialNB(alpha<strong>=</strong>2),<br>    classes<strong>=</strong>nb<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_tf_idf,y_train)<br>viz<strong>.</strong>score(X_test_tf_idf, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*XezBOFrAsn-axw4w_05k4g.png" /></figure><pre>y_pred <strong>=</strong> nb<strong>.</strong>predict(X_test_tf_idf)<br>nb_tfidf_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>nb_tfidf_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>nb_tfidf_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>— — — — — — — — — — — — — — — — —</p><h4>Logistic Regression</h4><pre><strong>from</strong> sklearn.linear_model <strong>import</strong> LogisticRegression<br>log <strong>=</strong> LogisticRegression(C<strong>=</strong>0.3, max_iter<strong>=</strong>1500)<br>log<strong>.</strong>fit(X_train_tf_idf,y_train)</pre><pre>print(&quot;LOGISTIC MODEL&quot;)<br>eval(log, X_train_tf_idf, X_test_tf_idf)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*9vSd2GpEgMQsoqz2DpUAtg.png" /></figure><pre>model <strong>=</strong> LogisticRegression(C<strong>=</strong>0.3, max_iter<strong>=</strong>1500)<br>scores <strong>=</strong> cross_validate(model, X_train_tf_idf, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*aOvBOdSYxtLwARarf3ObYw.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    LogisticRegression(C<strong>=</strong>0.3, max_iter<strong>=</strong>1000),<br>    classes<strong>=</strong>log<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_tf_idf,y_train)<br>viz<strong>.</strong>score(X_test_tf_idf, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*b_WH-XLtMy8Mo-dnsJL0OA.png" /></figure><pre>y_pred <strong>=</strong> log<strong>.</strong>predict(X_test_tf_idf)<br>log_tfidf_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>log_tfidf_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>log_tfidf_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>— — — — — — — — — — — — — — — — — — —</p><h4>SVM</h4><pre><strong>from</strong> sklearn.svm <strong>import</strong> LinearSVC<br>svc <strong>=</strong> LinearSVC(C<strong>=</strong>0.1)<br>svc<strong>.</strong>fit(X_train_tf_idf,y_train)</pre><pre>print(&quot;SVC MODEL&quot;)<br>eval(svc, X_train_tf_idf, X_test_tf_idf)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*NWaUir7QLXLtJPG5e7rpfA.png" /></figure><pre>model <strong>=</strong> LinearSVC(C<strong>=</strong>0.1)<br>scores <strong>=</strong> cross_validate(model, X_train_tf_idf, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*ckkm5wdDhQIpCjrrsCGluA.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    LinearSVC(C<strong>=</strong>0.1),<br>    classes<strong>=</strong>svc<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_tf_idf,y_train)<br>viz<strong>.</strong>score(X_test_tf_idf, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-RrokQ_6n42nlmmj3lmLrQ.png" /></figure><pre>y_pred <strong>=</strong> svc<strong>.</strong>predict(X_test_tf_idf)<br>svc_tfidf_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>svc_tfidf_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>svc_tfidf_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>— — — — — — — — — — — — — — — — —</p><h3>RandomForest</h3><pre>rf <strong>=</strong> RandomForestClassifier(max_depth <strong>=</strong> 55, random_state <strong>=</strong> 10)<br>rf<strong>.</strong>fit(X_train_tf_idf, y_train)</pre><pre>print(&quot;RF MODEL&quot;)<br>eval(rf, X_train_tf_idf, X_test_tf_idf)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*M8xCTrsrvdDn2skx6RLArw.png" /></figure><pre>model <strong>=</strong> RandomForestClassifier(max_depth <strong>=</strong> 55, random_state <strong>=</strong> 10)<br>scores <strong>=</strong> cross_validate(model, X_train_tf_idf, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*qgYZ4FMTorsGoHdqNHYd1w.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    RandomForestClassifier(100, max_depth<strong>=</strong>40, random_state <strong>=</strong> 42, n_jobs <strong>=</strong> <strong>-</strong>1),<br>    classes<strong>=</strong>rf<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_tf_idf,y_train)<br>viz<strong>.</strong>score(X_test_tf_idf, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*KJno9jLBOeyZ894bWHE-fA.png" /></figure><pre>y_pred <strong>=</strong> rf<strong>.</strong>predict(X_test_tf_idf)<br>rf_tfidf_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>rf_tfidf_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>rf_tfidf_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>— — — — — — — — — — — — — — — — — — —</p><h4>XG Boost</h4><pre><strong>from</strong> xgboost <strong>import</strong> XGBClassifier<br>xgb <strong>=</strong> XGBClassifier(random_state<strong>=</strong>10, max_depth <strong>=</strong> 5)<br>xgb<strong>.</strong>fit(X_train_tf_idf, y_train)</pre><pre>print(&quot;XG Boost MODEL&quot;)<br>eval(xgb, X_train_tf_idf, X_test_tf_idf)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*7bcKCajz3kFzvYK68mnBPg.png" /></figure><pre>model <strong>=</strong> XGBClassifier(random_state<strong>=</strong>10, max_depth <strong>=</strong> 5)<br>scores <strong>=</strong> cross_validate(model, X_train_tf_idf, y_train, scoring <strong>=</strong> scoring, cv <strong>=</strong> 10)<br>df_scores <strong>=</strong> pd<strong>.</strong>DataFrame(scores, index <strong>=</strong> range(1, 11))<br>df_scores<strong>.</strong>mean()[2:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*3FqjEcdJDsYUotbRGbrztQ.png" /></figure><pre>viz <strong>=</strong> PrecisionRecallCurve(<br>    XGBClassifier(random_state<strong>=</strong>10, max_depth <strong>=</strong> 5),<br>    classes<strong>=</strong>xgb<strong>.</strong>classes_,<br>    per_class<strong>=True</strong>,<br>    cmap<strong>=</strong>&quot;Set1&quot;<br>)<br>viz<strong>.</strong>fit(X_train_tf_idf,y_train)<br>viz<strong>.</strong>score(X_test_tf_idf, y_test)<br>viz<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*UT806MDNw1Jo-KDA_vVPHA.png" /></figure><pre>y_pred <strong>=</strong> xgb<strong>.</strong>predict(X_test_tf_idf)<br>xgb_tfidf_rec_neg <strong>=</strong> recall_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>xgb_tfidf_f1_neg <strong>=</strong> f1_score(y_test, y_pred, labels <strong>=</strong> [&quot;negative&quot;], average <strong>=</strong> <strong>None</strong>)<br>xgb_tfidf_AP_neg <strong>=</strong> viz<strong>.</strong>score_[&quot;negative&quot;]</pre><p>— — — — — — — — — — — — — — — — — — — —</p><h3>Comparing Scores</h3><pre>compare <strong>=</strong> pd<strong>.</strong>DataFrame({&quot;Model&quot;: [&quot;NaiveBayes_count&quot;, &quot;LogReg_count&quot;, &quot;SVM_count&quot;, &quot;Random Forest_count&quot;, <br>                                  &quot;XGB_count&quot;, &quot;NaiveBayes_tfidf&quot;, &quot;LogReg_tfidf&quot;, &quot;SVM_tfidf&quot;, <br>                                  &quot;Random Forest_tfidf&quot;, &quot;XGB_tfidf&quot;],<br>                        <br>                        &quot;F1_Score_Negative&quot;: [nb_count_f1_neg[0], log_count_f1_neg[0], svc_count_f1_neg[0],rf_count_f1_neg[0],<br>                                              xgb_count_f1_neg[0], nb_tfidf_f1_neg[0], log_tfidf_f1_neg[0], svc_tfidf_f1_neg[0],<br>                                              rf_tfidf_f1_neg[0], xgb_tfidf_f1_neg[0]],<br>                        <br>                        &quot;Recall_Score_Negative&quot;: [nb_count_rec_neg[0], log_count_rec_neg[0], svc_count_rec_neg[0], <br>                                                  rf_count_rec_neg[0], xgb_count_rec_neg[0], nb_tfidf_rec_neg[0], <br>                                                  log_tfidf_rec_neg[0], svc_tfidf_rec_neg[0],rf_tfidf_rec_neg[0],<br>                                                  xgb_tfidf_rec_neg[0]],<br>                        <br>                        &quot;Precision_Recall_Score_Negative&quot;: [nb_AP_neg, log_AP_neg, svc_AP_neg, rf_AP_neg, xgb_AP_neg,<br>                                                            nb_tfidf_AP_neg, log_tfidf_AP_neg, svc_tfidf_AP_neg,<br>                                                            rf_tfidf_AP_neg, xgb_tfidf_AP_neg]})<br><br><strong>def</strong> labels(ax):<br>                        <br>    <strong>for</strong> p <strong>in</strong> ax<strong>.</strong>patches:<br>        width <strong>=</strong> p<strong>.</strong>get_width()                        <em># get bar length</em><br>        ax<strong>.</strong>text(width,                               <em># set the text at 1 unit right of the bar</em><br>                p<strong>.</strong>get_y() <strong>+</strong> p<strong>.</strong>get_height() <strong>/</strong> 2,      <em># get Y coordinate + X coordinate / 2</em><br>                &#39;{:1.3f}&#39;<strong>.</strong>format(width),             <em># set variable to display, 2 decimals</em><br>                ha <strong>=</strong> &#39;left&#39;,                         <em># horizontal alignment</em><br>                va <strong>=</strong> &#39;center&#39;)                       <em># vertical alignment</em><br>    <br>plt<strong>.</strong>figure(figsize<strong>=</strong>(15,30))<br>plt<strong>.</strong>subplot(311)<br>compare <strong>=</strong> compare<strong>.</strong>sort_values(by<strong>=</strong>&quot;Recall_Score_Negative&quot;, ascending<strong>=False</strong>)<br>ax<strong>=</strong>sns<strong>.</strong>barplot(x<strong>=</strong>&quot;Recall_Score_Negative&quot;, y<strong>=</strong>&quot;Model&quot;, data<strong>=</strong>compare, palette<strong>=</strong>&quot;ch:8.5,.5,dark=.3&quot;)<br>labels(ax)<br><br>plt<strong>.</strong>subplot(312)<br>compare <strong>=</strong> compare<strong>.</strong>sort_values(by<strong>=</strong>&quot;F1_Score_Negative&quot;, ascending<strong>=False</strong>)<br>ax<strong>=</strong>sns<strong>.</strong>barplot(x<strong>=</strong>&quot;F1_Score_Negative&quot;, y<strong>=</strong>&quot;Model&quot;, data<strong>=</strong>compare, palette<strong>=</strong>&quot;ch:8.5,.5,dark=.3&quot;)<br>labels(ax)<br><br><br>plt<strong>.</strong>subplot(313)<br>compare <strong>=</strong> compare<strong>.</strong>sort_values(by<strong>=</strong>&quot;Precision_Recall_Score_Negative&quot;, ascending<strong>=False</strong>)<br>ax<strong>=</strong>sns<strong>.</strong>barplot(x<strong>=</strong>&quot;Precision_Recall_Score_Negative&quot;, y<strong>=</strong>&quot;Model&quot;, data<strong>=</strong>compare, palette<strong>=</strong>&quot;ch:8.5,.5,dark=.3&quot;)<br>labels(ax)<br>plt<strong>.</strong>show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TbBqtSLA_0MlaNjo_QtCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeOXzX5Mpm48sYYpM2YZ1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b14JWr_cPFpz4dIoqtl1lg.png" /></figure><p>I didn’t get the precision scores. Rather, I got the <em>f1 score</em> for each model, which is a harmonic average of precision and recall scores.</p><p>After considering 3 graphs, I decided that Logistic Regression with tf_idf is the best model.</p><h3>For new Tweets, prediction with pipeline</h3><p>Finally, I am going to create the model with Pipeline and get new predictions.</p><pre><strong>from</strong> sklearn.pipeline <strong>import</strong> Pipeline</pre><pre>pipe <strong>=</strong> Pipeline([(&#39;tfidf&#39;,TfidfVectorizer(preprocessor<strong>=</strong>cleaning, min_df<strong>=</strong>3)),(&#39;log&#39;,LogisticRegression(C<strong>=</strong>0.3, max_iter<strong>=</strong>1000))])</pre><pre>pipe<strong>.</strong>fit(X, y)</pre><p>Now, I will give 3 different sentences to the model including neutral, positive, and negative.</p><pre>tweet <strong>=</strong> &quot;so so&quot;<br>tweet <strong>=</strong> pd<strong>.</strong>Series(tweet)<br>pipe<strong>.</strong>predict(tweet)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*cf9Xso-MFcUwWCT14t4xSw.png" /></figure><pre>tweet <strong>=</strong> &quot;customer sevices were slow&quot;<br>tweet <strong>=</strong> pd<strong>.</strong>Series(tweet)<br>pipe<strong>.</strong>predict(tweet)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*cf9Xso-MFcUwWCT14t4xSw.png" /></figure><pre>tweet <strong>=</strong> &quot;it is amazing&quot;<br>tweet <strong>=</strong> pd<strong>.</strong>Series(tweet)<br>pipe<strong>.</strong>predict(tweet)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*e2xjua8cd2XtUtmzeflX6Q.png" /></figure><p>The model is successful in detecting negative and positive comments, yet not successful enough to catch the neutral ones.</p><h3>Wordcloud</h3><p>Last but not least, I am going to create a wordcloud in the form of a plane representing the most common words used in the text .</p><p>I imported the necessary libraries.</p><pre><strong>import</strong> numpy <strong>as</strong> np<br><strong>from</strong> os <strong>import</strong> path<br><strong>from</strong> PIL <strong>import</strong> Image<br><strong>from</strong> wordcloud <strong>import</strong> WordCloud, STOPWORDS, ImageColorGenerator</pre><p>As you remember, I’ve cleaned the text in the first steps and I’ve saved it <em>cleaning_text</em>.</p><pre>tweets <strong>=</strong> cleaning_text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*ywV_KnsOX9Qicyi-MXbheg.png" /></figure><p>I joined the tweets.</p><pre>all_words <strong>=</strong> &quot; &quot;<strong>.</strong>join(tweets)</pre><p>I opened the image I am going to use.</p><pre>flight_mask <strong>=</strong> np<strong>.</strong>array(Image<strong>.</strong>open(&quot;../input/plane-im/plane_im.jpg&quot;))</pre><p>I converted the zeros to 255 because masking functions requires all white part of the mask to be 255, not 0. This value represents the “intensity” of the pixel. Values of 255 are pure white, while values of 1 are black.</p><pre><strong>def</strong> transform_format(val):<br>    <strong>if</strong> val<strong>.</strong>any() <strong>==</strong> 0:<br>        <strong>return</strong> 255<br>    <strong>else</strong>:<br>        <strong>return</strong> val</pre><p>Finally, I defined the wordcloud. I want the model to display a maximum of 200 words, so I added “<em>max_words=200”</em>.</p><pre><em># Create a word cloud image</em><br>wc <strong>=</strong> WordCloud(background_color<strong>=</strong>&quot;white&quot;,  mask<strong>=</strong> flight_mask, max_words<strong>=</strong>200, contour_color<strong>=</strong>&#39;blue&#39;)<br><br><em># Generate a wordcloud</em><br>wc<strong>.</strong>generate(all_words)<br><br><em># show</em><br>plt<strong>.</strong>figure(figsize<strong>=</strong>[10,15])<br>plt<strong>.</strong>imshow(wc, interpolation<strong>=</strong>&#39;bilinear&#39;)<br>plt<strong>.</strong>axis(&quot;off&quot;)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*ELAw5GwAV6nwDOLN1cLIfA.png" /></figure><p>If you want to see more details, you can check the <a href="https://www.kaggle.com/code/dilaraozcerit/airline-sentiment-analysis">notebook</a>.</p><h3>References</h3><ol><li><a href="https://www.upgrad.com/blog/machine-learning-vs-nlp/">https://www.upgrad.com/blog/machine-learning-vs-nlp/</a></li><li><a href="https://www.analyticsvidhya.com/blog/2021/07/nltk-a-beginners-hands-on-guide-to-natural-language-processing/">https://www.analyticsvidhya.com/blog/2021/07/nltk-a-beginners-hands-on-guide-to-natural-language-processing/</a></li><li><a href="https://www.datacamp.com/tutorial/wordcloud-python">https://www.datacamp.com/tutorial/wordcloud-python</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=873b10e99f3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>