<?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 Abdulraqib Omotosho on Medium]]></title>
        <description><![CDATA[Stories by Abdulraqib Omotosho on Medium]]></description>
        <link>https://medium.com/@abdulraqibshakir03?source=rss-b25e6936214d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sZUI6cGalToZLiQ8Roj9hw.jpeg</url>
            <title>Stories by Abdulraqib Omotosho on Medium</title>
            <link>https://medium.com/@abdulraqibshakir03?source=rss-b25e6936214d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:30:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdulraqibshakir03/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[MY REVIEW ON THE “TO SMOTE, OR NOT TO SMOTE PAPER"]]></title>
            <link>https://medium.com/@abdulraqibshakir03/my-review-on-the-to-smote-or-not-to-smote-paper-bd0b44cfcefa?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd0b44cfcefa</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 13:31:30 GMT</pubDate>
            <atom:updated>2024-01-15T13:33:12.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GUqtPzSqGHZPjKyS" /><figcaption>Photo by Jason Hudson on Unsplash</figcaption></figure><p>The paper investigates whether data balancing/oversampling techniques like SMOTE are beneficial for imbalanced binary classification, especially when using strong state-of-the-art classifiers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*DsqX_xIwNHUO5CsBDEWRmQ.png" /><figcaption>excerpts from the paper.</figcaption></figure><h3>Objectives</h3><p>- Investigate whether balancing/oversampling minority class data is beneficial for imbalanced binary classification, especially with strong modern classifiers.</p><p>- Provide extensive empirical analysis using proper scoring metrics like AUC and label metrics like F1.</p><p>- Evaluate impact of tuning hyperparameters versus using a priori exceptional values.</p><p>- Compare oversampling to optimizing decision thresholds for label metrics.</p><p>- Identify scenarios where oversampling is and is not useful.</p><p>- Relate results to theories on proper metrics, consistent algorithms, etc.</p><h3>Methods</h3><p>- Use 73 real-world imbalanced datasets from various sources.</p><p>- Test 3 strong classifiers (LightGBM, XGBoost, CatBoost) and 4 weaker classifiers (MLP, SVM, decision tree, AdaBoost).</p><p>- Compare default classifiers, tuned classifiers, and classifiers with oversampling using SMOTE, ADASYN, etc.</p><p>- Evaluate proper metrics like AUC, log loss. Also label metrics like F1 with fixed and optimized thresholds.</p><p>- Test impact of a priori versus validated tuning of oversampling hyperparameters.</p><p>- Relate results to consistency theory and proper metrics. Show AUC is proper under common assumptions.</p><h3>Results</h3><p>- With proper metrics, oversampling only helps weaker classifiers, hurts strong classifiers.</p><p>- Strong classifiers without oversampling outperform weak classifiers with oversampling.</p><p>- Oversampling improves minority probability predictions but worsens majority and overall log loss.</p><p>- With label metrics and fixed thresholds, oversampling improves all classifiers. But simple random oversampling is as good as SMOTE.</p><p>- With optimized thresholds, oversampling only helps very weak classifiers like MLP. Threshold optimization otherwise preferred.</p><p>- A priori exceptional hyperparameters can make oversampling helpful for all classifiers, but risks overfitting.</p><h3>Conclusions</h3><p>- Oversampling generally does not help with strong modern classifiers, proper metrics.</p><p>- Simpler solutions like threshold optimization typically preferred over complex oversampling.</p><p>- Oversampling still useful in some scenarios like with weak learners or fixed thresholds.</p><p>- Results align with theories on proper metrics, consistent algorithms. AUC is proper under common assumptions.</p><p>- Most prior empirical studies focused on scenarios where oversampling does help.</p><p>- SMOTE and other oversampling techniques are very popular, but their usefulness is limited based on this study.</p><p>- The skewed class distribution may not be the core reason for poor performance on imbalanced data. Other factors like small sample size may play a bigger role.</p><p>- Proper scoring metrics like AUC associate higher loss with minority misclassifications. But optimizing symmetric loss still optimizes the proper metric under common assumptions.</p><p>- Label metrics like F1 score require setting a decision threshold. Optimizing this threshold makes the algorithm consistent for the metric.</p><p>- Oversampling techniques add many more hyperparameters that can lead to overfitting if tuned improperly. Simpler solutions are preferable.</p><p>- Theoretical analysis and results on proper metrics, consistent algorithms, and threshold optimization have been underutilized.</p><p>- More empirical studies should include strong modern classifiers as baselines when evaluating techniques for imbalanced classification.</p><p>- Techniques customized for imbalanced data may not be needed given algorithms like XGBoost that perform well on imbalanced problems.</p><p>- Preprocessing the training data through oversampling should not be a default tactic when dealing with skewed datasets. Its benefits are limited.</p><p>- There are still some open research questions, like explaining why oversampling shows more benefits for weak learners compared to strong ones.</p><h4>The key conclusion is that oversampling should not be a default tactic when dealing with class imbalance, contrary to popular practice. The paper provides an empirical basis to help guide the appropriate use of oversampling.</h4><p>To read the full paper, you can download it <a href="https://arxiv.org/abs/2201.08528">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd0b44cfcefa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Data Import into MySQL and PostgreSQL: Mastering Command-Line Techniques]]></title>
            <link>https://pub.towardsai.net/efficient-data-import-into-mysql-and-postgresql-mastering-command-line-techniques-e002a737f5e8?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e002a737f5e8</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 20:02:09 GMT</pubDate>
            <atom:updated>2023-12-20T20:02:09.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uaSdz8VSTJtdqwXn" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the field of database management, the ability to seamlessly import data is a crucial skill for any developer or data professional. While graphical user interfaces (GUIs) and tools like PgAdmin Workbench provide convenient interfaces for managing databases, there’s a distinct power and efficiency in using the command line to import data directly into MySQL and PostgreSQL. This article will guide you through the command-line methods for importing data, offering a hands-on approach that not only enhances your command-line prowess but also provides a deeper understanding of the underlying processes. It will empower you to efficiently import data into MySQL and PostgreSQL, paving the way for streamlined and scriptable database interactions whether you’re a seasoned command-line enthusiast or a newcomer looking to broaden your database management skills.</p><h3>PostgreSQL</h3><p>PostgreSQL, often referred to as “Postgres,” stands as a robust and open-source relational database management system (RDBMS). What sets PostgreSQL apart is its extensibility, standards compliance, and advanced features, making it a powerful choice for handling diverse data scenarios. Its support for various data types, indexing options, and complex queries positions it as a versatile solution for data management. When it comes to data import into SQL databases, PostgreSQL’s reliability, scalability, and extensibility make it an ideal candidate. Its ability to handle large datasets, coupled with support for complex operations, ensures a seamless and efficient data import process, making PostgreSQL a go-to choice for those seeking a powerful, open-source solution in the realm of SQL databases.</p><p><em>Without further ado, let’s get to the heart of the matter….</em></p><p>Firstly, for Windows users, let’s navigate to the SQL Shell (psql) on the desktop. Open the application by searching for “SQL Shell” or “psql” in the Start menu. Now, for Mac users, access the Terminal application, which serves as the command line interface. You can find it in the Applications &gt; Utilities folder or by searching for “Terminal” using Spotlight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*B1ffFFA7u4Xu8BmlbffFZQ.jpeg" /><figcaption>SQL Shell (psql) on Windows</figcaption></figure><p>Next, in the Terminal or SQL Shell, hit Enter to navigate through the Server (localhost), Database (postgres), Port (5433), and Username (postgres). You’ll then be prompted to enter the password for the database. After entering the password successfully, you should see the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*kGCdCtl1rUUhtL9-QC4VyA.jpeg" /></figure><p>Following the navigation steps, create a database using the command below. In this instance, I’ve named it “salesrecord”.</p><pre>CREATE DATABASE salesrecord;</pre><p>Now, let’s connect to the newly created database, “salesrecord,” using the following command:</p><pre>\c salesrecord;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*VCny-sI1HIRUyE7W5TE02w.jpeg" /><figcaption>You will get this message once you connect to the database.</figcaption></figure><p>Next, let’s create a table named “salesdata” in the database with specified column names and data types using the following command:</p><pre>CREATE TABLE salesdata (<br>    region VARCHAR(255),<br>    country VARCHAR(255),<br>    item_types VARCHAR(255),<br>    sales_channel VARCHAR(255),<br>    order_priority VARCHAR(255),<br>    order_date DATE,<br>    order_id BIGINT,<br>    ship_date DATE,<br>    units_sold BIGINT,<br>    unit_price NUMERIC,<br>    unit_cost NUMERIC,<br>    total_revenue DECIMAL(10, 2),<br>    total_cost NUMERIC,<br>    total_profit DECIMAL(10, 2)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*zwK8wfDjysg0HpRrdmkFHQ.jpeg" /><figcaption>Successfully created a table, salesdata in the database.</figcaption></figure><p>Finally, effortlessly import data into the “salesdata” table within seconds using the command below. Remember to specify the complete path of the file directory for seamless execution. In this instance, I’m importing from the “Datasets” directory within the “Python” folder on the Desktop, located in the Users directory on my local drive.</p><pre>COPY salesdata <br>FROM &#39;C:/Users/user/Desktop/__Python__/Datasets/500000 Sales Records.csv&#39; <br>WITH (FORMAT csv, DELIMITER &#39;,&#39;,  HEADER true);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*HjggrTfKqkSVsQa2aDPKZw.jpeg" /><figcaption>Import into the table successful!</figcaption></figure><p>After following all the above steps, we have our data successfully imported into the table in the database in just a few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8az9LPKAUWdSqqXBSt3h-g.jpeg" /><figcaption>Dataset successfully imported into the table in the database.</figcaption></figure><h3>MYSQL</h3><p>MySQL, often called MySQL, is a strong and open-source database system. It’s known for being adaptable, following standards, and having advanced features, making it great for handling different types of data. With support for various data types and efficient ways of organizing data, MySQL is a versatile choice. When it comes to importing data into SQL databases, MySQL is reliable, scalable, and flexible. It can handle large amounts of data and complex operations, ensuring a smooth and effective importing process. MySQL is a top pick for those seeking a powerful, open-source solution for SQL databases.</p><p><em>Without further ado, let’s get to the heart of the matter….</em></p><p>For Windows users, search for “Command Prompt” in the Start menu, then right-click on “Command Prompt” and select “Run as administrator” to launch the MySQL Command Line Client with elevated privileges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*V_c-TBt2g6j1TPnAtu95tA.jpeg" /></figure><p>Navigate to the MySQL command line directory on your local drive using the terminal. In my case, I achieved this by executing the following command. This command ensures that you are in the correct directory for accessing MySQL’s command-line tools.</p><pre>cd C:\Program Files\MySQL\MySQL Server 8.0\bin</pre><p>Next, run the below command, which prompts you to enter your password.</p><pre>mysql -u root -p --local_infile</pre><p>After entering the password successfully, you should see the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*4kmCvWDNg6Mtk6oYx8s59Q.jpeg" /></figure><p>Following the navigation steps, create a database using the command below. In this instance, I’ve named it “salesrecord”.</p><pre>CREATE DATABASE salesrecord;</pre><p>Now, let’s connect to the newly created database, “salesrecord,” using the following command:</p><pre>USE salesrecord;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*tYGWkIsrSs6aefxAcJCeNw.jpeg" /><figcaption>You will get this message once you connect to the database.</figcaption></figure><blockquote>Enabling ‘SET GLOBAL local_infile = ‘ON’;’ becomes essential when efficient data loading from a local file into a MySQL table using the ‘LOAD DATA LOCAL INFILE’ statement is desired. This feature streamlines the data import process, contributing to a smoother user experience. However, it’s important to be aware that activating ‘local_infile’ introduces security considerations, particularly if the MySQL server is accessible over a public network. Once the data import is completed, the ‘local_infile’ option should be promptly disabled by executing ‘SET GLOBAL local_infile = ‘OFF’;’ to minimize potential vulnerabilities and ensure a secure MySQL environment. Users are encouraged to enable ‘local_infile’ selectively for specific tasks and disable it promptly afterward, prioritizing security within their MySQL setups.</blockquote><pre>SET GLOBAL local_infile = &#39;ON&#39;</pre><p>Next, let’s create a table named “salesdata” in the database with specified column names and data types using the following command:</p><pre>CREATE TABLE salesdata (<br>    region VARCHAR(255),<br>    country VARCHAR(255),<br>    item_types VARCHAR(255),<br>    sales_channel VARCHAR(255),<br>    order_priority VARCHAR(255),<br>    order_date DATE,<br>    order_id BIGINT,<br>    ship_date DATE,<br>    units_sold BIGINT,<br>    unit_price DECIMAL(10, 2),<br>    unit_cost DECIMAL(10, 2),<br>    total_revenue DECIMAL(10, 2),<br>    total_cost DECIMAL(10, 2),<br>    total_profit DECIMAL(10, 2)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*lwPh8XB-nuII5c6xXmtKVQ.jpeg" /><figcaption>Successfully created a table, salesdata in the database.</figcaption></figure><p>Finally, effortlessly import data into the “salesdata” table within seconds using the command below. Remember to specify the complete path of the file directory for seamless execution. In this instance, I’m importing from the below directory in my local drive.</p><pre>LOAD DATA LOCAL INFILE &#39;C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads\\500000 Sales Records.csv&#39;<br>INTO TABLE salesdata<br>FIELDS TERMINATED BY &#39;,&#39;<br>ENCLOSED BY &#39;&quot;&#39;<br>LINES TERMINATED BY &#39;\n&#39;<br>IGNORE 1 ROWS;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*NMYVbDFcwwiqOctcdxhSBQ.jpeg" /><figcaption>Import into the table successful!</figcaption></figure><p>After completing the aforementioned steps, our data has been seamlessly imported into the database table within a matter of seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYx6AtdcVkAExae-W1qURQ.jpeg" /><figcaption>Dataset successfully imported into the table in the database.</figcaption></figure><p>In conclusion, this tutorial has equipped you with essential command-line skills for swift and efficient data management in both MySQL and PostgreSQL. By steering clear of the sluggish import processes associated with graphical interfaces like Workbench or PgAdmin, this tutorial champions the command line for a faster and more efficient data import experience. Ditch slow clicks and embrace speedy command lines.</p><p>Happy querying!!</p><blockquote>Thanks for reading — I hope you found this piece enjoyable🤗! Connect with me on <a href="https://medium.com/twitter.com/raqibcodes">X (formerly Twitter)</a>, <a href="https://github.com/Abdulraqib20">GitHub</a> or <a href="https://www.linkedin.com/in/abdulraqib-omotosho">LinkedIn</a> and explore more of my stories <a href="https://medium.com/@abdulraqibshakir03">here</a>. Cheers!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e002a737f5e8" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/efficient-data-import-into-mysql-and-postgresql-mastering-command-line-techniques-e002a737f5e8">Efficient Data Import into MySQL and PostgreSQL: Mastering Command-Line Techniques</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Data Seas: My Year-Long Voyage into the World of Data Science]]></title>
            <link>https://medium.com/ai-unleased/navigating-the-data-seas-my-year-long-voyage-into-the-world-of-data-science-3a490edf4815?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a490edf4815</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 10:57:23 GMT</pubDate>
            <atom:updated>2023-11-24T20:50:34.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mqsi3uSTcGXQJUWl" /><figcaption>Photo by <a href="https://unsplash.com/@arstyy?utm_source=medium&amp;utm_medium=referral">Austin Neill</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It all started by pure chance during a period of unforeseen circumstances. I had just completed 200 level and my university was on a year-long strike and I suddenly found myself with an abundance of free time and a strong desire to explore new horizons. Up until then, the term “data science” had been a complete mystery to me. My tech journey had yet to begin properly, and my comfort zone consisted of design tools like Photoshop and Figma. While design was a passion, I yearned for something more.</p><p>Then, I stumbled upon Python, online, a programming language that intrigued me. But little did I know, this seemingly random discovery would set the stage for a profound transformation in my life. As fate would have it, my path to data science was further shaped by social media. My Twitter feed, which used to be filled with posts about my favorite sport, football, went through a significant shift. Suddenly, posts about data science began appearing on my timeline, and I found myself drawn to them. I started liking and retweeting these data science posts with a genuine sense of curiosity. What happened next was nothing short of remarkable — football-related tweets slowly but steadily disappeared from my timeline and <em>data science</em> started appearing more and more (I later got to understood why this was happening later on anyway). This made me curious, and I decided to find out what data science was all about.</p><p>To get a grasp of this new language, I turned to online resources and got to take Udacity’s free Python programming course. Each day was a step forward, and I slowly began to understand the basics of python, functions and scripting. Thereafter, I proceeded to learn how to harness the power of Python for data analysis where I was introduced to libraries and modules such as Pandas, NumPy, and Matplotlib, which are fundamental to data analysis. I then enrolled in the Google Data Analytics Professional Course and got a very solid understanding of what data analytics entails where I got introduced to the tools widely used in the field including Google Sheets &amp; Microsoft Excel, SQL, Tableau and the R programming language. I also got acquainted with the way data professionals approach and solve business problems. All of this gave me a very solid background in the data space and paved the way for deeper exploration within this exciting field.</p><p>Next on, I took the Machine Learning Specialization course curated by the influential computer scientist, Andrew Ng. This was a game-changer as it introduced me to the world of machine learning, the heartbeat of AI. The course provided me with a deep understanding of Machine Learning principles &amp; techniques where I also familiarized myself with further toolkits used by data scientists including the web-based <em>jupyter notebook</em>.</p><p>Eager to apply all I had learnt, I created a GitHub account and started building projects. It became a platform for showcasing my growing skills and knowledge. I started with small projects including the popular <em>“Hello World”</em> project of ML- The Titanic Survival Prediction and then gradually tacking more complex challenges. I then began regularly committing my codes and projects to GitHub. This hands-on experience was vital in refining my understanding and having practical skills in the field of data science and machine learning.</p><p>Lest I forget, I successfully enrolled in the <a href="https://learn.udacity.com/nanodegrees/nd002-alg-">Udacity Data Analyst Nanodegree</a> programme via a scholarship from ALX. Here, I delved deeper into advanced concepts in data analytics. I gained expertise in various critical areas including data wrangling, data cleaning, data investigation, data visualization, effective communication with stakeholders and presenting findings. This intensive program broadened my horizons and equipped me with the necessary tools needed to excel in the world of data science.</p><p>This is not to say everything was smooth sailing. Along this journey, I encountered my fair share of challenges and encountered some hurdles. Was it when I was finding it difficult to install anaconda at the start and python modules? Or trying to find my way around <em>jupyter notebook </em>or even the times when I just encountered bugs that cause me much irritation that will at times tempt me to fling my laptop away. There were even times I had to first make a long prayer before I run a line of code that I shouldn’t encounter any form of errors or bugs. Lol, crazy times. Well, each of these hurdles just turned out to be a lesson in disguise teaching me resilience, patience and the importance of perseverance in this evolving field of technology.</p><p>As I honed my skills, I started applying my knowledge to real-world projects. From building predictive models that could effectively gauge customer churn behavior to scraping data from the web to build projects and also scraping data via APIs, I dived into practical applications in data science. Over the course of a year, I accomplished a multitude of projects that hold immense value in real-world settings. One significant project involved creating predictive models capable of effectively gauging customer churn behavior. By analyzing various factors, these models could predict which customers were likely to leave a service or product, allowing for proactive strategies to retain them.</p><p>Another area I delved into was data scraping, both from websites and through APIs. This allowed me to collect data crucial for my projects, opening doors to a lot of possibilities for analysis and insights. On the application side, I successfully deployed a sentiment prediction model, trained on student feedback data (from my colleagues at the University of Ilorin). This model provided a valuable gauge of student perceptions and sentiments towards their educational experience. It was a practical demonstration of how data science can significantly impact educational experience. Also, I developed an application capable of analyzing WhatsApp chats. This project offered a unique perspective into the potential of data science in understanding communication patterns and extracting valuable insights from conversations. In addition, I also built a book recommender system app trained on Google Books where I obtained data via API calls. This system was capable of suggesting books to users based on their preferences.</p><p>In fact, the list of projects I completed within this short span is extensive, each offering great value in a real-world context. These projects aren’t just a reflection of my skills; they represent the potential data science holds to create meaningful applications that can positively influence various aspects of our lives.</p><p>The interesting part of my journey is that I was essentially self-taught, learning things on my own. I didn’t get to attend any bootcamps nor do I have a formal mentor or guide to show me the way, but I had unwavering support from my parents, which proved to be my strongest motivation. My parents were my constant source of encouragement. Their belief in my abilities and their unwavering motivation propelled me to explore and learn, even when I encountered challenges. They were always there, reminding me that I could achieve anything I set my mind to, and this belief in me gave me the confidence to continue my data journey.</p><p>Their guidance was not rooted in complex technical knowledge, but rather in the simple but powerful act of believing in my potential. Their support was a driving force that kept me going, and I learned that the right encouragement could make a world of difference, even in a self-taught journey like mine. As I continued to learn, I realized that mentorship and guidance can come in many forms, and the belief and motivation of loved ones can be just as influential as formal guidance from experts.</p><p>During this journey, I’ve had the incredible opportunity to connect with individuals from around the world who share a passion for data science. This experience has broadened my horizons, opening my mind to the possibilities beyond my immediate surroundings. The connections I’ve made have been more than just networking; they’ve been windows into a global community of data enthusiasts. I’ve received numerous calls and messages from folks who recognized my potential and were eager to collaborate on various projects. It’s been a testament to the power of a global, interconnected world and the opportunities it can bring.</p><p>Working on projects for different people has been a fulfilling aspect of my growth. I’ve taken on various assignments and delivered with an excellent success rate, which not only added to my knowledge but also brought in a valuable source of income. Despite the impressive growth I’ve experienced, I remain committed to pushing myself even further. <em>The passion I have for data science has transformed it into more than just a career — it’s become a hobby. When you’re passionate about something, it’s not work; it’s a calling.</em> This passion has driven me to be consistently gritty, determined, and focused on my goals and I’m excited to see where it will lead me next.</p><p>My biggest vision in this career path is to leverage my skills to create a positive impact on humanity. I’m driven by the desire to use data science to enhance lives and contribute to making the world a better and safer place for all. Looking ahead, I have exciting plans that I want to take on. I aim to delve deeper into the fascinating world of Generative AI and focus on building large language model applications. This field holds incredible potential for pushing the boundaries of what’s possible in artificial intelligence, and I’m eager to be a part of this journey.</p><p>Moreover, I aspire to be more than just a solo explorer. I want to actively engage with communities worldwide and strengthen my physical presence in the global network of data science practitioners. Building strong connections and collaborating with like-minded individuals is a vital part of my vision. One of my core objectives is to assist newbies in seamlessly transitioning into the field of data science. I believe that by sharing my knowledge and experiences, I can help others navigate the complexities of this exciting domain with greater ease.</p><p>As I reflect on this first year in data science, the wise words of pioneering statistician, John Tukey ring true — “<em>An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem.</em>”</p><p>My sojourn has shown me the importance of framing the right questions, not just pursuing technical perfection. I’m humbled by how much I’ve grown, and energized by how much there is still to learn on this journey. The road ahead promises to be challenging but full of purpose as I continue seeking out the human stories hidden within the data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a490edf4815" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-unleased/navigating-the-data-seas-my-year-long-voyage-into-the-world-of-data-science-3a490edf4815">Navigating the Data Seas: My Year-Long Voyage into the World of Data Science</a> was originally published in <a href="https://medium.com/ai-unleased">AI Unleased</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying NLP: A Beginner’s Guide to Natural Language Processing Basics and Techniques]]></title>
            <link>https://pub.towardsai.net/demystifying-nlp-a-beginners-guide-to-natural-language-processing-basics-and-techniques-eb233d2f449?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb233d2f449</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 18:02:01 GMT</pubDate>
            <atom:updated>2023-09-22T18:02:01.227Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFpyTHH9Dw48WNGS" /><figcaption>Photo by <a href="https://unsplash.com/@jrkorpa?utm_source=medium&amp;utm_medium=referral">Jr Korpa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Natural Language Processing (NLP) is an exciting field in Machine Learning that empowers machines to comprehend, interpret, understand and generate human language. It is basically the technology that allows computers to read, understand, and respond to human language — be it in the form of text or speech. It’s like teaching machines to speak our language and even generate creative, coherent, and contextually relevant responses. In this article, we will delve into the basic terms, terminologies and fundamentals of the technology that underpins ChatGPT and the plethora of generative AI systems prevalent today.</p><p>Key Terms Used Include:</p><h3><strong>Document</strong></h3><p>A piece of text, which can range from a single sentence to an entire book.</p><h3>Corpus</h3><p>A collection of documents used for analysis or training in NLP.</p><pre>corpus = [&quot;This is the first document.&quot;, &quot;Another document here.&quot;, &quot;And a third one.&quot;]</pre><h3>Vocabulary</h3><p>The set of all unique words in a corpus.</p><pre>from collections import Counter<br><br>corpus = [&quot;This is the first document.&quot;, &quot;Another document here.&quot;, &quot;And a third one.&quot;]<br>words = &#39; &#39;.join(corpus).lower().split()<br>vocabulary = set(words)<br>print(&quot;Vocabulary:&quot;, vocabulary)</pre><pre>Vocabulary: {&#39;document.&#39;, &#39;document&#39;, &#39;first&#39;, &#39;a&#39;, &#39;another&#39;, &#39;and&#39;, &#39;third&#39;, &#39;this&#39;, &#39;here.&#39;, &#39;is&#39;, &#39;the&#39;, &#39;one.&#39;}</pre><h3>Segmentation</h3><p>The process of breaking a text into meaningful segments, like sentences or paragraphs.</p><h3>Tokenization</h3><p>Breaking text into smaller units, such as words or subwords (tokens).</p><pre>from nltk.tokenize import word_tokenize<br><br>text = &quot;Tokenization is an important step in NLP.&quot;<br>tokens = word_tokenize(text)<br>print(&quot;Tokens:&quot;, tokens)</pre><pre>Tokens: [&#39;Tokenization&#39;, &#39;is&#39;, &#39;an&#39;, &#39;important&#39;, &#39;step&#39;, &#39;in&#39;, &#39;NLP&#39;, &#39;.&#39;]</pre><h3>Stopwords</h3><p>Commonly used words (e.g., ‘and’, ‘the’, ‘is’) that are usually removed in NLP analysis.</p><pre>from nltk.corpus import stopwords<br><br>stop_words = set(stopwords.words(&#39;english&#39;))<br>print(&quot;Stopwords:&quot;, stop_words)</pre><pre>Stopwords: {&#39;he&#39;, &#39;once&#39;, &#39;m&#39;, &#39;this&#39;, &quot;that&#39;ll&quot;, &#39;their&#39;, &#39;the&#39;, &quot;she&#39;s&quot;, &quot;you&#39;ve&quot;, &quot;hadn&#39;t&quot;, &#39;mightn&#39;, &#39;down&#39;, &#39;off&#39;, &#39;now&#39;, &quot;shouldn&#39;t&quot;, &#39;t&#39;, &quot;isn&#39;t&quot;, &#39;that&#39;, &quot;didn&#39;t&quot;, &#39;wasn&#39;, &#39;do&#39;, &#39;shan&#39;, &#39;yourselves&#39;, &#39;a&#39;, &#39;ve&#39;, &#39;themselves&#39;, &#39;out&#39;, &quot;don&#39;t&quot;, &#39;hasn&#39;, &#39;than&#39;, &#39;couldn&#39;, &quot;mightn&#39;t&quot;, &quot;you&#39;d&quot;, &#39;further&#39;, &#39;has&#39;, &#39;having&#39;, &quot;wouldn&#39;t&quot;, &#39;here&#39;, &#39;him&#39;, &#39;from&#39;, &#39;where&#39;, &#39;your&#39;, &#39;these&#39;, &#39;my&#39;, &#39;up&#39;, &#39;so&#39;, &#39;have&#39;, &#39;hadn&#39;, &quot;weren&#39;t&quot;, &#39;to&#39;, &#39;hers&#39;, &#39;doesn&#39;, &#39;below&#39;, &quot;needn&#39;t&quot;, &#39;re&#39;, &quot;you&#39;re&quot;, &#39;when&#39;, &#39;whom&#39;, &#39;all&#39;, &#39;is&#39;, &#39;should&#39;, &#39;not&#39;, &#39;were&#39;, &#39;you&#39;, &#39;until&#39;, &#39;doing&#39;, &quot;mustn&#39;t&quot;, &quot;it&#39;s&quot;, &#39;because&#39;, &#39;y&#39;, &#39;her&#39;, &#39;both&#39;, &#39;o&#39;, &#39;weren&#39;, &#39;other&#39;, &#39;on&#39;, &#39;his&#39;, &quot;shan&#39;t&quot;, &#39;why&#39;, &#39;through&#39;, &#39;between&#39;, &#39;am&#39;, &#39;be&#39;, &#39;she&#39;, &#39;more&#39;, &#39;herself&#39;, &quot;couldn&#39;t&quot;, &quot;doesn&#39;t&quot;, &quot;aren&#39;t&quot;, &#39;which&#39;, &#39;won&#39;, &#39;of&#39;, &#39;don&#39;, &#39;some&#39;, &#39;was&#39;, &#39;under&#39;, &#39;few&#39;, &#39;needn&#39;, &#39;ours&#39;, &#39;theirs&#39;, &#39;it&#39;, &#39;aren&#39;, &#39;and&#39;, &#39;own&#39;, &#39;isn&#39;, &#39;about&#39;, &#39;such&#39;, &#39;again&#39;, &#39;its&#39;, &#39;any&#39;, &#39;by&#39;, &#39;mustn&#39;, &#39;had&#39;, &#39;s&#39;, &#39;can&#39;, &#39;haven&#39;, &#39;before&#39;, &#39;over&#39;, &#39;those&#39;, &#39;during&#39;, &#39;while&#39;, &quot;wasn&#39;t&quot;, &#39;we&#39;, &#39;each&#39;, &#39;being&#39;, &#39;then&#39;, &#39;against&#39;, &#39;me&#39;, &quot;should&#39;ve&quot;, &#39;d&#39;, &#39;after&#39;, &#39;didn&#39;, &#39;as&#39;, &#39;ll&#39;, &quot;haven&#39;t&quot;, &#39;wouldn&#39;, &#39;there&#39;, &#39;an&#39;, &#39;been&#39;, &#39;ourselves&#39;, &quot;you&#39;ll&quot;, &#39;what&#39;, &#39;if&#39;, &#39;in&#39;, &#39;shouldn&#39;, &#39;for&#39;, &#39;with&#39;, &#39;just&#39;, &#39;how&#39;, &#39;who&#39;, &#39;them&#39;, &#39;are&#39;, &#39;but&#39;, &#39;no&#39;, &#39;ain&#39;, &#39;very&#39;, &#39;ma&#39;, &#39;same&#39;, &#39;above&#39;, &#39;into&#39;, &#39;himself&#39;, &#39;did&#39;, &#39;myself&#39;, &#39;most&#39;, &#39;only&#39;, &#39;will&#39;, &#39;our&#39;, &#39;they&#39;, &#39;nor&#39;, &#39;yours&#39;, &#39;at&#39;, &#39;too&#39;, &quot;hasn&#39;t&quot;, &#39;itself&#39;, &#39;or&#39;, &quot;won&#39;t&quot;, &#39;does&#39;, &#39;i&#39;, &#39;yourself&#39;}</pre><h3>Stemming</h3><p>Reducing words to their base or root form (stem).</p><pre>from nltk.stem import PorterStemmer<br><br>stemmer = PorterStemmer()<br>word = &quot;running&quot;<br>stemmed_word = stemmer.stem(word)<br>print(&quot;Stemmed word:&quot;, stemmed_word)</pre><pre><br>Stemmed word: run</pre><h3>Lemmatization</h3><p>Reducing words to their base form (lemma) considering the context.</p><pre>from nltk.stem import WordNetLemmatizer<br><br>lemmatizer = WordNetLemmatizer()<br>word = &quot;Raqib loves coding and dancing.&quot;<br>lemmatized_word = lemmatizer.lemmatize(word)<br>print(&quot;Lemmatized word:&quot;, lemmatized_word)</pre><h3>POS Tagging (Part-of-Speech Tagging)</h3><p>Assigning a part-of-speech (e.g., noun, verb, adjective) to each word in a sentence.</p><pre>from nltk import pos_tag<br>from nltk.tokenize import word_tokenize<br><br>sentence = &quot;The cat is on the mat&quot;<br>tokens = word_tokenize(sentence)<br>pos_tags = pos_tag(tokens)<br>print(&quot;POS Tags:&quot;, pos_tags)</pre><pre>POS Tags: [(&#39;The&#39;, &#39;DT&#39;), (&#39;cat&#39;, &#39;NN&#39;), (&#39;is&#39;, &#39;VBZ&#39;), (&#39;on&#39;, &#39;IN&#39;), (&#39;the&#39;, &#39;DT&#39;), (&#39;mat&#39;, &#39;NN&#39;)]</pre><ul><li>(&#39;The&#39;, &#39;DT&#39;): &#39;The&#39; is a determiner (DT).</li><li>(&#39;cat&#39;, &#39;NN&#39;): &#39;cat&#39; is a noun (NN).</li><li>(&#39;is&#39;, &#39;VBZ&#39;): &#39;is&#39; is a verb, third person singular present (VBZ).</li><li>(&#39;on&#39;, &#39;IN&#39;): &#39;on&#39; is a preposition or subordinating conjunction (IN).</li><li>(&#39;the&#39;, &#39;DT&#39;): &#39;the&#39; is a determiner (DT).</li><li>(&#39;mat&#39;, &#39;NN&#39;): &#39;mat&#39; is a noun (NN).</li></ul><h3>Bag of Words (BoW)</h3><p>A representation of text that counts the frequency of words in a document, disregarding grammar and word order.</p><pre>from sklearn.feature_extraction.text import CountVectorizer<br><br>corpus = [&quot;This is the first document.&quot;, &quot;Another document here.&quot;, &quot;And a third one.&quot;]<br>vectorizer = CountVectorizer()<br>bow_representation = vectorizer.fit_transform(corpus)<br>print(&quot;Bag of Words representation:\n&quot;, bow_representation.toarray())<br>print(&quot;Vocabulary:&quot;, vectorizer.get_feature_names())</pre><h3>TF-IDF (Term Frequency-Inverse Document Frequency)</h3><p>A technique to weigh the importance of words in a document relative to a corpus based on frequency.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br><br>corpus = [&quot;This is the first document.&quot;, &quot;Another document here.&quot;, &quot;And a third one.&quot;]<br>vectorizer = TfidfVectorizer()<br>tfidf_representation = vectorizer.fit_transform(corpus)<br>print(&quot;TF-IDF representation:\n&quot;, tfidf_representation.toarray())<br>print(&quot;Vocabulary:&quot;, vectorizer.get_feature_names())</pre><pre>TF-IDF representation:<br> [[0.         0.         0.35543247 0.46735098 0.         0.46735098<br>  0.         0.46735098 0.         0.46735098]<br> [0.         0.62276601 0.4736296  0.         0.62276601 0.<br>  0.         0.         0.         0.        ]<br> [0.57735027 0.         0.         0.         0.         0.<br>  0.57735027 0.         0.57735027 0.        ]]<br>Vocabulary: [&#39;and&#39;, &#39;another&#39;, &#39;document&#39;, &#39;first&#39;, &#39;here&#39;, &#39;is&#39;, &#39;one&#39;, &#39;the&#39;, &#39;third&#39;, &#39;this&#39;]</pre><blockquote><strong>Text Preprocessing Steps</strong></blockquote><p>Now, we would apply the basic NLP techniques to preprocess a text string.</p><p><em>Convert text to lowercase.</em></p><pre>sample_text = &quot;NLP is an exciting field! It enables machines to comprehend, interpret, and generate human language. Learn more at https://raqibcodes.com. #NLP #MachineLearning @NLPCommunity 2023303&quot;<br><br># Convert text to lowercase<br>def convert_to_lowercase(text):<br>    return text.lower()<br><br># Apply the lowercase conversion<br>lowercased_text = convert_to_lowercase(sample_text)<br>print(&quot;Lowercased Text:&quot;, lowercased_text)</pre><pre>Lowercased Text: nlp is an exciting field! it enables machines to comprehend, interpret, and generate human language. learn more at https://raqibcodes.com. #nlp #machinelearning @nlpcommunity 2023303</pre><p><em>Remove special characters.</em></p><pre>def remove_special_characters(text):<br>    # Remove URLs, hashtags, mentions, and special characters<br>    text = re.sub(r&quot;http\S+|www\S+|@\w+|#\w+&quot;, &quot;&quot;, text)<br>    text = re.sub(r&quot;[^\w\s.]&quot;, &quot;&quot;, text)<br>    return text<br><br># Apply removing special characters<br>text_no_special_chars = remove_special_characters(lowercased_text)<br>print(&quot;Text without special characters:&quot;, text_no_special_chars)</pre><pre>Text without special characters: nlp is an exciting field it enables machines to comprehend interpret and generate human language. learn more at     2023303</pre><p><em>Remove numbers and digits.</em></p><pre>def remove_numbers(text):<br>    # Remove numbers/digits<br>    text = re.sub(r&#39;\d+(\.\d+)?&#39;, &#39;&#39;, text)<br>    return text<br><br># Apply removing numbers/digits<br>text_no_numbers = remove_numbers(text_no_special_chars)<br>print(&quot;Text without numbers/digits:&quot;, text_no_numbers)</pre><pre>Text without numbers/digits: nlp is an exciting field it enables machines to comprehend interpret and generate human language. learn more at </pre><p><em>Tokenize text.</em></p><pre>from nltk.tokenize import word_tokenize<br><br>def tokenize_text(text):<br>    # Tokenize the text<br>    tokens = word_tokenize(text)<br>    return tokens<br><br># Apply tokenization<br>tokens = tokenize_text(text_no_numbers)<br>print(&quot;Tokens:&quot;, tokens)</pre><pre>Tokens: [&#39;nlp&#39;, &#39;is&#39;, &#39;an&#39;, &#39;exciting&#39;, &#39;field&#39;, &#39;it&#39;, &#39;enables&#39;, &#39;machines&#39;, &#39;to&#39;, &#39;comprehend&#39;, &#39;interpret&#39;, &#39;and&#39;, &#39;generate&#39;, &#39;human&#39;, &#39;language&#39;, &#39;.&#39;, &#39;learn&#39;, &#39;more&#39;, &#39;at&#39;]</pre><p><em>Remove stopwords.</em></p><pre>from nltk.corpus import stopwords<br><br>def remove_stopwords(tokens):<br>    # Remove stop words<br>    stop_words = set(stopwords.words(&#39;english&#39;))<br>    tokens = [token for token in tokens if token not in stop_words]<br>    return tokens<br><br># Apply removing stop words<br>tokens_no_stopwords = remove_stopwords(tokens)<br>print(&quot;Tokens without stop words:&quot;, tokens_no_stopwords)</pre><pre>Tokens without stop words: [&#39;nlp&#39;, &#39;exciting&#39;, &#39;field&#39;, &#39;enables&#39;, &#39;machines&#39;, &#39;comprehend&#39;, &#39;interpret&#39;, &#39;generate&#39;, &#39;human&#39;, &#39;language&#39;, &#39;.&#39;, &#39;learn&#39;]</pre><p><em>Lemmatize words.</em></p><pre>from nltk.stem import WordNetLemmatizer<br><br>def lemmatize_words(tokens):<br>    # Lemmatize the words<br>    lemmatizer = WordNetLemmatizer()<br>    tokens = [lemmatizer.lemmatize(token) for token in tokens]<br>    return tokens<br><br># Apply lemmatization<br>lemmatized_tokens = lemmatize_words(tokens_no_stopwords)<br>print(&quot;Lemmatized Tokens:&quot;, lemmatized_tokens)</pre><pre>Lemmatized Tokens: [&#39;nlp&#39;, &#39;exciting&#39;, &#39;field&#39;, &#39;enables&#39;, &#39;machine&#39;, &#39;comprehend&#39;, &#39;interpret&#39;, &#39;generate&#39;, &#39;human&#39;, &#39;language&#39;, &#39;.&#39;, &#39;learn&#39;]</pre><p><em>Apply Stemming.</em></p><pre>from nltk.stem import PorterStemmer<br><br>def apply_stemming(tokens):<br>    # Apply stemming<br>    stemmer = PorterStemmer()<br>    stemmed_tokens = [stemmer.stem(token) for token in tokens]<br>    return stemmed_tokens<br><br># Apply stemming<br>stemmed_tokens = apply_stemming(lemmatized_tokens)<br>print(&quot;Stemmed Tokens:&quot;, stemmed_tokens)</pre><pre>Stemmed Tokens: [&#39;nlp&#39;, &#39;excit&#39;, &#39;field&#39;, &#39;enabl&#39;, &#39;machin&#39;, &#39;comprehend&#39;, &#39;interpret&#39;, &#39;gener&#39;, &#39;human&#39;, &#39;languag&#39;, &#39;.&#39;, &#39;learn&#39;]</pre><p><em>Join tokens back into a single string.</em></p><pre>def join_tokens(tokens):<br>    # Join tokens back into a single string<br>    return &#39; &#39;.join(tokens)<br><br># Apply joining tokens into a single string<br>preprocessed_text = join_tokens(lemmatized_tokens)<br>print(&quot;Preprocessed Text:&quot;, preprocessed_text)</pre><pre>Preprocessed Text: nlp exciting field enables machine comprehend interpret generate human language . learn</pre><p><em>Apply POS tagging.</em></p><pre>from nltk import pos_tag<br><br>def pos_tagging(tokens):<br>    # Perform POS tagging<br>    pos_tags = pos_tag(tokens)<br>    return pos_tags<br><br># Apply POS tagging<br>pos_tags = pos_tagging(lemmatized_tokens)<br>print(&quot;POS Tags:&quot;, pos_tags)</pre><pre>POS Tags: [(&#39;nlp&#39;, &#39;RB&#39;), (&#39;exciting&#39;, &#39;JJ&#39;), (&#39;field&#39;, &#39;NN&#39;), (&#39;enables&#39;, &#39;NNS&#39;), (&#39;machine&#39;, &#39;NN&#39;), (&#39;comprehend&#39;, &#39;VBP&#39;), (&#39;interpret&#39;, &#39;JJ&#39;), (&#39;generate&#39;, &#39;NN&#39;), (&#39;human&#39;, &#39;JJ&#39;), (&#39;language&#39;, &#39;NN&#39;), (&#39;.&#39;, &#39;.&#39;), (&#39;learn&#39;, &#39;VB&#39;)]</pre><p>Meaning of tags</p><ul><li>(&#39;nlp&#39;, &#39;RB&#39;): &#39;nlp&#39; is tagged as an adverb (RB).</li><li>(&#39;exciting&#39;, &#39;JJ&#39;): &#39;exciting&#39; is an adjective (JJ).</li><li>(&#39;field&#39;, &#39;NN&#39;): &#39;field&#39; is a noun (NN).</li><li>(&#39;enables&#39;, &#39;NNS&#39;): &#39;enables&#39; is a plural noun (NNS).</li><li>(&#39;machine&#39;, &#39;NN&#39;): &#39;machine&#39; is a noun (NN).</li><li>(&#39;comprehend&#39;, &#39;VBP&#39;): &#39;comprehend&#39; is a verb in the base form (VBP).</li><li>(&#39;interpret&#39;, &#39;JJ&#39;): &#39;interpret&#39; is an adjective (JJ).</li><li>(&#39;generate&#39;, &#39;NN&#39;): &#39;generate&#39; is a noun (NN).</li><li>(&#39;human&#39;, &#39;JJ&#39;): &#39;human&#39; is an adjective (JJ).</li><li>(&#39;language&#39;, &#39;NN&#39;): &#39;language&#39; is a noun (NN).</li><li>(&#39;.&#39;, &#39;.&#39;): &#39;.&#39; denotes a punctuation mark (period).</li><li>(&#39;learn&#39;, &#39;VB&#39;): &#39;learn&#39; is a verb in the base form (VB).</li></ul><p><em>Apply Bag of Words Representation.</em></p><pre>from sklearn.feature_extraction.text import CountVectorizer<br><br>def bag_of_words_representation(text):<br>    # Initialize CountVectorizer<br>    vectorizer = CountVectorizer()<br>    # Transform the text into a Bag of Words representation<br>    bow_representation = vectorizer.fit_transform([text])<br>    return bow_representation, vectorizer<br><br># Apply Bag of Words representation<br>bow_representation, vectorizer = bag_of_words_representation(preprocessed_text)<br>print(&quot;Bag of Words representation:&quot;)<br>print(bow_representation.toarray())<br>print(&quot;Vocabulary:&quot;, vectorizer.get_feature_names())</pre><pre>Bag of Words representation:<br>[[1 1 1 1 1 1 1 1 1 1 1]]<br>Vocabulary: [&#39;comprehend&#39;, &#39;enables&#39;, &#39;exciting&#39;, &#39;field&#39;, &#39;generate&#39;, &#39;human&#39;, &#39;interpret&#39;, &#39;language&#39;, &#39;learn&#39;, &#39;machine&#39;, &#39;nlp&#39;]</pre><p><em>Apply TF-IDF representation.</em></p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br><br>def tfidf_representation(text):<br>    # Initialize TfidfVectorizer<br>    vectorizer = TfidfVectorizer()<br>    # Transform the text into a TF-IDF representation<br>    tfidf_representation = vectorizer.fit_transform([text])<br>    return tfidf_representation, vectorizer<br><br># Apply TF-IDF representation<br>tfidf_representation, tfidf_vectorizer = tfidf_representation(preprocessed_text)<br>print(&quot;\nTF-IDF representation:&quot;)<br>print(tfidf_representation.toarray())<br>print(&quot;Vocabulary:&quot;, tfidf_vectorizer.get_feature_names())</pre><pre>TF-IDF representation:<br>[[0.30151134 0.30151134 0.30151134 0.30151134 0.30151134 0.30151134<br>  0.30151134 0.30151134 0.30151134 0.30151134 0.30151134]]<br>Vocabulary: [&#39;comprehend&#39;, &#39;enables&#39;, &#39;exciting&#39;, &#39;field&#39;, &#39;generate&#39;, &#39;human&#39;, &#39;interpret&#39;, &#39;language&#39;, &#39;learn&#39;, &#39;machine&#39;, &#39;nlp&#39;]</pre><p>Natural Language Processing (NLP) is the bridge between human language and machines. In this article, we’ve uncovered fundamental terms like ‘corpus,’ ‘vocabulary,’ and key techniques including ‘tokenization,’ ‘lemmatization,’ and ‘POS tagging.’ These are the building blocks for advanced NLP applications, pushing AI towards more human-like interactions.</p><blockquote>Thanks for reading🤓. You can check out my <a href="https://github.com/Abdulraqib20/Sentiment-Analysis-with-Student-Feedback">GitHub repo</a> where you can review an NLP project I worked on where I applied all of the above techniques and more advanced ones. Cheers!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb233d2f449" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/demystifying-nlp-a-beginners-guide-to-natural-language-processing-basics-and-techniques-eb233d2f449">Demystifying NLP: A Beginner’s Guide to Natural Language Processing Basics and Techniques</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Customer Insights: Unsupervised Learning for Dynamic Segmentation]]></title>
            <link>https://medium.com/@abdulraqibshakir03/unveiling-customer-insights-unsupervised-learning-for-dynamic-segmentation-5ec1fd66f1a?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ec1fd66f1a</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 00:25:48 GMT</pubDate>
            <atom:updated>2023-06-27T22:39:21.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SyyHXwNs9yT6WhoE" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=medium&amp;utm_medium=referral">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Customer Personality Analysis is a powerful tool that helps businesses gain a deep understanding of their ideal customers. By using techniques such as unsupervised learning, companies can uncover valuable insights about customer needs, behaviors, and concerns.</p><p>This analysis enables businesses to direct their products and services to different customer segments, rather than using a generic approach. For example, instead of marketing a new product to every customer in their database, a company can identify the most receptive customer segment and focus their efforts on that specific group.</p><p>In this article, we will explore how unsupervised learning can be used for customer segmentation. We’ll cover the process of analyzing customer data, extracting insights, and applying them to improve business strategies. We will then perform clustering to summarize customer segments.</p><p>The dataset used for this project can be found <a href="https://www.kaggle.com/datasets/imakash3011/customer-personality-analysis">here</a>.</p><h3><strong>Importing libraries and packages</strong></h3><pre># data analysis libraries<br>import pandas as pd<br>import numpy as np<br><br># data visualization libraries<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>sns.set(style=&#39;white&#39;)<br>import plotly.express as px<br><br># machine learning<br>from sklearn.preprocessing import StandardScaler, LabelEncoder<br>from sklearn.cluster import AgglomerativeClustering<br>from sklearn.metrics import silhouette_score, calinski_harabasz_score<br>from sklearn.cluster import KMeans<br>from sklearn.decomposition import PCA<br><br># remove warnings<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h3>Loading the dataset and cleaning it</h3><pre># read csv file into notebook<br>df = pd.read_csv(&#39;marketing_campaign.csv&#39;, sep=&#39;\t&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58YyBD-pl7KXQ6m2PXlMVA.jpeg" /></figure><pre># concise summary of a DataFrame.<br>df.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 2240 entries, 0 to 2239<br>Data columns (total 29 columns):<br> #   Column               Non-Null Count  Dtype  <br>---  ------               --------------  -----  <br> 0   ID                   2240 non-null   int64  <br> 1   Year_Birth           2240 non-null   int64  <br> 2   Education            2240 non-null   object <br> 3   Marital_Status       2240 non-null   object <br> 4   Income               2216 non-null   float64<br> 5   Kidhome              2240 non-null   int64  <br> 6   Teenhome             2240 non-null   int64  <br> 7   Dt_Customer          2240 non-null   object <br> 8   Recency              2240 non-null   int64  <br> 9   MntWines             2240 non-null   int64  <br> 10  MntFruits            2240 non-null   int64  <br> 11  MntMeatProducts      2240 non-null   int64  <br> 12  MntFishProducts      2240 non-null   int64  <br> 13  MntSweetProducts     2240 non-null   int64  <br> 14  MntGoldProds         2240 non-null   int64  <br> 15  NumDealsPurchases    2240 non-null   int64  <br> 16  NumWebPurchases      2240 non-null   int64  <br> 17  NumCatalogPurchases  2240 non-null   int64  <br> 18  NumStorePurchases    2240 non-null   int64  <br> 19  NumWebVisitsMonth    2240 non-null   int64  <br> 20  AcceptedCmp3         2240 non-null   int64  <br> 21  AcceptedCmp4         2240 non-null   int64  <br> 22  AcceptedCmp5         2240 non-null   int64  <br> 23  AcceptedCmp1         2240 non-null   int64  <br> 24  AcceptedCmp2         2240 non-null   int64  <br> 25  Complain             2240 non-null   int64  <br> 26  Z_CostContact        2240 non-null   int64  <br> 27  Z_Revenue            2240 non-null   int64  <br> 28  Response             2240 non-null   int64  <br>dtypes: float64(1), int64(25), object(3)<br>memory usage: 507.6+ KB</pre><pre># checking for nulls<br>df.isnull().sum()</pre><pre>ID                      0<br>Year_Birth              0<br>Education               0<br>Marital_Status          0<br>Income                 24<br>Kidhome                 0<br>Teenhome                0<br>Dt_Customer             0<br>Recency                 0<br>MntWines                0<br>MntFruits               0<br>MntMeatProducts         0<br>MntFishProducts         0<br>MntSweetProducts        0<br>MntGoldProds            0<br>NumDealsPurchases       0<br>NumWebPurchases         0<br>NumCatalogPurchases     0<br>NumStorePurchases       0<br>NumWebVisitsMonth       0<br>AcceptedCmp3            0<br>AcceptedCmp4            0<br>AcceptedCmp5            0<br>AcceptedCmp1            0<br>AcceptedCmp2            0<br>Complain                0<br>Z_CostContact           0<br>Z_Revenue               0<br>Response                0<br>dtype: int64</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*gXQumgh7UXqSWHDhx3EtnA.jpeg" /><figcaption>Removing null values (image by Author)</figcaption></figure><pre># checking for categorical features<br>cat_cols = df.select_dtypes(include=&#39;object&#39;).columns<br>for cat in cat_cols:<br>    print(f&#39;\nValue counts for: {cat}\n\n {df[cat].value_counts()}&#39;)<br>    print(&#39;-&#39; * 100)</pre><pre>Value counts for: Education<br><br> Graduation    1116<br>PhD            481<br>Master         365<br>2n Cycle       200<br>Basic           54<br>Name: Education, dtype: int64<br>----------------------------------------------------------------------------------------------------<br><br>Value counts for: Marital_Status<br><br> Married     857<br>Together    573<br>Single      471<br>Divorced    232<br>Widow        76<br>Alone         3<br>Absurd        2<br>YOLO          2<br>Name: Marital_Status, dtype: int64<br>----------------------------------------------------------------------------------------------------<br><br>Value counts for: Dt_Customer<br><br> 31-08-2012    12<br>12-09-2012    11<br>14-02-2013    11<br>12-05-2014    11<br>20-08-2013    10<br>              ..<br>05-08-2012     1<br>18-11-2012     1<br>09-05-2014     1<br>26-06-2013     1<br>09-01-2014     1<br>Name: Dt_Customer, Length: 662, dtype: int64<br>----------------------------------------------------------------------------------------------------</pre><h3>Feature Engineering</h3><p>Here, we would engineer new columns from the previously existing ones to enhance the performance of the model.</p><pre># customer age: since the customer registration with the company was between 2012 and 2014, we assume that the data was collected in January 2015 for simplicity.<br>df[&#39;Age&#39;] = 2015 - df[&#39;Year_Birth&#39;]<br><br># total spending<br>spending_cols = [&#39;MntWines&#39;, &#39;MntFruits&#39;, &#39;MntMeatProducts&#39;, &#39;MntFishProducts&#39;, &#39;MntSweetProducts&#39;, &#39;MntGoldProds&#39;]<br>df[&#39;Total_Spending&#39;] = df[spending_cols].sum(axis=1)<br><br># total number of dependents in each customer&#39;s household<br># df[&#39;Family_Size&#39;] = df[&#39;Kidhome&#39;] + df[&#39;Teenhome&#39;] + 1 # marital status may be included.<br>df[&#39;No_of_Dependents&#39;] = df[&#39;Kidhome&#39;] + df[&#39;Teenhome&#39;]<br><br># total number of campaigns accepted by each customer<br>campaign_cols = [&#39;AcceptedCmp1&#39;, &#39;AcceptedCmp2&#39;, &#39;AcceptedCmp3&#39;, &#39;AcceptedCmp4&#39;, &#39;AcceptedCmp5&#39;]<br>df[&#39;Total_Acceptance&#39;] = df[campaign_cols].sum(axis=1)<br><br># number of months since each customer&#39;s enrollment with the company until the current date<br>df[&#39;Dt_Customer&#39;] = pd.to_datetime(df[&#39;Dt_Customer&#39;])<br>df[&#39;Months_of_Enrollment&#39;] = ((pd.Timestamp(&#39;2015-01-01&#39;) - df[&#39;Dt_Customer&#39;]) / np.timedelta64(1, &#39;M&#39;)).astype(int)<br><br># most frequent purchasing channel<br>purchase_cols = [&#39;NumWebPurchases&#39;, &#39;NumCatalogPurchases&#39;, &#39;NumStorePurchases&#39;]<br>df[&#39;Purchasing_Channel&#39;] = df[purchase_cols].idxmax(axis=1).str.replace(&#39;Num&#39;, &#39;&#39;)<br><br># total purchases<br>total_purchases_col = [&#39;NumWebPurchases&#39;, &#39;NumCatalogPurchases&#39;, &#39;NumStorePurchases&#39;, &#39;NumDealsPurchases&#39;]<br>df[&#39;Total_Purchases&#39;] = df[total_purchases_col].sum(axis=1)<br><br># website activity<br>website_cols = [&#39;NumWebPurchases&#39;, &#39;NumWebVisitsMonth&#39;]<br>df[&#39;Website_Activity&#39;] = df[website_cols].sum(axis=1)<br><br># total number of campaigns responded to by each customer<br>response_cols = [&#39;AcceptedCmp1&#39;, &#39;AcceptedCmp2&#39;, &#39;AcceptedCmp3&#39;, &#39;AcceptedCmp4&#39;, &#39;AcceptedCmp5&#39;, &#39;Response&#39;]<br>df[&#39;Campaign_Response&#39;] = df[response_cols].sum(axis=1)<br><br># marital status new<br>df[&#39;Marital_Status_New&#39;] = df[&#39;Marital_Status&#39;].replace({<br>    &#39;Married&#39;: &#39;Partner&#39;,<br>    &#39;Together&#39;: &#39;Partner&#39;,<br>    &#39;Single&#39;: &#39;No_Partner&#39;,<br>    &#39;Divorced&#39;: &#39;No_Partner&#39;,<br>    &#39;Widow&#39;: &#39;No_Partner&#39;,<br>    &#39;Alone&#39;: &#39;No_Partner&#39;,<br>    &#39;Absurd&#39;: &#39;No_Partner&#39;,<br>    &#39;YOLO&#39;: &#39;No_Partner&#39;<br>})<br><br># education level<br>df[&#39;Education_Level&#39;] = df[&#39;Education&#39;].replace({<br>    &#39;Graduation&#39;: &#39;Graduate&#39;,<br>    &#39;PhD&#39;: &#39;Post_Graduate&#39;,<br>    &#39;Master&#39;: &#39;Post_Graduate&#39;,<br>    &#39;2n Cycle&#39;: &#39;Undergraduate&#39;,<br>    &#39;Basic&#39;: &#39;Undergraduate&#39;<br>})<br><br># parental status<br>df[&#39;Parent_Status&#39;] = ((df[&#39;Kidhome&#39;] &gt; 0) | (df[&#39;Teenhome&#39;] &gt; 0)).astype(int)<br><br>df[&#39;Income_Ratio&#39;] = df[&#39;Total_Spending&#39;] / df[&#39;Income&#39;]<br><br># dropping redundant columns<br>df = df.drop([<br>    &#39;Year_Birth&#39;, &#39;MntWines&#39;, &#39;MntFruits&#39;, &#39;MntMeatProducts&#39;, &#39;MntFishProducts&#39;, &#39;MntSweetProducts&#39;, &#39;MntGoldProds&#39;,<br>    &#39;Kidhome&#39;, &#39;Teenhome&#39;, &#39;AcceptedCmp1&#39;, &#39;AcceptedCmp2&#39;, &#39;AcceptedCmp3&#39;, &#39;AcceptedCmp4&#39;, &#39;AcceptedCmp5&#39;, &#39;Dt_Customer&#39;,<br>    &#39;NumWebPurchases&#39;, &#39;NumCatalogPurchases&#39;, &#39;NumStorePurchases&#39;, &#39;Response&#39;, &#39;Marital_Status&#39;, &#39;Education&#39;,<br>    &#39;Z_CostContact&#39;, &#39;Z_Revenue&#39;, &#39;NumWebVisitsMonth&#39;, &#39;NumDealsPurchases&#39;<br>], axis=1)</pre><p>An explanation of the new columns engineered from the code above:</p><p>1. Age: The “Age” column represents the age of each customer. It is calculated by subtracting the “Year_Birth” column from the year 2015, assuming the data was collected in January 2015 for simplicity.</p><p>2. Total_Spending: The “Total_Spending” column represents the total amount spent by each customer on various product categories. It is obtained by summing up the spending columns, including “MntWines,” “MntFruits,” “MntMeatProducts,” “MntFishProducts,” “MntSweetProducts,” and “MntGoldProds.”</p><p>3. No_of_Dependents: The “No_of_Dependents” column represents the total number of dependents in each customer’s household. It is calculated by adding the “Kidhome” and “Teenhome” columns.</p><p>4. Total_Acceptance: The “Total_Acceptance” column represents the total number of marketing campaigns accepted by each customer. It is obtained by summing up the acceptance columns, including “AcceptedCmp1,” “AcceptedCmp2,” “AcceptedCmp3,” “AcceptedCmp4,” and “AcceptedCmp5.”</p><p>5. Months_of_Enrollment: The “Months_of_Enrollment” column represents the number of months since each customer enrolled with the company until the current date. It is calculated by subtracting the customer’s enrollment date (stored in the “Dt_Customer” column) from January 1, 2015, and converting the resulting time difference to the number of months.</p><p>6. Purchasing_Channel: The “Purchasing_Channel” column represents the most frequent purchasing channel used by each customer. It is determined by identifying the column with the highest value among “NumWebPurchases,” “NumCatalogPurchases,” and “NumStorePurchases” and removing the “Num” prefix.</p><p>7. Total_Purchases: The “Total_Purchases” column represents the total number of purchases made by each customer. It is obtained by summing up the columns related to different purchase types, including “NumWebPurchases,” “NumCatalogPurchases,” “NumStorePurchases,” and “NumDealsPurchases.”</p><p>8. Website_Activity: The “Website_Activity” column represents the overall activity of customers on the company’s website. It is calculated by summing up the columns “NumWebPurchases” and “NumWebVisitsMonth.”</p><p>9. Campaign_Response: The “Campaign_Response” column represents the total number of campaigns responded to by each customer. It is obtained by summing up the response columns, including “AcceptedCmp1,” “AcceptedCmp2,” “AcceptedCmp3,” “AcceptedCmp4,” “AcceptedCmp5,” and “Response.”</p><p>10. Marital_Status_New: The “Marital_Status_New” column represents a new categorization of marital status. It replaces the original marital status values with new labels, such as “Partner” for “Married” and “Together,” and “No_Partner” for other statuses like “Single,” “Divorced,” “Widow,” “Alone,” “Absurd,” and “YOLO.”</p><p>11. Education_Level: The “Education_Level” column represents a new categorization of education level. It replaces the original education values with simplified labels, such as “Graduate” for “Graduation,” “Post_Graduate” for “PhD” and “Master,” and “Undergraduate” for “2n Cycle” and “Basic.”</p><p>12. Parent_Status: The “Parent_Status” column represents the parental status of each customer. It is calculated by checking if a customer has at least one child at home (indicated by a value greater than 0 in the “Kidhome” column) or at least one teenager at home (indicated by a value greater than 0 in the “Teenhome” column).</p><p>13. Income_Ratio: The “Income_Ratio” column represents the ratio of total spending to income for each customer. It is calculated by dividing the “Total_Spending” column by the “Income” column.</p><p>Finally, we drop several redundant columns that are no longer needed for analysis, such as columns related to birth year, spending amounts, household information, campaign acceptance, customer enrollment date, website visits, response, marital status, education, and others. These columns are dropped using the <em>drop()</em> function with the specified column names and the `axis=1` parameter to indicate that the columns should be dropped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqyjFa0NFl4Q9WM15-_KMQ.jpeg" /><figcaption>random samples of the new data (image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ji_PP90Ba8OUxM3gd7wajg.jpeg" /><figcaption>Descriptive statistics (image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*X4faigZDAYPWlXG4Lf3bEQ.jpeg" /><figcaption>concise summary of the data (image by Author)</figcaption></figure><h3>Exploratory Data Analysis</h3><pre># correlation matrix<br>corr = df.corr()<br>plt.figure(figsize=[20, 10])<br>sns.heatmap(corr, annot=True, cmap=&#39;coolwarm&#39;, fmt=&quot;.2f&quot;, linewidths=0.5)<br><br>plt.title(&#39;Correlation Matrix&#39;, fontsize=16)<br>plt.xticks(fontsize=12)<br>plt.yticks(fontsize=12)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tOMqDjfD9hx_PsVecyUXQ.png" /><figcaption>correlation matrix (image by Author)</figcaption></figure><pre># income distribution<br>plt.figure(figsize=[7, 10])<br>sns.boxplot(y=df[&#39;Income&#39;], color=&#39;lightblue&#39;, linewidth=1.5)<br><br>age_stats = df[&#39;Income&#39;].describe()<br>q1 = age_stats[&#39;25%&#39;]<br>q3 = age_stats[&#39;75%&#39;]<br>median = age_stats[&#39;50%&#39;]<br>min_val = age_stats[&#39;min&#39;]<br>max_val = age_stats[&#39;max&#39;]<br>range_val = max_val - min_val<br><br>iqr = q3 - q1<br>outliers_income = df[(df[&#39;Income&#39;] &lt; q1 - 1.5 * iqr) | (df[&#39;Income&#39;] &gt; q3 + 1.5 * iqr)][&#39;Income&#39;]<br><br>plt.text(0.9, q1, f&#39;25th Percentile: {q1:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, median, f&#39;Median: {median:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, q3, f&#39;75th Percentile: {q3:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, min_val, f&#39;Minimum: {min_val:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, max_val, f&#39;Maximum: {max_val:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, min_val + (range_val / 2), f&#39;Range: {range_val:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br><br>lower_fence = q1 - 1.5 * iqr<br>plt.text(0.9, lower_fence, f&#39;Lower Fence: {lower_fence:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>upper_fence = q3 + 1.5 * iqr<br>plt.text(0.9, upper_fence, f&#39;Upper Fence: {upper_fence:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br><br>plt.title(&#39;Income Distribution&#39;, fontsize=16)<br>plt.xlabel(&#39;Income&#39;, fontsize=12)<br>plt.xticks(fontsize=10)<br>plt.yticks(fontsize=10)<br>plt.grid(axis=&#39;x&#39;, linestyle=&#39;--&#39;)<br>sns.despine()<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*HCxY_axoMpxd9IjFmUd8kA.png" /><figcaption>we can see there are outliers in the Income distribution (image by Author)</figcaption></figure><pre># Age distribution<br>plt.figure(figsize=[7, 10])<br>sns.boxplot(y=df[&#39;Age&#39;], color=&#39;lightblue&#39;, linewidth=1.5)<br><br>age_stats = df[&#39;Age&#39;].describe()<br>q1 = age_stats[&#39;25%&#39;]<br>q3 = age_stats[&#39;75%&#39;]<br>median = age_stats[&#39;50%&#39;]<br>min_val = age_stats[&#39;min&#39;]<br>max_val = age_stats[&#39;max&#39;]<br>range_val = max_val - min_val<br><br>iqr = q3 - q1<br>outliers_age = df[(df[&#39;Age&#39;] &lt; q1 - 1.5 * iqr) | (df[&#39;Age&#39;] &gt; q3 + 1.5 * iqr)][&#39;Age&#39;]<br><br>plt.text(0.9, q1, f&#39;25th Percentile: {q1:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, median, f&#39;Median: {median:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, q3, f&#39;75th Percentile: {q3:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, min_val, f&#39;Minimum: {min_val:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, max_val, f&#39;Maximum: {max_val:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>plt.text(0.9, min_val + (range_val / 2), f&#39;Range: {range_val:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br><br>lower_fence = q1 - 1.5 * iqr<br>plt.text(0.9, lower_fence, f&#39;Lower Fence: {lower_fence:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br>upper_fence = q3 + 1.5 * iqr<br>plt.text(0.9, upper_fence, f&#39;Upper Fence: {upper_fence:.2f}&#39;, va=&#39;center&#39;, ha=&#39;left&#39;, color=&#39;darkblue&#39;, fontweight=&#39;bold&#39;)<br><br>plt.title(&#39;Age Distribution&#39;, fontsize=16)<br>plt.xlabel(&#39;Age&#39;, fontsize=12)<br>plt.xticks(fontsize=10)<br>plt.yticks(fontsize=10)<br>plt.grid(axis=&#39;x&#39;, linestyle=&#39;--&#39;)<br>sns.despine()<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*XWrZo1BsDVIZwczC2rbEWw.png" /><figcaption>we can see there are outliers in the Age distribution (image by Author)</figcaption></figure><pre># Complain distribution<br>plt.figure(figsize=[10, 7])<br>counts = df[&#39;Complain&#39;].value_counts()<br>labels = [f&quot;{attendance}\n{count / len(df) * 100:.1f}%&quot; for attendance, count in counts.items()]<br>colors = [&#39;#8e0201&#39;, &#39;#e8cccc&#39;]<br><br>fig, ax = plt.subplots()<br>ax.pie(counts, labels=labels, startangle=50, counterclock=False, pctdistance=0.8, labeldistance=1.2, colors=colors)<br>centre_circle = plt.Circle((0,0),0.70,fc=&#39;white&#39;)<br>fig.gca().add_artist(centre_circle)<br>ax.set_title(&#39;Distribution of Complain&#39;, fontsize=16, loc=&#39;left&#39;, pad=30)<br>ax.axis(&#39;equal&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*vGjdJzFixQ8eWcS921cEXg.png" /><figcaption>Majority of customers didn’t make a complain in the last 2 years. (image by Author)</figcaption></figure><pre># total spending<br>plt.figure(figsize=[10, 7])<br>sns.histplot(data=df, x=&#39;Total_Spending&#39;, color=&#39;#8e0201&#39;)<br>plt.title(&#39;Total Spending Distribution&#39;, fontsize=16)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*hozpAJ8S8rdekIg4pKUp9w.png" /></figure><pre># no of dependents<br>plt.figure(figsize=[10, 7])<br>order = df[&#39;No_of_Dependents&#39;].value_counts().index<br>sns.countplot(df[&#39;No_of_Dependents&#39;], order=order, color=&#39;#8e0201&#39;)<br>plt.title(&#39;No of Dependents in Customers household&#39;, fontsize=16)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*yuqkaTjjqBtC6HUv-_Ew7A.png" /><figcaption>Majority of the customers have a single dependent. (image by Author)</figcaption></figure><pre># Purchasing_Channel distribution<br>plt.figure(figsize=[10, 7])<br>counts = df[&#39;Purchasing_Channel&#39;].value_counts()<br>labels = [f&quot;{attendance}\n{count / len(df) * 100:.1f}%&quot; for attendance, count in counts.items()]<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br><br>fig, ax = plt.subplots()<br>ax.pie(counts, labels=labels, startangle=50, counterclock=False, pctdistance=0.8, labeldistance=1.2, colors=colors)<br>centre_circle = plt.Circle((0,0),0.70,fc=&#39;white&#39;)<br>fig.gca().add_artist(centre_circle)<br>ax.set_title(&#39;Distribution of Purchasing_Channel&#39;, fontsize=16, loc=&#39;left&#39;, pad=30)<br>ax.axis(&#39;equal&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*DdLO05fmsNc98YDSWSWJww.png" /><figcaption>Majority of the customers made purchases via the Store. (image by Author)</figcaption></figure><pre># total Total_Purchases<br>plt.figure(figsize=[10, 7])<br>sns.histplot(data=df, x=&#39;Total_Purchases&#39;, color=&#39;#8e0201&#39;)<br>plt.title(&#39;Total_Purchases Distribution&#39;, fontsize=16)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*we6zGw5SUUOPtWAvcvn2MQ.png" /></figure><pre># Website_Activity dist<br>plt.figure(figsize=[10, 7])<br>sns.histplot(df[&#39;Website_Activity&#39;], kde=True, color=&#39;#8e0201&#39;)<br>plt.title(&#39;Website Activity Distribution&#39;, fontsize=16)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*oomPGFtLse36Kl5Nf3mPoA.png" /><figcaption>The Website Activity distribution is positively skewed</figcaption></figure><pre># Marital_Status_New distribution<br>plt.figure(figsize=[10, 7])<br>counts = df[&#39;Marital_Status_New&#39;].value_counts()<br>labels = [f&quot;{attendance}\n{count / len(df) * 100:.1f}%&quot; for attendance, count in counts.items()]<br>colors = [&#39;#8e0201&#39;, &#39;#e8cccc&#39;]<br><br>fig, ax = plt.subplots()<br>ax.pie(counts, labels=labels, startangle=50, counterclock=False, pctdistance=0.8, labeldistance=1.2, colors=colors)<br>centre_circle = plt.Circle((0,0),0.70,fc=&#39;white&#39;)<br>fig.gca().add_artist(centre_circle)<br>ax.set_title(&#39;Distribution of Marital Status&#39;, fontsize=16, loc=&#39;left&#39;, pad=30)<br>ax.axis(&#39;equal&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*LUsrI75on8pbpqG_5IdAOQ.png" /><figcaption>Majority of the customers have partners. (image by Author)</figcaption></figure><pre># Months_of_Enrollment distribution<br>plt.figure(figsize=[10, 7])<br>sns.histplot(df[&#39;Months_of_Enrollment&#39;], color=&#39;#8e0201&#39;)<br>plt.title(&#39;Months_of_Enrollment Distribution&#39;, fontsize=16)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*i9TjHtik1NXw_LxJf35TQg.png" /><figcaption>Most customers enrolled between 20 and 25 months ago.</figcaption></figure><pre># Education_Level distribution<br>plt.figure(figsize=[10, 7])<br>counts = df[&#39;Education_Level&#39;].value_counts()<br>labels = [f&quot;{attendance}\n{count / len(df) * 100:.1f}%&quot; for attendance, count in counts.items()]<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br><br>fig, ax = plt.subplots()<br>ax.pie(counts, labels=labels, startangle=50, counterclock=False, pctdistance=0.8, labeldistance=1.2, colors=colors)<br>centre_circle = plt.Circle((0,0),0.70,fc=&#39;white&#39;)<br>fig.gca().add_artist(centre_circle)<br>ax.set_title(&#39;Distribution of Education Level&#39;, fontsize=16, loc=&#39;left&#39;, pad=30)<br>ax.axis(&#39;equal&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*AoZak7vD-XOFZycoVsVyJw.png" /><figcaption>Majority of the customers have are Graduates. (image by Author)</figcaption></figure><pre># Parent_Status distribution<br>plt.figure(figsize=[10, 7])<br>counts = df[&#39;Parent_Status&#39;].value_counts()<br>labels = [f&quot;{attendance}\n{count / len(df) * 100:.1f}%&quot; for attendance, count in counts.items()]<br>colors = [&#39;#8e0201&#39;, &#39;#e8cccc&#39;]<br><br>fig, ax = plt.subplots()<br>ax.pie(counts, labels=labels, startangle=50, counterclock=False, pctdistance=0.8, labeldistance=1.2,  colors=colors)<br>centre_circle = plt.Circle((0,0),0.70,fc=&#39;white&#39;)<br>fig.gca().add_artist(centre_circle)<br>ax.set_title(&#39;Distribution of Parental Status&#39;, fontsize=16, loc=&#39;left&#39;, pad=30)<br>ax.axis(&#39;equal&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*I9mZ_mM8wpv5Tbi2X3k9zg.png" /><figcaption>Majority of the customers are parents. (image by Author)</figcaption></figure><pre># Total Spending by Income Distribution<br>plt.figure(figsize=[10, 7])<br>sns.scatterplot(data=df, x=&#39;Total_Spending&#39;,  y=&#39;Income&#39;,  color=&#39;#8e0201&#39;)<br>plt.title(&#39;Total Spending by Income Distribution&#39;, fontsize=16)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*EbH_a-VPFyXyjA3npdUDEg.png" /><figcaption>The Income of customers is positively correlated with the total amount they have spent. (image by Author)</figcaption></figure><pre># Days of Enrollment by Age distribution<br>plt.figure(figsize=[10, 7])<br>sns.lineplot(data=df, x=&#39;Months_of_Enrollment&#39;,  y=&#39;Age&#39;,  color=&#39;#8e0201&#39;)<br>plt.title(&#39;Number of Months of Enrollment by Age distribution&#39;, fontsize=16)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*EhfK1KZjP3-TMN6XmhN1dA.png" /></figure><pre>plt.figure(figsize=[10, 7])<br>sns.barplot(data=df, x=&#39;No_of_Dependents&#39;, y=&#39;Income&#39;, color=&#39;#8e0201&#39;)<br>plt.title(&#39;Number of dependents Clusters&#39;)<br>plt.xlabel(&#39;No of Dependents&#39;)<br>plt.ylabel(&#39;Income&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Ko4pbJlQ99yFNh_FscrBBA.png" /><figcaption>Customers with no dependents/children have the highest income. (image by Author)</figcaption></figure><h3>Data Preprocessing and Scaling</h3><p>Here we would check for outliers and then scale the dataset.</p><pre># checking for outliers<br>def print_outliers(column):<br>    q1 = column.quantile(0.25)<br>    q3 = column.quantile(0.75)<br>    iqr = q3 - q1<br>    lower_fence = q1 - 1.5 * iqr<br>    upper_fence = q3 + 1.5 * iqr<br>    outliers = column[(column &lt; lower_fence) | (column &gt; upper_fence)]<br>    <br>    print(f&quot;Outliers in {column.name}:&quot;)<br>    print(outliers)<br><br>print_outliers(df[&#39;Age&#39;])<br>print_outliers(df[&#39;Income&#39;])</pre><pre>Outliers in Age:<br>192    115<br>239    122<br>339    116<br>Name: Age, dtype: int64<br>Outliers in Income:<br>164     157243.0<br>617     162397.0<br>655     153924.0<br>687     160803.0<br>1300    157733.0<br>1653    157146.0<br>2132    156924.0<br>2233    666666.0<br>Name: Income, dtype: float64</pre><p>Removing outliers in the Age and Income columns is necessary for several reasons. Firstly, outliers in the data, such as ages of 115 or 122, and unusually high incomes like 666,666, may indicate errors or data entry mistakes. Secondly, outliers can have a significant impact on the performance of statistical models, as they can disproportionately influence the results. The removal of outliers ensures the model can focus on the majority of the data and provide more accurate predictions.</p><pre># removing outliers<br>def remove_outliers(column):<br>    q1 = column.quantile(0.25)<br>    q3 = column.quantile(0.75)<br>    iqr = q3 - q1<br>    lower_fence = q1 - (1.5 * iqr)<br>    upper_fence = q3 + (1.5 * iqr)<br>    <br>    no_outliers = column[(column &gt;= lower_fence) &amp; (column &lt;= upper_fence)]<br>    return no_outliers<br><br>no_outliers_age = remove_outliers(df[&#39;Age&#39;])<br>no_outliers_income = remove_outliers(df[&#39;Income&#39;])<br>df = df[(df[&#39;Age&#39;].isin(no_outliers_age)) &amp; (df[&#39;Income&#39;].isin(no_outliers_income))]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcLG7LGS1m4MnEX3MdbGyg.png" /><figcaption>Correlation matrix after outliers have been removed (image by Author)</figcaption></figure><pre># apply label encoding and scale the dataset<br>le = LabelEncoder()<br>cat_cols = df.select_dtypes(include=&#39;object&#39;).columns<br>for col in cat_cols:<br>    df[col] = le.fit_transform(df[col])<br>    <br>scaler = StandardScaler()<br>scaled_data = scaler.fit_transform(df)<br>df_scaled = pd.DataFrame(scaled_data, columns=df.columns)<br>df_scaled.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czwZtuzdDEX_GyN9bYt2Nw.jpeg" /><figcaption>dataset after it has been scaled and encoded (image by Author)</figcaption></figure><h3>Dimensionality Reduction Using PCA</h3><p>Dimensionality reduction is a technique used to reduce the number of features or variables in a dataset while preserving the essential information. One commonly used technique for dimensionality reduction is Principal Component Analysis (PCA), which transforms the original features into a new set of orthogonal variables called principal components. Here, I used PCA not only for dimensionality reduction but also to mitigate the impact of highly correlated features, resulting in a more robust and accurate clustering analysis.</p><pre># copy the dataset into a new variable X<br>X = df_scaled.copy()<br><br># Apply PCA for dimensionality reduction. Keep 3 componenets<br>pca = PCA(n_components=3)<br><br>#Fit the model with X and apply the dimensionality reduction on X.<br>X_pca = pca.fit_transform(X)<br><br># Plot the reduced dimension using PCA<br>fig = plt.figure(figsize=(10, 8))<br>x, y, z = X_pca[:, 0], X_pca[:, 1], X_pca[:, 2]<br>colors = &#39;#8e0201&#39;<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)<br>ax.scatter(x,y, z, c=colors, marker=&quot;d&quot;)<br>ax.set_title(&#39;Data in Reduced Dimension&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*uJVLdYbD3BGoV9ebsd1h6Q.png" /><figcaption>The plot of the features of the dataset when reduced to three.</figcaption></figure><h3>Checking the optimal number of clusters</h3><p><em>To check the optimal number of clusters, we use the following evaluation techniques namely;</em></p><blockquote>Elbow Curve method</blockquote><blockquote>Silhouette score Curve method</blockquote><blockquote>Calinski-Harabasz index curve</blockquote><pre>min_clusters = 2<br>max_clusters = 10<br>distortions = []<br>silhouette_scores = []<br>ch_scores = []<br><br># Fit K-means and compute the sum of squared distances, silhouette scores, and CH scores<br>for k in range(min_clusters, max_clusters + 1):<br>    kmeans = KMeans(n_clusters=k)<br>    kmeans.fit(df_scaled)<br>    distortions.append(kmeans.inertia_)<br>    silhouette_scores.append(silhouette_score(df_scaled, kmeans.labels_))<br>    ch_scores.append(calinski_harabasz_score(df_scaled, kmeans.labels_))<br><br># Plot the elbow curve<br>plt.figure(figsize=[10, 7])<br>plt.plot(range(min_clusters, max_clusters + 1), distortions, marker=&#39;d&#39;, label=&#39;Sum of Squared Distances&#39;, color=&#39;#8e0201&#39;)<br>plt.xlabel(&#39;Number of clusters (K)&#39;)<br>plt.ylabel(&#39;Value&#39;)<br>plt.title(&#39;Elbow Curve&#39;)<br>plt.legend()<br>plt.show()<br><br>rate_of_change = np.diff(distortions)<br>rate_of_change_ratio = rate_of_change[1:] / rate_of_change[:-1]<br>optimal_k_elbow = np.argmax(rate_of_change_ratio) + min_clusters + 1<br><br># Print the optimal number of clusters based on the elbow method<br>print(f&quot;The optimal number of clusters (Elbow method) is: {optimal_k_elbow}&quot;)<br><br># Plot the silhouette scores<br>plt.figure(figsize=[10, 7])<br>plt.plot(range(min_clusters, max_clusters + 1), silhouette_scores, marker=&#39;d&#39;, label=&#39;Silhouette Score&#39;, color=&#39;#8e0201&#39;)<br>plt.xlabel(&#39;Number of clusters (K)&#39;)<br>plt.ylabel(&#39;Value&#39;)<br>plt.title(&#39;Silhouette Analysis&#39;)<br>plt.legend()<br>plt.show()<br><br># Identify the optimal number of clusters using silhouette score<br>optimal_k_silhouette = np.argmax(silhouette_scores) + min_clusters<br><br># Print the optimal number of clusters based on the silhouette method<br>print(f&quot;The optimal number of clusters (Silhouette method) is: {optimal_k_silhouette}&quot;)<br><br># Plot the Calinski-Harabasz scores<br>plt.figure(figsize=[10, 7])<br>plt.plot(range(min_clusters, max_clusters + 1), ch_scores, marker=&#39;d&#39;, label=&#39;Calinski-Harabasz Index&#39;, color=&#39;#8e0201&#39;)<br>plt.xlabel(&#39;Number of clusters (K)&#39;)<br>plt.ylabel(&#39;Value&#39;)<br>plt.title(&#39;Calinski-Harabasz Index&#39;)<br>plt.legend()<br>plt.show()<br><br># Identify the optimal number of clusters using Calinski-Harabasz index<br>optimal_k_ch = np.argmax(ch_scores) + min_clusters<br><br># Print the optimal number of clusters based on the Calinski-Harabasz index<br>print(f&quot;The optimal number of clusters (Calinski-Harabasz method) is: {optimal_k_ch}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*XOQLdkTaC0GsqpAbDCKETA.png" /><figcaption>The optimal number of clusters (Elbow method) is: 5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*_BLMD7wckQWdZj4JKeVASg.png" /><figcaption>The optimal number of clusters (Silhouette method) is: 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*o6-Ebcoyw__2hTI_Jkd56A.png" /><figcaption>The optimal number of clusters (Calinski-Harabasz method) is: 2</figcaption></figure><p>In this case, we would prioritize the Silhouette method and the Calinski-Harabasz method, as they both provide insights into the quality and separation of the clusters.<br>The <strong>Silhouette method</strong> suggests 2 clusters, indicating that the data points within each cluster are relatively well-separated from points in other clusters. This could imply a clear distinction between two major customer segments.<br>The <strong>Calinski-Harabasz method</strong> also suggests 2 clusters, indicating a high inter-cluster variance compared to the intra-cluster variance. This suggests that the clusters are well-separated and distinct from each other.</p><h3>Agglomerative Clustering</h3><p>Now that I have reduced the attributes to two dimensions, I will be performing segmentation by clustering via Agglomerative clustering. Agglomerative clustering is a hierarchical clustering method. It involves merging examples until the desired number of clusters is achieved. And since we have 2 to be the optimal number of clusters from the methods we used above, we will set it to 2 in the Agglomerative Clustering.</p><pre># Fit Agglomerative Clustering model<br>clustering = AgglomerativeClustering(n_clusters=2)<br>clustering.fit_predict(X_pca)<br><br># Obtain cluster labels<br>cluster_labels = clustering.labels_<br><br># Add the cluster labels to the original dataframe<br>df_clustered = df_scaled.copy()<br>df_clustered[&#39;Cluster&#39;] = cluster_labels<br><br># Analyze Clusters<br>cluster_counts = df_clustered[&#39;Cluster&#39;].value_counts()<br>print(&#39;Cluster Counts:&#39;)<br>print(cluster_counts)<br><br># Visualize the clusters<br>plt.figure(figsize=(8, 6))<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.scatterplot(X_pca[:, 0], X_pca[:, 1], hue=cluster_labels, palette=palette)<br>plt.title(&#39;Agglomerative Clustering&#39;)<br>plt.xlabel(&#39;Principal Component 1&#39;)<br>plt.ylabel(&#39;Principal Component 2&#39;)<br>plt.show()<br><br>Cluster Counts:<br>1    1197<br>0    1008<br>Name: Cluster, dtype: int64</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*EY-1nxtEm4idPAbgqlAc2w.png" /></figure><pre># Now lets have a visual distribution of the Clusters.<br>plt.figure(figsize=[6, 6])<br>order = df_clustered[&#39;Cluster&#39;].value_counts().index<br>pl = sns.countplot(x=df_clustered[&quot;Cluster&quot;], color=&#39;#8e0201&#39;, order=order)<br>pl.set_title(&quot;Distribution Of The Clusters&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*QinN1KdZRnpS6cX5vzTxnA.png" /><figcaption>We can see that the clusters are evenly distributed. (Image by Author)</figcaption></figure><h3>Cluster Profiling</h3><p>This involves the profiling of the segments and to see where the customers belong by studying the patterns of the clusters.</p><pre># Add cluster labels to original dataset<br>clusters = cluster_labels<br>df[&#39;Clusters&#39;] = clusters.astype(int)</pre><pre>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.scatterplot(data=df, x=&#39;Income&#39;, y=&#39;Total_Spending&#39;, hue=&#39;Clusters&#39;, palette=palette)<br>plt.title(&#39;Total Spending and Income based on Clusters&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*SPldP7_v2jp0EP_0MI7_NQ.png" /></figure><p><strong>Insights:</strong><br>Cluster 0: High Income and High Spending<br>Cluster 1: Low Income and Low Spending</p><pre>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.scatterplot(data=df, x=&#39;Total_Spending&#39;, y=&#39;Age&#39;, hue=&#39;Clusters&#39;, palette=palette)<br>plt.title(&#39;Total Spending and Age based on Clusters&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*MYG3vKCY2pfBy2I_-GaOqA.png" /></figure><p><strong>Insights:</strong><br>There isn’t much insight to be drawn from the above cluster patterns of the relationship between Customer’s age and the total amount they have spent as can be seen above.</p><pre>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.violinplot(data=df, x=&#39;Clusters&#39;,  y=&#39;Total_Purchases&#39;, palette=palette)<br>plt.title(&#39;Total number of purchases made&#39;)<br>plt.xlabel(&quot;Number Of purchases made&quot;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*PGZo08Amwrm8dtQXj73oHg.png" /></figure><p><strong>Insights:</strong><br>Cluster 0: The total number of purchases made on average is 21 and the highest total purchases from folks in this segment is 43.<br>Cluster 1: The total number of purchases made on average is about 10 and the highest total purchases from folks in this segment is 26. This isn’t really a surprise as Customers in Cluster 0 are the highest earning customers and also spend the most. Again, the lowest total purchases by customers in the first cluster is 7 while some customers in the second cluster didn&#39;t even make any purchase at all.</p><pre>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.boxplot(data=df, x=&#39;Clusters&#39;, y=&#39;Age&#39;, palette=palette)<br>plt.title(&#39;Clusters by Age&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*nZ21NAsqMSpiQGwUdOl_nA.png" /></figure><p><strong>Insights:</strong><br>Firstly, we can see no outlier points in the Age distribution for both set of customers. Customers in the Cluster 0 are the oldest with their median age at almost 50 and the oldest at 75 while those belonging to Cluster 1 have their median age pegged at a little above 40 and oldest at 70.</p><pre>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.countplot(data=df, x=&#39;Total_Acceptance&#39;, hue=&#39;Clusters&#39;, palette=palette)<br>plt.title(&#39;Total number of marketing campaigns accepted&#39;)<br>plt.xlabel(&quot;Number Of Total Accepted Promotions&quot;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*UblvO_3rp9tuvCGj--cfFQ.png" /></figure><p><strong>Insights:</strong><br>As can be seen above, there has been a reluctance by customers in the campaigns they have accepted. No customer also partakes in all five of the campaigns.</p><pre>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.countplot(data=df, x=&#39;Months_of_Enrollment&#39;, hue=&#39;Clusters&#39;, palette=palette)<br>plt.xlabel(&#39;Number of Months since Enrollment&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*d5xMX_cLTrfMjdcnDjGsqA.png" /></figure><p><strong>Insights:</strong><br>The customers that enrolled the earliest and spent the most belong to Cluster 0. The second cluster has customers that spent the lowest with the earliest enrollments among them contributing to their very low spending.</p><pre>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.countplot(data=df, x=&#39;No_of_Dependents&#39;, hue=&#39;Clusters&#39;, palette=palette)<br>plt.xlabel(&#39;Number of Dependents in customers household&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*dNdJX8-fMd2tlTVXVWmvSQ.png" /></figure><p><strong>Insights:</strong><br>Customers belonging to the first cluster mostly have no dependents in their household while the customers in the second cluster majorly have a single dependent. Overall customers with dependents mostly belong to the second cluster.</p><pre># Marital Status<br>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.countplot(data=df, x=&#39;Marital_Status_New&#39;, hue=&#39;Clusters&#39;, palette=palette)<br>plt.xlabel(&#39;Marital Status&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.xticks(ticks=[0, 1], labels=[&#39;Single&#39;, &#39;Married&#39;])<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*eNlR15f6ULFFOzvZlLWwbw.png" /></figure><p><strong>Insights:</strong><br>The marital status in all clusters indicates married with a big majority going to the customers in Cluster 1.</p><pre># no_of_dependents vs income<br>plt.figure(figsize=[10, 7])<br>colors = [&#39;#8e0201&#39;, &#39;#c93432&#39;, &#39;#e8cccc&#39;]<br>palette = sns.set_palette(sns.color_palette(colors))<br>sns.barplot(data=df, x=&#39;No_of_Dependents&#39;, y=&#39;Income&#39;, hue=&#39;Clusters&#39;, palette=palette, ci=None)<br>plt.title(&#39;Number of dependents Clusters&#39;)<br>plt.xlabel(&#39;No of Dependents&#39;)<br>plt.ylabel(&#39;Income&#39;)<br># plt.xticks(ticks=[0, 1], labels=[&#39;Single&#39;, &#39;Married&#39;])<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*iw-VYqLKzeJ4CbbaQEZfJQ.png" /></figure><p><strong>Insights:</strong><br>Majority of customers in Cluster 0 have no dependent/child and they have the highest income while most customers in Cluster 1 have 3 dependents/children and are the highest earners in this case.</p><h3>Conclusion</h3><ul><li>Most customers didn&#39;t make a complaint in the last two years.</li><li>Most customers have a single dependent/child in their household.</li><li>Most customers made purchases via the Store.</li><li>Most customers enrolled between 20 and 25 months ago</li><li>Majority of the customers have partners.</li><li>Majority of the customers have been Graduates.</li><li>Majority of the customers are parents.</li><li>Customers that didn’t respond to campaigns are the majority.</li><li>The earliest enrollments in the business were by customers aged 48.</li><li>The total amount spent is highly correlated with customers income and the total purchases they made.</li><li>The highest spending age groups are between 40–60.</li><li>Of the three metrics we used to evaluate the model, two of them(majority) suggested 2 clusters.</li><li>Customers with no dependents/children have been the highest spenders.</li></ul><h3>Business Insights</h3><ul><li>To address the reluctance of customers in accepting the campaigns and encourage higher participation rates, tailor the campaign offers specifically to the preferences and needs of customers in cluster 1.</li><li>To address the challenges of low income and low spending among customers in Cluster 1, develop affordable and cost-effective products that cater to the budget constraints and you can also implement programs that provide incentives if they repeatedly buy a product more than once which will allow the, to continue engaging with the business even with their low income.</li><li>The preferences, priorities, and purchasing behaviors of older customers in Cluster 0 may differ from those of the younger customers in Cluster 1 hence the need to consider age-related factors when developing new products or enhancing existing ones.</li><li>Given that the majority of customers make purchases from the stores, it is crucial to maintain a strong presence and optimize the in-store experience and while fewer customers make purchases online, it highlights the potential for growth in the e-commerce channel hence the business should focus on improving website usability.</li></ul><blockquote>Thanks for reading🤓. Check out my GitHub <a href="https://github.com/Abdulraqib20/Customer-Personality-Analysis">repo</a> where you can find the code and other resources related to the project. Your feedback and suggestions are valuable and will help me improve and deliver more meaningful content in the future. Cheers!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ec1fd66f1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Opportunities: A Step-by-Step Guide to Accessing Free Financial Aid on Coursera]]></title>
            <link>https://medium.com/@abdulraqibshakir03/unlocking-opportunities-a-step-by-step-guide-to-accessing-free-financial-aid-on-coursera-6bfaac1e09ac?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bfaac1e09ac</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 20:35:58 GMT</pubDate>
            <atom:updated>2023-06-08T20:35:58.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EF04tuaoL8oLR-d-" /><figcaption>Photo by <a href="https://unsplash.com/@kobuagency?utm_source=medium&amp;utm_medium=referral">KOBU Agency</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Education is a powerful catalyst for personal and professional growth, but financial barriers often hinder access to quality learning opportunities. Fortunately, Coursera has revolutionized the landscape by providing top-notch courses from prestigious institutions — and they’re committed to making education accessible to all. The beauty of Coursera lies not only in its diverse catalog of courses but also in its commitment to making education accessible to all. One of the ways it achieves this mission is by offering financial aid to learners who may face financial constraints. If you’ve been eager to enhance your skills and knowledge but have concerns about the cost, you’re in the right place.</p><p>In this guide, I’ll walk you through the process of obtaining financial aid on Coursera, sharing the valuable insights and resources I’ve personally benefited from. By following these steps, you can embark on your own learning journey without the burden of financial constraints. Whether you’re a student, a professional looking to upskill, or someone passionate about expanding your knowledge, this guide will equip you with the knowledge and tools to tap into the free financial aid resources available on Coursera, just as I have done.</p><h3><strong>Step 1: Login to Coursera and Discover Your Desired Course</strong></h3><p>To begin your journey towards obtaining financial aid on Coursera, the first step is to log in to your Coursera account. If you don’t have an account yet, create one — it’s a quick and simple process. Once you’re logged in, navigate through Coursera’s vast catalog of courses and find the one that aligns with your learning goals and interests. Coursera offers a wide range of subjects, from technology and business to arts and humanities. Take your time to explore and select the course that resonates with you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oODIYK3RbYsNMJR7ZUjV6g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMCuJZ4U5PBI8hknMumjyg.jpeg" /></figure><h3>Step 2: Access Financial Aid Application for Your Chosen Course</h3><p>Once you have identified the course you wish to learn on Coursera, click on the course title to access its detailed information page. On this page, you will find an “Enroll for Free” button, but instead of clicking on it right away, look for the “Financial Aid” option located beside the enrollment button.</p><p>Click on the “Financial Aid” link to initiate the financial aid application process. This step will redirect you to a separate page where you can provide essential information about your financial circumstances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYMART992JcGZKvyQ0ANNA.jpeg" /></figure><h3>Step 3: Select Courses for Financial Aid Application</h3><p>After clicking on the “Financial Aid” option for your chosen course, a financial aid application window will open. In this window, you will find a list of available courses that you can apply for financial aid. Carefully review the list of courses presented to you, ensuring they align with your learning goals and interests. Take note of the course names and select the ones you want to apply for financial aid.</p><p>You can choose multiple courses to include in your financial aid application, but make sure you can commit to completing them within the specified timeframes. It’s essential to be realistic about your capacity to manage multiple courses simultaneously, considering other commitments and responsibilities you may have. Once you have finalized your selection, click on the corresponding checkboxes next to the course names to indicate your choices for financial aid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*2dTNt7Xj0eR45lhlp02-2A.jpeg" /></figure><h3>Step 4: Provide Required Information and Explain Your Financial Aid Application</h3><p>After selecting the courses you want to apply for financial aid, it’s time to enter the required information in the checkboxes and provide a compelling reason for your application. The checkboxes may vary depending on the course, but typically, you’ll be asked to provide information such as your education, annual income, amount you can pay, employment status, and reason you are applying. Fill out these checkboxes accurately to ensure a fair assessment of your financial situation.</p><p>When it comes to explaining why you are applying for financial aid, it’s important to craft a thoughtful and sincere response. Here are some hints to help you write your statement:</p><ol><li>Demonstrate your commitment: Express your genuine passion for learning and how obtaining financial aid would enable you to pursue your educational goals. Share how these courses align with your career aspirations or personal interests.</li><li>Highlight financial constraints: Articulate any financial challenges you are currently facing that make it difficult for you to afford the course fees. This could include limited financial resources, being a student with limited income, or other financial obligations you have to manage.</li><li>Emphasize the value of education: Share your belief in the transformative power of education and how these courses would contribute to your personal and professional growth. Discuss how the knowledge and skills gained from these courses would have a positive impact on your life.</li><li>Express gratitude and commitment: Convey your appreciation for the opportunity to apply for financial aid and express your dedication to completing the courses if awarded aid. Highlight your commitment to making the most of this educational opportunity and how you plan to apply the knowledge gained.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ffLH4BKAMllGNkTruz67g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUvhpU1q6aiGLGpzTa5ncg.jpeg" /></figure><h3>Step 5: Review Your Application and Submit with Confidence</h3><p>Before you hit that submit button, take a moment to review your financial aid application. Double-check that you have provided all the required information accurately and that your statement clearly articulates your need for financial assistance.</p><p>Reviewing your application ensures that you have put forth your best effort and increases the likelihood of a favorable response from Coursera. Once you’re satisfied with your application, go ahead and submit it with confidence, knowing that you have taken the necessary steps to access free financial aid for your desired courses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgVimYJaQ41zpZze1TztiQ.jpeg" /></figure><p>Congratulations on taking the initiative to pursue your educational goals through Coursera’s financial aid program. By applying for financial aid, you have demonstrated your determination to overcome financial barriers and invest in your personal and professional development. Remember, the decision regarding your financial aid application rests with Coursera, and it usually takes at least 2 weeks for them to review and respond. Be patient and stay positive during this waiting period. Wishing you the best of luck in your financial aid application and your educational journey ahead!</p><p><em>Thank you for taking the time to read this guide on accessing free financial aid on Coursera🤓. I hope you found the information valuable and empowering as you embark on your learning journey.</em></p><p><em>If you’re interested in exploring more of my work as a data scientist, I have documented several projects on Medium. You can find them </em><a href="https://medium.com/@abdulraqibshakir03"><em>here</em></a><em>. Additionally, you can explore my GitHub </em><a href="https://github.com/Abdulraqib20"><em>repository</em></a><em> and portfolio </em><a href="https://raqibcodes.me/"><em>website</em></a><em> to discover more projects and resources related to data science. Cheers!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bfaac1e09ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis on Student Feedback in Engineering Education]]></title>
            <link>https://medium.com/@abdulraqibshakir03/sentiment-analysis-on-student-feedback-in-engineering-education-55a913dd7967?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/55a913dd7967</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 00:13:25 GMT</pubDate>
            <atom:updated>2023-07-08T23:24:45.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QjoyUXqKNR0VK4vr" /><figcaption>Photo by <a href="https://unsplash.com/@zulmaury?utm_source=medium&amp;utm_medium=referral">Zulmaury Saavedra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the field of engineering education, student feedback plays a vital role in assessing the effectiveness of teaching methods, course materials, and overall learning experiences. Sentiment analysis, a key component of data science, offers a powerful approach to analyze and extract valuable insights from student feedback.</p><p>The objective of this project is to perform sentiment analysis on the feedback provided by <strong>300 level computer engineering students in the University of Ilorin (my course mates)</strong>. By making use of natural language processing (NLP) techniques and machine learning algorithms, we aim to uncover sentiments expressed in the feedback and gain a comprehensive understanding of student perceptions, satisfaction, and areas of improvement.</p><p>Through the analysis of student feedback, we can identify common themes, sentiment trends, and specific challenges faced by students. This valuable information can help inform the department and it’s lectureres about the effectiveness of their teaching methodologies, course content, and student support systems. The insights derived from sentiment analysis on student feedback can drive evidence-based decision-making in engineering education. It enables the department to address concerns, make improvements, and create a positive learning environment that caters to the needs of the students.</p><h3>Data Collection</h3><p>To get the data to use for this project, I utilized <a href="https://docs.google.com/forms/d/e/1FAIpQLSeInhWFxECdegDDIYo7uY3-U-JHYyUDkTBQBw-KJxIvzYg_yA/viewform">Google Forms</a> to collect valuable feedback from students. The platform aided in the collection of diverse responses ensuring accuracy and efficiency in gathering student sentiments and provided a comprehensive dataset for the sentiment analysis project. Afterwards, I exported the collected data to a CSV format for the analysis.</p><p><strong>Importing libraries and packages</strong></p><pre># importing libraries and packages<br><br>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>sns.set_theme(style=&#39;white&#39;)<br>from PIL import Image<br><br>import re<br>import string<br>from nltk.tokenize import word_tokenize<br>from nltk.corpus import stopwords<br>from nltk.stem import WordNetLemmatizer<br>from nltk.sentiment import SentimentIntensityAnalyzer<br>from textblob import TextBlob<br>from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator<br><br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.feature_extraction.text import TfidfTransformer<br>from sklearn.decomposition import PCA<br>from sklearn.cluster import KMeans<br>from sklearn.feature_extraction.text import CountVectorizer<br>from sklearn.decomposition import LatentDirichletAllocation<br><br>import xgboost as xgb<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.naive_bayes import MultinomialNB<br>from sklearn.metrics import accuracy_score, roc_auc_score<br>from sklearn.pipeline import Pipeline<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><pre># load the dataset and show the first 5 rows<br>df = pd.read_csv(&#39;Sentiment Analysis on Student Feedback.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jx1EmIelAWK4VQVbuxE8vQ.jpeg" /><figcaption>The first 5 rows of the dataset.</figcaption></figure><pre>df.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 100 entries, 0 to 99<br>Data columns (total 11 columns):<br> #   Column                  Non-Null Count  Dtype <br>---  ------                  --------------  ----- <br> 0   Timestamp               100 non-null    object<br> 1   Course Code             100 non-null    object<br> 2   Feedback                100 non-null    object<br> 3   Previous Experience     100 non-null    object<br> 4   Gender                  100 non-null    object<br> 5   Attendance              100 non-null    object<br> 6   Course Difficulty       100 non-null    object<br> 7   Study Hours (per week)  100 non-null    object<br> 8   Overall Satisfaction    100 non-null    int64 <br> 9   Department              100 non-null    object<br> 10  Unnamed: 11             3 non-null      object<br>dtypes: int64(1), object(10)<br>memory usage: 8.7+ KB</pre><h3>Data Cleaning</h3><p>Here, I’m going to clean the dataset as it can be seen to have some quality issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNO_Is2hKexubicLYXJZ-g.png" /><figcaption>The initial columns vs the columns when leading and trailing characters are removed.</figcaption></figure><pre># drop unncessary column<br>df = df.drop([&#39;Unnamed: 11&#39;], axis=1)<br><br># Convert the column to datetime format<br>df[&#39;Timestamp&#39;] = pd.to_datetime(df[&#39;Timestamp&#39;])<br><br># Extract the date and time into separate columns<br>df[&#39;Date&#39;] = df[&#39;Timestamp&#39;].dt.date<br>df[&#39;Time&#39;] = df[&#39;Timestamp&#39;].dt.time<br><br># drop Timestamp column<br>df = df.drop([&#39;Timestamp&#39;], axis=1)<br><br># corrections to &quot;Study Hours (per week) column&quot;<br>df[&#39;Study Hours (per week)&#39;] = df[&#39;Study Hours (per week)&#39;].str.extract(r&#39;(\d+)&#39;).fillna(0).astype(int)<br></pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 100 entries, 0 to 99<br>Data columns (total 11 columns):<br> #   Column                  Non-Null Count  Dtype <br>---  ------                  --------------  ----- <br> 0   Course Code             100 non-null    object<br> 1   Feedback                100 non-null    object<br> 2   Previous Experience     100 non-null    object<br> 3   Gender                  100 non-null    object<br> 4   Attendance              100 non-null    object<br> 5   Course Difficulty       100 non-null    object<br> 6   Study Hours (per week)  100 non-null    int32 <br> 7   Overall Satisfaction    100 non-null    int64 <br> 8   Department              100 non-null    object<br> 9   Date                    100 non-null    object<br> 10  Time                    100 non-null    object<br>dtypes: int32(1), int64(1), object(9)<br>memory usage: 8.3+ KB</pre><p>Let’s now preview some random samples of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j3sQhyqELhl62YXTJU4EeQ.jpeg" /></figure><h3>Data Preprocessing</h3><p>Cleaning and preprocessing the data by handling contractions, converting text to lower case removing stop words, punctuations, hashtags, numbers/digits and special characters and then tokenizing and lemmatizing the text.</p><pre># Function to handle contractions<br>def handle_contractions(text):<br>    contractions = {<br>        &quot;n&#39;t&quot;: &quot; not&quot;,<br>        &quot;&#39;s&quot;: &quot; is&quot;,<br>        &quot;&#39;re&quot;: &quot; are&quot;,<br>        &quot;&#39;ve&quot;: &quot; have&quot;,<br>        &quot;&#39;d&quot;: &quot; would&quot;,<br>        &quot;&#39;ll&quot;: &quot; will&quot;,<br>        &quot;&#39;m&quot;: &quot; am&quot;<br>    }<br><br>    words = text.split()<br>    for i in range(len(words)):<br>        if words[i] in contractions:<br>            words[i] = contractions[words[i]]<br>    return &#39; &#39;.join(words)<br><br># Function to preprocess text data<br>def preprocess_text(text):<br>    # Convert to lowercase<br>    text = text.lower()<br>    <br>    # Remove URLs, hashtags, mentions, and special characters<br>    text = re.sub(r&quot;http\S+|www\S+|@\w+|#\w+&quot;, &quot;&quot;, text)<br>    text = re.sub(r&quot;[^\w\s]&quot;, &quot;&quot;, text)<br><br>    # Remove numbers/digits<br>    text = re.sub(r&#39;\b[0-9]+\b\s*&#39;, &#39;&#39;, text)<br>#     text = re.sub(r&#39;\d+&#39;, &#39;&#39;, text)<br><br>    # Remove punctuation<br>    text = &#39;&#39;.join([char for char in text if char not in string.punctuation])<br><br>    # Tokenize the text<br>    tokens = word_tokenize(text)<br><br>    # Remove stop words<br>    stop_words = set(stopwords.words(&#39;english&#39;))<br>    tokens = [token for token in tokens if token not in stop_words]<br>    <br>    # Convert to lowercase<br>    tokens = [token.lower() for token in tokens]<br><br>    # Handle contractions<br>    text = handle_contractions(&#39; &#39;.join(tokens))<br><br>    # Lemmatize the words<br>    lemmatizer = WordNetLemmatizer()<br>    tokens = [lemmatizer.lemmatize(token) for token in word_tokenize(text)]<br><br>    # Join tokens back into a single string<br>    processed_text = &#39; &#39;.join(tokens)<br><br>    return processed_text<br><br># Apply preprocessing to the &#39;Feedback&#39; column<br>df[&#39;Processed_Feedback&#39;] = df[&#39;Feedback&#39;].apply(preprocess_text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*7fHQuAA-pIc9Y51Ow6jylw.jpeg" /><figcaption>First 10 rows of the “Processed” feedback column.</figcaption></figure><h3>Language Detection</h3><p>Detecting the type of language used in the feedback text.</p><pre>from langdetect import detect<br><br>def detect_language(text):<br>    try:<br>        lang = detect(text)<br>        return lang<br>    except:<br>        return None<br>    <br>df[&#39;Language&#39;] = df[&#39;Processed_Feedback&#39;].apply(detect_language)<br>df[&#39;Language&#39;].unique()</pre><pre>array([&#39;en&#39;, &#39;cy&#39;, &#39;so&#39;, &#39;sk&#39;, &#39;af&#39;, &#39;fr&#39;, &#39;hr&#39;, &#39;id&#39;, &#39;pt&#39;, &#39;de&#39;, &#39;pl&#39;,<br>       &#39;es&#39;], dtype=object)</pre><pre>language_mapping = {<br>    &#39;en&#39;: &#39;English&#39;,<br>    &#39;cy&#39;: &#39;Welsh&#39;,<br>    &#39;so&#39;: &#39;Somali&#39;,<br>    &#39;sk&#39;: &#39;Slovak&#39;,<br>    &#39;af&#39;: &#39;Afrikaans&#39;,<br>    &#39;fr&#39;: &#39;French&#39;,<br>    &#39;hr&#39;: &#39;Croatian&#39;,<br>    &#39;id&#39;: &#39;Indonesian&#39;,<br>    &#39;pt&#39;: &#39;Portuguese&#39;,<br>    &#39;it&#39;: &#39;Italian&#39;,<br>    &#39;pl&#39;: &#39;Polish&#39;,<br>    &#39;es&#39;: &#39;Spanish&#39;<br>}<br><br>df[&#39;Language&#39;] = df[&#39;Language&#39;].map(language_mapping)<br>df[&#39;Language&#39;].unique()</pre><pre>array([&#39;English&#39;, &#39;Welsh&#39;, &#39;Somali&#39;, &#39;Slovak&#39;, &#39;Afrikaans&#39;, &#39;French&#39;,<br>       &#39;Croatian&#39;, &#39;Indonesian&#39;, &#39;Portuguese&#39;, nan, &#39;Polish&#39;, &#39;Spanish&#39;],<br>      dtype=object)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*ouJNwSuIXAStTXJSZ4Varw.jpeg" /></figure><p>The language is not important in this analysis though as it is not consistent with the feedback text. So, I’ll drop the column.</p><pre>df[&#39;Char_Count&#39;] = df[&#39;Processed_Feedback&#39;].apply(len) # can also use df[&#39;Processed_Feedback&#39;].str.len()<br>df[&#39;Word_Count&#39;] = df[&#39;Processed_Feedback&#39;].apply(lambda x: len(x.split()))<br>df = df.drop([&#39;Language&#39;], axis=1)</pre><h3>Sentiment scores and Labels</h3><p>Calculating the sentiment scores and its corresponding labels.</p><p><strong>Important Note</strong></p><p>In the context of sentiment analysis, <strong>subjectivity scores</strong> can help distinguish between subjective statements that reflect personal opinions or emotions and objective statements that convey factual information. A high subjectivity score indicates a greater level of personal bias or opinion, while a low subjectivity score suggests a more objective or factual nature of the text.</p><p>Subjectivity is an important aspect to consider alongside polarity (sentiment) analysis, as it provides additional context and granularity in understanding the nature of the text and the subjective or objective nature of the statements being analyzed. The interpretation of subjectivity scores depends on the specific context and objective of your analysis. In general, a high subjectivity score indicates a greater degree of personal opinion or bias expressed in the text. This can be valuable if you are interested in capturing and analyzing subjective or emotional content, such as in sentiment analysis or opinion mining.</p><p>However, if the goal is to analyze and classify objective or factual information, a low subjectivity score would be more desirable. A low subjectivity score suggests that the text contains more objective statements that are based on facts or present information without personal opinion or bias.</p><pre># Calculate sentiment scores<br>df[&#39;Sentiment_Score&#39;] = df[&#39;Processed_Feedback&#39;].apply(lambda x: TextBlob(x).sentiment.polarity)<br><br># Calculate subjectivity scores<br>df[&#39;Subjectivity_Score&#39;] = df[&#39;Processed_Feedback&#39;].apply(lambda x: TextBlob(x).sentiment.subjectivity)<br><br># Map sentiment scores to sentiment labels<br>df[&#39;Sentiment_Label&#39;] = df.apply(lambda row: &#39;Positive&#39; if row[&#39;Sentiment_Score&#39;] &gt; 0 and row[&#39;Subjectivity_Score&#39;] &gt; 0.5 else <br>                                        &#39;Negative&#39; if row[&#39;Sentiment_Score&#39;] &lt; 0 and row[&#39;Subjectivity_Score&#39;] &gt; 0.5 else &#39;Neutral&#39;, axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oD4I5S99foFmd0IXQzRAfA.jpeg" /><figcaption>Random samples of the dataset.</figcaption></figure><h3>Aspect-Based sentiment Analysis Metrics</h3><p><strong>Summary Statistics and Metrics</strong></p><pre># Sentiment Analysis Metrics<br>sentiment_counts = df[&#39;Sentiment_Label&#39;].value_counts()<br>average_sentiment_score = df[&#39;Sentiment_Score&#39;].mean()<br>average_subj_score = df[&#39;Subjectivity_Score&#39;].mean()<br><br># Descriptive Statistics<br>study_hours_stats = df[&#39;Study Hours (per week)&#39;].describe()<br>overall_satisfaction_stats = df[&#39;Overall Satisfaction&#39;].describe()<br><br># Categorical Metrics<br>course_code_counts = df[&#39;Course Code&#39;].value_counts()<br>department_counts = df[&#39;Department&#39;].value_counts()<br>sentiment_distribution = df.groupby(&#39;Course Code&#39;)[&#39;Sentiment_Label&#39;].value_counts(normalize=True)<br><br># Print the calculated metrics<br>print(&quot;Sentiment Analysis Metrics:&quot;)<br>print(sentiment_counts)<br>print(&quot;Average Sentiment Score:&quot;, average_sentiment_score)<br>print(&quot;Average SUbjectivity Score:&quot;, average_subj_score)<br>print(&quot;\nDescriptive Statistics - Study Hours:&quot;)<br>print(study_hours_stats)<br>print(&quot;\nDescriptive Statistics - Overall Satisfaction:&quot;)<br>print(overall_satisfaction_stats)<br>print(&quot;\nCategorical Metrics - Course Code Counts:&quot;)<br>print(course_code_counts)<br>print(&quot;\nCategorical Metrics - Department Counts:&quot;)<br>print(department_counts)<br>print(&quot;\nSentiment Distribution by Course Code:&quot;)<br>print(sentiment_distribution)</pre><pre>Sentiment Analysis Metrics:<br>Neutral     42<br>Positive    34<br>Negative    24<br>Name: Sentiment_Label, dtype: int64<br>Average Sentiment Score: 0.04988879870129869<br>Average Subjectivity Score: 0.5088712121212121<br>Average Length of Feedback: 31.8<br><br>Descriptive Statistics - Study Hours:<br>count    100.000000<br>mean       8.310000<br>std        5.506094<br>min        0.000000<br>25%        4.000000<br>50%        8.000000<br>75%       12.000000<br>max       21.000000<br>Name: Study Hours (per week), dtype: float64<br><br>Descriptive Statistics - Overall Satisfaction:<br>count    100.000000<br>mean       5.100000<br>std        3.599944<br>min        0.000000<br>25%        1.000000<br>50%        5.000000<br>75%        9.000000<br>max       10.000000<br>Name: Overall Satisfaction, dtype: float64<br><br>Categorical Metrics - Course Code Counts:<br>CPE 321    31<br>CPE 311    13<br>CPE 341    13<br>CPE 381    12<br>CPE 331    11<br>MEE 361    10<br>GSE 301    10<br>Name: Course Code, dtype: int64<br><br>Categorical Metrics - Department Counts:<br>Yes    99<br>No      1<br>Name: Department, dtype: int64<br><br>Sentiment Distribution by Course Code:<br>Course Code  Sentiment_Label<br>CPE 311      Positive           0.769231<br>             Neutral            0.153846<br>             Negative           0.076923<br>CPE 321      Negative           0.516129<br>             Neutral            0.387097<br>             Positive           0.096774<br>CPE 331      Positive           0.727273<br>             Neutral            0.181818<br>             Negative           0.090909<br>CPE 341      Neutral            0.538462<br>             Negative           0.230769<br>             Positive           0.230769<br>CPE 381      Neutral            0.666667<br>             Negative           0.166667<br>             Positive           0.166667<br>GSE 301      Neutral            0.600000<br>             Positive           0.400000<br>MEE 361      Neutral            0.500000<br>             Positive           0.400000<br>             Negative           0.100000<br>Name: Sentiment_Label, dtype: float64</pre><p><strong>Analyzing the frequency of specific keywords or phrases in the feedback.</strong></p><pre># analyze the frequency of specific keywords or phrases in the feedback<br>from collections import Counter<br><br># The keywords or phrases of interest<br>keywords = [&#39;shit&#39;, &#39;difficult&#39;, &#39;terrible&#39;, &#39;okay&#39;, &#39;best&#39;, &#39;worst&#39;, &#39;good&#39;, &#39;try&#39;]<br><br># Concatenate all the preprocessed feedback into a single string<br>all_feedback = &#39; &#39;.join(df[&#39;Processed_Feedback&#39;])<br><br># Tokenize the text into individual words<br>tokens = all_feedback.split()<br><br># Count the frequency of each keyword in the feedback<br>keyword_frequency = Counter(tokens)<br><br># Print the frequency of each keyword<br>for keyword in keywords:<br>    print(f&quot;Frequency of &#39;{keyword}&#39;: {keyword_frequency[keyword]}&quot;)</pre><pre>Frequency of &#39;shit&#39;: 1<br>Frequency of &#39;difficult&#39;: 4<br>Frequency of &#39;terrible&#39;: 5<br>Frequency of &#39;okay&#39;: 3<br>Frequency of &#39;best&#39;: 3<br>Frequency of &#39;worst&#39;: 2<br>Frequency of &#39;good&#39;: 8<br>Frequency of &#39;try&#39;: 1</pre><p><strong>Text clustering to group similar feedback together</strong></p><pre># Create a TF-IDF vectorizer<br>vectorizer = TfidfVectorizer()<br><br># Apply TF-IDF vectorization to the processed feedback text<br>tfidf_matrix = vectorizer.fit_transform(df[&#39;Processed_Feedback&#39;])<br><br># Perform K-means clustering<br>num_clusters = 3  # Specify the desired number of clusters<br>kmeans = KMeans(n_clusters=num_clusters, random_state=42)<br>kmeans.fit(tfidf_matrix)<br><br># Assign cluster labels to the feedback data<br>df[&#39;Cluster&#39;] = kmeans.labels_<br><br># Apply dimensionality reduction using PCA<br>pca = PCA(n_components=2)<br>reduced_features = pca.fit_transform(tfidf_matrix.toarray())<br><br># Plot the clusters<br>plt.figure(figsize=(8, 6))<br>plt.scatter(reduced_features[:, 0], reduced_features[:, 1], c=df[&#39;Cluster&#39;], cmap=&#39;viridis&#39;)<br>plt.xlabel(&#39;PC1&#39;)<br>plt.ylabel(&#39;PC2&#39;)<br>plt.title(&#39;K-means Clustering Visualization&#39;)<br>plt.colorbar()<br>plt.show()<br><br># Print the top terms for each cluster<br>print(&quot;Top terms per cluster:&quot;)<br>order_centroids = kmeans.cluster_centers_.argsort()[:, ::-1]<br>terms = vectorizer.get_feature_names()<br>for i in range(num_clusters):<br>    print(f&quot;Cluster {i}:&quot;)<br>    for ind in order_centroids[i, :10]:<br>        print(f&quot;  {terms[ind]}&quot;)<br>    print()</pre><pre>Top terms per cluster:<br>Cluster 0:<br>  nice<br>  course<br>  teaching<br>  scientist<br>  lecturer<br>  easy<br>  method<br>  job<br>  way<br>  go<br><br>Cluster 1:<br>  lecturer<br>  good<br>  teaching<br>  terrible<br>  course<br>  method<br>  like<br>  bad<br>  akanni<br>  class<br><br>Cluster 2:<br>  course<br>  stress<br>  easy<br>  well<br>  hard<br>  awful<br>  unit<br>  wahala<br>  plus<br>  dey</pre><h3>Topic Modeling</h3><p>Implementing the topic modeling technique, <strong>Latent Dirichlet Allocation (LDA)</strong> to identify underlying topics or themes in the feedback data. This can provide deeper insights into the content and help analyze sentiment within specific topics.</p><pre># Create a CountVectorizer<br>vectorizer = CountVectorizer(max_features=1000, lowercase=True, stop_words=&#39;english&#39;, ngram_range=(1, 2))<br><br># Apply CountVectorizer to the processed feedback text<br>dtm = vectorizer.fit_transform(df[&#39;Processed_Feedback&#39;])<br><br># Perform LDA topic modeling<br>num_topics = 10  # Specify the desired number of topics<br>lda = LatentDirichletAllocation(n_components=num_topics, random_state=42)<br>lda.fit(dtm)<br><br># Get the top words for each topic<br>feature_names = vectorizer.get_feature_names()<br>top_words = 10  # Specify the number of top words to retrieve for each topic<br>for topic_idx, topic in enumerate(lda.components_):<br>    print(f&quot;Topic {topic_idx}:&quot;)<br>    print(&quot; &quot;.join([feature_names[i] for i in topic.argsort()[:-top_words - 1:-1]]))<br>    print()</pre><pre>Topic 0:<br>course lecturer difficult lecturer difficult hard time isnt teaching course difficult man<br><br>Topic 1:<br>course good lecturer nice terrible nice course easy course easy awful lecturer good<br><br>Topic 2:<br>course nice teaching lecturer method teaching method stress method lecturer nice teaching cool<br><br>Topic 3:<br>teaching code terrible course method teaching method bad love love code course taught<br><br>Topic 4:<br>time bad okay teaching teaching mode mode taught lecturer revision revision whats<br><br>Topic 5:<br>course make class dey especially dey make experience easy man pas<br><br>Topic 6:<br>akanni cool way god teach know really dry class dry know teach<br><br>Topic 7:<br>course easy awful wahala course hard hard good lecturer unit course unit<br><br>Topic 8:<br>lecturer course class course lecturer hate man wey plus lecturer good dey<br><br>Topic 9:<br>course lecturer god class student sha teaching coding like understand</pre><h3>Emotion Detection</h3><p>Identifying emotions in student feedback. The sentiment property of the TextBlob object to retrieve the sentiment scores which includes polarity (a value between -1 and 1 indicating the sentiment) and subjectivity (a value between 0 and 1 indicating the subjectivity of the text).<br><strong>Emotion Polarity</strong>: Emotion polarity measures the sentiment or emotional tone of a text. It indicates whether the text expresses a positive, negative, or neutral emotion. In the code provided, the polarity scores are obtained using the SentimentIntensityAnalyzer from NLTK. The polarity scores include values for positive, negative, and neutral sentiment. The sentiment polarity can help identify the overall sentiment or emotional tone of the feedback text.<br><strong>Emotion Subjectivity</strong>: Emotion subjectivity measures the degree of subjectivity or objectivity in the expression of emotions in a text. It indicates how much the text relies on personal opinions, beliefs, or experiences rather than factual or objective information. A higher subjectivity score suggests that the text is more influenced by personal perspectives or experiences.</p><pre>def calculate_emotions(text):<br>    blob = TextBlob(text)<br>    emotion_scores = blob.sentiment.polarity, blob.sentiment.subjectivity<br>    return emotion_scores<br><br># Apply emotion analysis to the feedback text<br>df[&#39;Emotion_Scores&#39;] = df[&#39;Processed_Feedback&#39;].apply(calculate_emotions)<br><br># Extract emotion scores for each emotion category<br>df[&#39;Emotion_Polarity&#39;] = df[&#39;Emotion_Scores&#39;].apply(lambda x: x[0])<br><br># assign emotion labels based on polarity values<br>df[&#39;Emotion_Label&#39;] = df[&#39;Emotion_Polarity&#39;].apply(lambda x: &#39;Positive&#39; if x &gt; 0 else &#39;Negative&#39; if x &lt; 0 else &#39;Neutral&#39;)<br><br># the resulting dataframe with emotion scores and labels<br>df[[&#39;Processed_Feedback&#39;, &#39;Emotion_Polarity&#39;, &#39;Emotion_Label&#39;]].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGUaeBEVX0ooiRr58gJnBA.jpeg" /><figcaption>Image by Author</figcaption></figure><h3>Exploratory Data Analysis</h3><p>Creating meaningful visualizations to gain insights and communicate findings effectively. Exploring different types of plots, charts, and graphs to showcase various aspects of the data and also analyzing the distribution of sentiment labels in the data to understand the overall sentiment polarity.</p><h4>Correlation Analysis</h4><p>Exploring the correlation between sentiment and other variables in the dataset to identify potential relationships.</p><pre>correlation_matrix = df[[&#39;Study Hours (per week)&#39;, &#39;Overall Satisfaction&#39;]].corr()<br><br>cmap = sns.diverging_palette(220, 10, as_cmap=True)<br>sns.heatmap(correlation_matrix, annot=True, fmt=&quot;.2f&quot;, cmap=cmap, vmin=-1, vmax=1, linewidths=0.5)<br>plt.title(&#39;Correlation between Study Hours and Overall Satisfaction&#39;)<br><br>for i in range(correlation_matrix.shape[0]):<br>    for j in range(correlation_matrix.shape[1]):<br>        if i != j:<br>            text = &#39;{:.2f}&#39;.format(correlation_matrix.iloc[i, j])<br>            plt.text(j + 0.5, i + 0.5, text, ha=&#39;center&#39;, va=&#39;center&#39;, color=&#39;black&#39;)<br><br>colorbar = plt.gca().collections[0].colorbar<br>colorbar.set_ticks([-1, -0.5, 0, 0.5, 1])<br>colorbar.set_ticklabels([&#39;Strong Negative&#39;, &#39;Negative&#39;, &#39;Neutral&#39;, &#39;Positive&#39;, &#39;Strong Positive&#39;])<br><br>plt.xlabel(&#39;Features&#39;)<br>plt.ylabel(&#39;Features&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*7ATiI-UZbyXNwq8s7pi7Cg.png" /><figcaption>Correlation between study hours and overall satisfaction.</figcaption></figure><pre>correlation_matrix = df[[&#39;Sentiment_Score&#39;, &#39;Overall Satisfaction&#39;]].corr()<br><br>cmap = sns.diverging_palette(220, 10, as_cmap=True)<br>sns.heatmap(correlation_matrix, annot=True, fmt=&quot;.2f&quot;, cmap=cmap, vmin=-1, vmax=1, linewidths=0.5)<br>plt.title(&#39;Correlation between Sentiment Score and Satisfaction&#39;)<br><br>for i in range(correlation_matrix.shape[0]):<br>    for j in range(correlation_matrix.shape[1]):<br>        if i != j:<br>            text = &#39;{:.2f}&#39;.format(correlation_matrix.iloc[i, j])<br>            plt.text(j + 0.5, i + 0.5, text, ha=&#39;center&#39;, va=&#39;center&#39;, color=&#39;black&#39;)<br><br>colorbar = plt.gca().collections[0].colorbar<br>colorbar.set_ticks([-1, -0.5, 0, 0.5, 1])<br>colorbar.set_ticklabels([&#39;Strong Negative&#39;, &#39;Negative&#39;, &#39;Neutral&#39;, &#39;Positive&#39;, &#39;Strong Positive&#39;])<br><br>plt.xlabel(&#39;Features&#39;)<br>plt.ylabel(&#39;Features&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*0e84qjOsaex03ljF2KlO_w.png" /><figcaption>Correlation Matrix</figcaption></figure><pre># Bar plot for Course Code<br>plt.figure(figsize=(10, 6))<br>color = sns.color_palette()[0]<br>order = df[&#39;Course Code&#39;].value_counts().index<br>ax = sns.countplot(data=df, x=&#39;Course Code&#39;, color=color, order=order)<br>plt.xlabel(&#39;Course Code&#39;)<br>plt.ylabel(&#39;Count of Feedback&#39;)<br>plt.title(&#39;Feedback Count by Course Code&#39;)<br>plt.xticks(rotation=45)<br>ax.bar_label(ax.containers[0], fmt=&#39;%.0f&#39;, label_type=&#39;edge&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*_Wc8imIix0oQwC9UIX4rfQ.png" /></figure><pre># Word cloud for Overall Feedback: Combine all feedback into a single string<br>all_feedback = &#39; &#39;.join(df[&#39;Processed_Feedback&#39;])<br><br>plt.figure(figsize=(10, 6))<br>wordcloud = WordCloud(width=800, height=400, background_color=&#39;white&#39;).generate(all_feedback)<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&#39;Word Cloud of Overall Feedback&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*JBqkuiLrewavNjjeF-XWaQ.png" /></figure><pre># Word cloud for Positive Feedback<br>data = &#39; &#39;.join(df[df[&#39;Processed_Feedback&#39;] == &#39;Positive&#39;][&#39;Processed_Feedback&#39;])<br><br>plt.figure(figsize=(10, 6))<br>wordcloud = WordCloud(width=800, height=400, background_color=&#39;white&#39;).generate(all_feedback)<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&#39;Word Cloud of Positive Feedback&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*JK40UsaiVGXmUfstS6DZLA.png" /></figure><pre># Word cloud for Negative Feedback<br>data = &#39; &#39;.join(df[df[&#39;Processed_Feedback&#39;] == &#39;Negative&#39;][&#39;Processed_Feedback&#39;])<br><br>plt.figure(figsize=(10, 6))<br>wordcloud = WordCloud(width=800, height=400, background_color=&#39;white&#39;).generate(all_feedback)<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&#39;Word Cloud of Negative Feedback&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*a6mY4BbOfWR9oyuGk0U1XA.png" /></figure><pre># Word cloud for Neutral Feedback<br>data = &#39; &#39;.join(df[df[&#39;Processed_Feedback&#39;] == &#39;Neutral&#39;][&#39;Processed_Feedback&#39;])<br><br>plt.figure(figsize=(10, 6))<br>wordcloud = WordCloud(width=800, height=400, background_color=&#39;white&#39;).generate(all_feedback)<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&#39;Word Cloud of Neutral Feedback&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*beWE5cyIIOxgiEEQnsdPHQ.png" /></figure><pre># Bar plot for Sentiment<br>plt.figure(figsize=(8, 6))<br>color = sns.color_palette()[0]<br>order = df[&#39;Sentiment_Label&#39;].value_counts().index<br>ax = sns.countplot(data=df, x=&#39;Sentiment_Label&#39;, color=color, order=order)<br>plt.xlabel(&#39;Sentiment&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Distribution of Sentiments&#39;)<br>ax.bar_label(ax.containers[0], fmt=&#39;%.0f&#39;, label_type=&#39;edge&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*95mYPm-79H0vF-N-T3FQoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*FDmd59PueBhBBuSuf2V1kQ.png" /></figure><pre># Bar plot for Previous Experience<br>plt.figure(figsize=(8, 6))<br>color = sns.color_palette()[0]<br>ax = sns.countplot(data=df, x=&#39;Previous Experience&#39;, color=color)<br>plt.xlabel(&#39;Previous Experience&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Feedback Count by Previous Experience&#39;)<br>ax.bar_label(ax.containers[0], fmt=&#39;%.0f&#39;, label_type=&#39;edge&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*GULZdsbT7o1m5MSOaKyArQ.png" /></figure><pre># Pie chart for Gender distribution<br>counts = df[&#39;Gender&#39;].value_counts()<br>labels = [f&quot;{gender}\n{count / len(df) * 100:.1f}%&quot; for gender, count in counts.items()]<br><br>fig, ax = plt.subplots()<br>ax.pie(counts, labels=labels, startangle=50, counterclock=False, pctdistance=0.8, labeldistance=1.2)<br>centre_circle = plt.Circle((0,0),0.70,fc=&#39;white&#39;)<br>fig.gca().add_artist(centre_circle)<br>ax.set_title(&#39;Gender Distribution&#39;, fontsize=16, loc=&#39;left&#39;, pad=30)<br>ax.axis(&#39;equal&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*GWwHJcJIpqlnt6xY1rEaJg.png" /></figure><pre># Pie chart for Attendance<br>counts = df[&#39;Attendance&#39;].value_counts()<br>labels = [f&quot;{attendance}\n{count / len(df) * 100:.1f}%&quot; for attendance, count in counts.items()]<br><br>fig, ax = plt.subplots()<br>ax.pie(counts, labels=labels, startangle=50, counterclock=False, pctdistance=0.8, labeldistance=1.2)<br>centre_circle = plt.Circle((0,0),0.70,fc=&#39;white&#39;)<br>fig.gca().add_artist(centre_circle)<br>ax.set_title(&#39;Distribution of Attendance&#39;, fontsize=16, loc=&#39;left&#39;, pad=30)<br>ax.axis(&#39;equal&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*JOThb5dmQZnWCBSux97nHQ.png" /></figure><pre># Bar plot for Course Difficulty<br>plt.figure(figsize=(10, 6))<br>color = sns.color_palette()[0]<br>order = [&#39;Easy&#39;, &#39;Moderate&#39;, &#39;Challenging&#39;, &#39;Difficult&#39;]<br>ax = sns.countplot(data=df, x=&#39;Course Difficulty&#39;, color=color, order=order)<br>plt.xlabel(&#39;Course Difficulty&#39;)<br>plt.ylabel(&#39;Count of Feedback&#39;)<br>plt.title(&#39;Feedback Count by Course Difficulty&#39;)<br>ax.bar_label(ax.containers[0], fmt=&#39;%.0f&#39;, label_type=&#39;edge&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*FAt1Zbt1iClwy4O1tJpZPA.png" /></figure><pre># Histogram for Study Hours (per week)<br>plt.figure(figsize=(10, 6))<br>color = sns.color_palette()[0]<br>ax = sns.histplot(data=df, x=&#39;Study Hours (per week)&#39;, bins=20, color=color)<br>plt.xlabel(&#39;Study Hours (per week)&#39;)<br>plt.ylabel(&#39;Count of Students&#39;)<br>plt.title(&#39;Distribution of Study Hours&#39;)<br>ax.bar_label(ax.containers[0], fmt=&#39;%.0f&#39;, label_type=&#39;edge&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*sBoD5UALQ4yVE5wbSSXX2w.png" /></figure><pre># Histogram for Overall Satisfaction<br>plt.figure(figsize=(10, 6))<br>sns.histplot(data=df, x=&#39;Overall Satisfaction&#39;, bins=30)<br>plt.xlabel(&#39;Overall Satisfaction&#39;)<br>plt.ylabel(&#39;Count of Students&#39;)<br>plt.title(&#39;Distribution of Overall Satisfaction&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*85OCROWApxFWgr_hozD6cQ.png" /></figure><pre># Word Frequency Analysis<br>from collections import Counter<br>word_frequency = Counter(&quot; &quot;.join(df[&#39;Processed_Feedback&#39;]).split()).most_common(30)<br>plt.figure(figsize=(20, 10))<br>color = sns.color_palette()[0]<br>ax = sns.barplot(x=[word[1] for word in word_frequency], y=[word[0] for word in word_frequency], color=color)<br>ax.bar_label(ax.containers[0], fmt=&#39;%.0f&#39;, label_type=&#39;edge&#39;)<br>plt.xlabel(&#39;Frequency&#39;)<br>plt.ylabel(&#39;Word&#39;)<br>plt.title(&#39;Top 30 Most Frequent Words&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUpXB3T_Ntq3TBct5SGivA.png" /></figure><pre># Sentiment Box Plots<br>plt.figure(figsize=(10, 6))<br>color = sns.color_palette()[0]<br>sns.boxplot(data=df, x=&#39;Course Code&#39;, y=&#39;Sentiment_Score&#39;, color=color)<br>plt.xlabel(&#39;Course Code&#39;)<br>plt.ylabel(&#39;Sentiment Score&#39;)<br>plt.title(&#39;Sentiment Distribution by Course Code&#39;)<br>plt.xticks(rotation=45)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*--oNpIMLU88-uUaBb6pImQ.png" /></figure><pre># Bar plot for Course Difficulty<br>plt.figure(figsize=(10, 6))<br>hue_order = [&#39;Easy&#39;, &#39;Moderate&#39;, &#39;Challenging&#39;, &#39;Difficult&#39;]<br>sns.countplot(data=df, x=&#39;Course Code&#39;, hue=&#39;Course Difficulty&#39;, palette=&#39;Blues_r&#39;, hue_order=hue_order)<br>plt.xlabel(&#39;Course Difficulty&#39;)<br>plt.ylabel(&#39;Count of Feedback&#39;)<br>plt.title(&#39;Feedback Count by Course Difficulty&#39;)<br>plt.legend(loc=1)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*q3jUCFAHEk87kJYVvrPHWA.png" /></figure><pre># Bar plot for Course Code distribution by Sentiment distribution<br>plt.figure(figsize=(10, 6))<br>hue_order = [&#39;Positive&#39;, &#39;Neutral&#39;, &#39;Negative&#39;]<br>sns.countplot(data=df, x=&#39;Course Code&#39;, hue=&#39;Sentiment_Label&#39;, palette=&#39;Blues_r&#39;, hue_order=hue_order)<br>plt.xlabel(&#39;Course Code&#39;)<br>plt.ylabel(&#39;Count of Feedback&#39;)<br>plt.title(&#39;Course Code distribution by Sentiment distribution&#39;)<br>plt.legend(loc=1)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*0YK_T-C2C7ND-RIEhmftCg.png" /></figure><pre># Sentiment Distribution by Course Difficulty<br>plt.figure(figsize=(10, 6))<br>hue_order = [&#39;Positive&#39;, &#39;Neutral&#39;, &#39;Negative&#39;]<br>order = [&#39;Easy&#39;, &#39;Moderate&#39;, &#39;Challenging&#39;, &#39;Difficult&#39;]<br>sns.countplot(data=df, x=&#39;Course Difficulty&#39;, hue=&#39;Sentiment_Label&#39;, <br>              palette=&#39;Blues_r&#39;, hue_order=hue_order, order=order)<br>plt.xlabel(&#39;Course Difficulty&#39;)<br>plt.ylabel(&#39;Count of Feedback&#39;)<br>plt.title(&#39;Sentiment Distribution by Course Difficulty&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*UuyTGCZ4uYgaU07kejqL4g.png" /></figure><pre># Sentiment Distribution by Gender<br>plt.figure(figsize=(10, 6))<br>hue_order = [&#39;Positive&#39;, &#39;Neutral&#39;, &#39;Negative&#39;]<br>sns.countplot(data=df, x=&#39;Gender&#39;, hue=&#39;Sentiment_Label&#39;, hue_order=hue_order, palette=&#39;Blues_r&#39;)<br>plt.xlabel(&#39;Gender&#39;)<br>plt.ylabel(&#39;Count of Feedback&#39;)<br>plt.title(&#39;Sentiment Distribution by Gender&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*p8KCitjl4gPnE0U-cMb8Ig.png" /></figure><pre># Word Count distribution by course difficulty<br>plt.figure(figsize=(10, 6))<br>order = [&#39;Easy&#39;, &#39;Moderate&#39;, &#39;Challenging&#39;, &#39;Difficult&#39;]<br>color = sns.color_palette()[0]<br>sns.boxplot(data=df, x=&#39;Course Difficulty&#39;, y=&#39;Word_Count&#39;, color=color, order=order)<br>plt.xlabel(&#39;Course Difficulty&#39;)<br>plt.ylabel(&#39;Word Count&#39;)<br>plt.title(&#39;Distribution of Word Count for different levels of Course Difficulty&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*TqP5jF60C967blrLUToPtA.png" /></figure><pre># Distribution of Study Hours (per week) and Overall Satisfaction<br>plt.figure(figsize=(10, 6))<br>color = sns.color_palette()[0]<br>sns.lineplot(data=df, x=&#39;Study Hours (per week)&#39;, y=&#39;Overall Satisfaction&#39;, color=color, ci=None)<br>plt.xlabel(&#39;Study Hours (per week)&#39;)<br>plt.ylabel(&#39;Overall Satisfaction&#39;)<br>plt.title(&#39;Distribution of Study Hours (per week) and Overall Satisfaction&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*RDvcnUFW1WOwgnKsJ6m0sQ.png" /></figure><pre># Sentiment vs. Overall Satisfaction<br>plt.figure(figsize=(10, 6))<br>color = sns.color_palette()[0]<br>sns.scatterplot(x=&#39;Sentiment_Score&#39;, y=&#39;Overall Satisfaction&#39;, data=df, color=color)<br>plt.xlabel(&#39;Sentiment Score&#39;)<br>plt.ylabel(&#39;Overall Satisfaction&#39;)<br>plt.title(&#39;Sentiment score vs. Overall Satisfaction&#39;)<br>plt.xticks(np.arange(-1, 1.1, 0.5))<br>plt.yticks(np.arange(0, 11))<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*wiPKPt3JVvm3ZTgCQWxdug.png" /></figure><pre># Sentiment score Distribution by Course code<br>plt.figure(figsize=(10, 6))<br>color = sns.color_palette()[0]<br>sns.relplot(data=df, x=&#39;Course Code&#39;,y = &#39;Sentiment_Score&#39;, color=color, kind=&#39;scatter&#39;)<br>plt.xlabel(&#39;Course code&#39;)<br>plt.ylabel(&#39;Sentiment Score&#39;)<br>plt.title(&#39;Sentiment score vs Course code distribution&#39;)<br>plt.xticks(rotation=45)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*p74uIih3qn84IVJ_stcHIg.png" /></figure><pre># correlation matrix of all variables in the data<br>correlation_matrix = df.corr()<br><br>plt.figure(figsize=[20, 6])<br>cmap = sns.diverging_palette(220, 10, as_cmap=True)<br>sns.heatmap(correlation_matrix, annot=True, fmt=&quot;.2f&quot;, cmap=cmap, vmin=-1, vmax=1, linewidths=0.5)<br>plt.title(&#39;Correlation between variables in the dataset&#39;)<br><br>for i in range(correlation_matrix.shape[0]):<br>    for j in range(correlation_matrix.shape[1]):<br>        if i != j:<br>            text = &#39;{:.2f}&#39;.format(correlation_matrix.iloc[i, j])<br>            plt.text(j + 0.5, i + 0.5, text, ha=&#39;center&#39;, va=&#39;center&#39;, color=&#39;black&#39;)<br><br>colorbar = plt.gca().collections[0].colorbar<br>colorbar.set_ticks([-1, -0.5, 0, 0.5, 1])<br>colorbar.set_ticklabels([&#39;Strong Negative&#39;, &#39;Negative&#39;, &#39;Neutral&#39;, &#39;Positive&#39;, &#39;Strong Positive&#39;])<br><br>plt.xlabel(&#39;Features&#39;)<br>plt.ylabel(&#39;Features&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeQfi7NU5Z05r28jx4FAZA.png" /></figure><pre>sns.set(style=&#39;ticks&#39;)<br>sns.pairplot(data=df, vars=[&#39;Study Hours (per week)&#39;, &#39;Overall Satisfaction&#39;, <br>                            &#39;Sentiment_Score&#39;], hue=&#39;Previous Experience&#39;, markers=&#39;o&#39;)<br>plt.suptitle(&#39;Study Hours (per week), Overall Satisfaction and Sentiment Score Distributions by Previous Experience&#39;,<br>             y=1.08)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*2AG3Lpw3Ts9Ipv7Ih_AC1g.png" /></figure><h3>Machine Learning Model</h3><p>I then built a ML model using XGBoost Classifier for predicting sentiment labels.</p><h4>XGBoost Classifier</h4><pre>X = df[&#39;Processed_Feedback&#39;]<br>y = df[&#39;Sentiment_Label&#39;]<br><br>print(X.shape, y.shape)<br><br>#(100,) (100,)<br><br>le = LabelEncoder()<br>y_encoded = le.fit_transform(y)<br>print(&#39;Encoded Target Labels:&#39;)<br>print(y_encoded, &#39;\n&#39;)<br><br># get mapping for each label<br>le_name_mapping = dict(zip(le.classes_, le.transform(le.classes_)))<br>print(&#39;Label Mappings:&#39;)<br>print(le_name_mapping)</pre><pre>Encoded Target Labels:<br>[1 1 0 1 1 1 2 1 1 2 1 0 1 0 1 2 0 0 0 1 1 2 0 0 1 1 2 1 1 0 2 1 1 1 1 2 0<br> 2 0 1 2 1 0 2 2 0 2 0 1 0 1 0 1 0 2 1 2 1 1 1 1 2 0 2 1 1 1 2 2 0 2 1 1 2<br> 2 0 2 1 0 2 2 0 2 2 0 2 1 1 1 2 2 1 2 1 2 2 0 1 2 2] <br><br>Label Mappings:<br>{&#39;Negative&#39;: 0, &#39;Neutral&#39;: 1, &#39;Positive&#39;: 2}</pre><p><strong>Using random train and test subsets.</strong></p><pre># Spliting the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y_encoded, test_size=0.2, random_state=42)<br><br># Preprocessor<br>preprocessor = Pipeline([<br>    (&#39;bow&#39;, CountVectorizer(stop_words=&#39;english&#39;)),<br>    (&#39;tfidf&#39;, TfidfTransformer()),<br>])<br><br># XGBoost Classifier<br>xgb_classifier = xgb.XGBClassifier(<br>    learning_rate=0.1,<br>    max_depth=6,<br>    n_estimators=80,<br>    use_label_encoder=False,<br>    objective=&#39;multi:softmax&#39;,<br>    eval_metric=&#39;merror&#39;,<br>    num_class=3<br>)<br><br># Pipeline<br>pipe = Pipeline([<br>    (&#39;preprocessor&#39;, preprocessor),<br>    (&#39;model&#39;, xgb_classifier),<br>])<br><br># Hyperparameter Tuning<br>param_grid = {<br>    &#39;model__learning_rate&#39;: [0.1, 0.01, 0.001],<br>    &#39;model__max_depth&#39;: [6, 8, 10],<br>    &#39;model__n_estimators&#39;: [80, 100, 120],<br>}<br>grid_search = GridSearchCV(pipe, param_grid, cv=5)<br>grid_search.fit(X_train, y_train)<br>best_params = grid_search.best_params_<br>print(&#39;Best parameters:&#39;, best_params)<br><br># Fit and Evaluate on Testing Set<br>pipe.set_params(**best_params)<br>pipe.fit(X_train, y_train)<br>y_pred = pipe.predict(X_test)<br>acc = accuracy_score(y_test, y_pred)<br>print(&#39;Testing Accuracy:&#39;, acc)</pre><pre>Best parameters: {&#39;model__learning_rate&#39;: 0.01, &#39;model__max_depth&#39;: 6, &#39;model__n_estimators&#39;: 80}<br>Testing Accuracy: 0.75</pre><p><strong>Using Cross Validation.</strong></p><pre># Preprocessor<br>preprocessor = Pipeline([<br>    (&#39;bow&#39;, CountVectorizer(stop_words=&#39;english&#39;)),<br>    (&#39;tfidf&#39;, TfidfTransformer()),<br>])<br><br># XGBoost Classifier<br>xgb_classifier = xgb.XGBClassifier(<br>    learning_rate=0.1,<br>    max_depth=6,<br>    n_estimators=80,<br>    use_label_encoder=False,<br>    objective=&#39;multi:softmax&#39;,<br>    eval_metric=&#39;merror&#39;,<br>    num_class=3<br>)<br><br># Pipeline<br>pipe = Pipeline([<br>    (&#39;preprocessor&#39;, preprocessor),<br>    (&#39;model&#39;, xgb_classifier),<br>])<br><br># Hyperparameter Tuning with Cross-Validation<br>param_grid = {<br>    &#39;model__learning_rate&#39;: [0.1, 0.01, 0.001],<br>    &#39;model__max_depth&#39;: [6, 8, 10],<br>    &#39;model__n_estimators&#39;: [80, 100, 120],<br>}<br>grid_search = GridSearchCV(pipe, param_grid, cv=5)<br>grid_search.fit(X, y_encoded)<br>best_params = grid_search.best_params_<br>print(&#39;Best parameters:&#39;, best_params)<br><br># Fit and Evaluate using Cross-Validation<br>pipe.set_params(**best_params)<br>cv_scores = cross_val_score(pipe, X, y_encoded, cv=5)<br>mean_cv_score = cv_scores.mean()<br>print(&#39;Cross-validation accuracy:&#39;, mean_cv_score)</pre><pre>Best parameters: {&#39;model__learning_rate&#39;: 0.01, &#39;model__max_depth&#39;: 8, &#39;model__n_estimators&#39;: 100}<br>Cross-validation accuracy: 0.6799999999999999</pre><p>I also created a <a href="https://app.powerbi.com/links/AupqjRXtlh?ctid=66b3f0c2-8bc6-451e-9603-986f618ae682&amp;pbi_source=linkShare&amp;bookmarkGuid=1adc0a91-ec20-476b-94ad-feef4f3f0ec1">Power BI report</a> to communicate my findings which can be seen in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBS2POwv3GKzKd7eZs_oFg.jpeg" /><figcaption>Power BI report to communicate insights.</figcaption></figure><h3>Conclusion</h3><p>In conclusion, the sentiment analysis of student feedback in engineering education has yielded valuable insights and recommendations for improvement. The sentiment distribution indicates a majority of Neutral feedback (suggesting a balanced perspective or lack of strong sentiment towards their educational experience) followed by Positive and Negative sentiments. The prevalence of Neutral sentiments in the student feedback sentiment analysis may also indicate that students are providing objective observations or factual statements without expressing a clear positive or negative sentiment. Furthermore, it was observed that a majority of students had no previous experience, adding to the context of the analysis.</p><p>Gender disparity shows both male and female students expressing negative sentiments, with females expressing more positive sentiments and males having more neutral sentiments which highlight the importance of considering gender as a factor in understanding and addressing the sentiment dynamics in student feedback.</p><p>Variation across courses highlights specific strengths or areas for improvement, with CPE 321 being the most challenging. CPE 341 and CPE 311 received lower sentiment scores, while CPE 311 had the highest sentiment score. It was also noted that the easy courses had the most number of positive sentiments. Correlations reveal the alignment of sentiment score with overall satisfaction and perfect correlation with emotion polarity.</p><p>Additionally, the high correlation between study hours and overall satisfaction implies that the amount of time students dedicate to studying may positively influence their overall satisfaction with the courses they take.</p><p>Topic modeling uncovers key themes discussed by students. The sentiment analysis serves as a foundation for continuous improvement in engineering education with targeted interventions required for courses with more negative sentiments, particularly CPE 321 ensuring a fulfilling and satisfactory learning conditions for the students.</p><p>Lastly, I built a model which achieved impressive accuracy rates of 68% in cross-validation and 75% in testing. This project has deepened my understanding of ML and fueled my passion for using technology to understand and predict human emotions.</p><blockquote>Thanks for reading🤓. Check out my <a href="https://github.com/Abdulraqib20/Sentiment-Analysis-with-Student-Feedback">GitHub repo</a> where you can find the code and resources related to this project and explore other projects I have worked on. You can also interact with the Power BI Dashboard <a href="https://app.powerbi.com/links/AupqjRXtlh?ctid=66b3f0c2-8bc6-451e-9603-986f618ae682&amp;pbi_source=linkShare&amp;bookmarkGuid=1adc0a91-ec20-476b-94ad-feef4f3f0ec1">here</a>. If you found this analysis insightful and informative, please show your support by liking, commenting, and following. Your feedback and suggestions are valuable and will help me improve and deliver more meaningful content in the future. Cheers!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55a913dd7967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WhatsApp Chats Analysis with Python]]></title>
            <link>https://medium.com/@abdulraqibshakir03/whatsapp-chats-analysis-with-python-fe7a220f0796?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe7a220f0796</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 12:14:04 GMT</pubDate>
            <atom:updated>2023-08-01T20:02:57.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bwUZXoYDtHHLKWol" /><figcaption>Photo by <a href="https://unsplash.com/@alexbemore?utm_source=medium&amp;utm_medium=referral">Alexander Shatov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>WhatsApp chats have become a staple in our uni life!</p><p>📱🎓 Ever wondered what insights can be uncovered from those messages? Python and data analysis offer exciting insights like most active chatters, hot topics, popular discussions, most active times and more! In this article, I’ll explore how to analyze WhatsApp chats and unlock valuable information from the convo history.</p><h3>Getting the data</h3><p>I used my university’s class WhatsApp group as a case study to provide interesting insights into how my classmates interact and communicate with each other outside of the classroom. To export the chat history, not including video or photos, I followed the steps below.</p><ol><li>Open the WhatsApp chat that you want to export.</li><li>Tap on the three dots on the top right corner of the chat screen.</li><li>Select “More” and then “Export Chat” from the drop-down menu.</li><li>Choose “Without Media” to exclude media files such as photos and videos from the export.</li><li>Choose the preferred method of sharing the exported chat file, such as sending it to your email or even just saving it to your device.</li><li>Once the file is saved, you can access it and use it for further analysis using Python.</li></ol><h3>Importing libraries and packages</h3><p>I’ll be utilizing various libraries and packages, such as Pandas, Matplotlib, and NLTK, which can help with tasks such as data manipulation, visualization, and natural language processing. Therefore, before diving into the analysis, it’s important to make sure these libraries are installed and imported correctly.</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>sns.set_theme(style=&#39;white&#39;)<br>import plotly.express as px<br><br>import re<br>from collections import Counter<br>import emoji<br>import collections<br>import datetime<br>from os import path<br>from PIL import Image<br>from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator<br><br>import nltk <br>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br>from nltk.probability import FreqDist<br><br>import warnings<br>warnings.simplefilter(action=&#39;ignore&#39;, category=UserWarning)</pre><h3>Creating the dataframe from the text file</h3><p>Once we have the text file containing the exported WhatsApp chat data, we can create a Pandas DataFrame in Python to organize the data in a structured format. This will allow us to easily manipulate and analyze the chat data using various Python libraries and techniques.</p><pre># Read chat data from text file<br>with open(&#39;WhatsApp Chat with CPE 300L.txt&#39;, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>    chat_data = f.readlines()<br><br># Define regular expressions to extract data<br>message_regex = re.compile(r&#39;^(\d{2}\/\d{2}\/\d{4}, \d{2}:\d{2}) - ([^:]+): (.+)$&#39;)<br>system_message_regex = re.compile(r&#39;^(\d{2}\/\d{2}\/\d{4}, \d{2}:\d{2}) - (.+)$&#39;)<br>media_message_regex = re.compile(r&#39;^(\d{2}\/\d{2}\/\d{4}, \d{2}:\d{2}) - ([^:]+) attached (\S+) \(.*\)$&#39;)<br><br># Initialize data lists<br>dates = []<br>times = []<br>members = []<br>messages = []<br>message_types = []<br>message_lengths = []<br>reaction_counts = []<br>word_counts = []<br>hashtags = []<br>mentions = []<br>emojis = []<br><br># Loop through chat data and extract required information<br>for line in chat_data:<br>    # Check if line contains a message<br>    match = message_regex.match(line)<br>    if match:<br>        dates.append(match.group(1)[:10])<br>        times.append(match.group(1)[11:])<br>        member = emoji.demojize(match.group(2)).strip()<br>        members.append(member)<br>        messages.append(match.group(3))<br>        message_types.append(&#39;text&#39;)<br>        message_lengths.append(len(match.group(3)))<br>        reaction_counts.append(0)<br>        word_counts.append(len(match.group(3).split()))<br>        hashtags.append(re.findall(r&#39;#(\w+)&#39;, match.group(3)))<br>        mentions.append(re.findall(r&#39;@(\w+)&#39;, match.group(3)))<br>        emojis.append(re.findall(r&#39;[\U0001F600-\U0001F650]&#39;, match.group(3)))<br>    else:<br>        # Check if line contains a system message<br>        match = system_message_regex.match(line)<br>        if match:<br>            dates.append(match.group(1)[:10])<br>            times.append(match.group(1)[11:])<br>            members.append(&#39;System&#39;)<br>            messages.append(match.group(2))<br>            message_types.append(&#39;system&#39;)<br>            message_lengths.append(len(match.group(2)))<br>            reaction_counts.append(0)<br>            word_counts.append(len(match.group(2).split()))<br>            hashtags.append([])<br>            mentions.append([])<br>            emojis.append([])<br>        else:<br>            # Check if line contains a media message<br>            match = media_message_regex.match(line)<br>            if match:<br>                dates.append(match.group(1)[:10])<br>                times.append(match.group(1)[11:])<br>                member = emoji.demojize(match.group(2)).strip()<br>                members.append(member)<br>                messages.append(match.group(3))<br>                message_types.append(&#39;media&#39;)<br>                message_lengths.append(0)<br>                reaction_counts.append(0)<br>                word_counts.append(0)<br>                hashtags.append([])<br>                mentions.append([])<br>                emojis.append([])<br><br># Create pandas dataframe from extracted data<br>df = pd.DataFrame({<br>    &#39;date&#39;: dates,<br>    &#39;time&#39;: times,<br>    &#39;member&#39;: members,<br>    &#39;message&#39;: messages,<br>    &#39;message_type&#39;: message_types,<br>    &#39;message_length&#39;: message_lengths,<br>    &#39;reaction_count&#39;: reaction_counts,<br>    &#39;word_count&#39;: word_counts,<br>    &#39;hashtags&#39;: hashtags,<br>    &#39;mentions&#39;: mentions,<br>    &#39;emojis&#39;: emojis<br>})</pre><h3><strong>Further exploration</strong></h3><p>Dimension of the data (number of rows, number of columns). The data has 24318 rows and 11 columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*fc0Mio4PNlGw7KsSN6Cklw.jpeg" /></figure><p>With the head() pandas method, we can see some records from the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8De-2vIU-wGkjx70Nm4jA.jpeg" /><figcaption>The first few records from the dataset.</figcaption></figure><p>I’m going to drop some rows as they are irrelevant to the analysis.</p><pre>df.drop([0, 1, 2, 3, 4], axis=0, inplace=True)<br>df.reset_index(drop=True, inplace=True)</pre><p>Identifying all the unique members or participants of the WhatsApp group chat using pandas unique() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWx-gLac4NvSC7bzTOgD0A.jpeg" /><figcaption>All the members of the group.</figcaption></figure><p>Some of the members’ name are incorrect. I will make changes to this.</p><pre># rename incorrect member names<br><br>replace_dict = {<br>    &#39;System&#39;: &#39;System messages&#39;,<br>    &#39;Queen Lizzy :princess:&#39;: &#39;Queen Lizzy&#39;,<br>    &#39;Ahmed Abubakar:face_with_medical_mask:&#39;: &#39;Ahmed&#39;,<br>    &#39;Aishort&#39;: &#39;Aisha&#39;,<br>    &#39;ViNe:keycap_6::keycap_9:&#39;: &#39;ViNe 69&#39;,<br>    &#39;Real John :soccer_ball:&#39;: &#39;John&#39;,<br>    &#39;+234 816 440 8811&#39;: &#39;Abdulmalik&#39;,<br>    &#39;+234 708 310 7624&#39;: &#39;Inioluwa&#39;,<br>    &#39;Khaleesi:crown::princess:&#39;: &#39;Khaleesi&#39;,<br>    &#39;Abdulrahman :glasses:&#39;: &#39;Abdulrahman&#39;,<br>    &#39;Ayotunde Martins&#39;: &#39;Martins&#39;,<br>    &#39;Augustine :soccer_ball:&#39;: &#39;Augustine&#39;,<br>    &#39;Kenny Habeeb&#39;: &#39;Kenny&#39;,<br>    &#39;Abdulraqib&#39;: &#39;Raqib&#39;,<br>    &#39;Peace :face_with_medical_mask:&#39;: &#39;Peace&#39;,<br>    &#39;Nelson Isralia&#39;: &#39;Nelson&#39;,<br>    &#39;Dami&#39;: &#39;Dammy&#39;,<br>    &#39;Mayowa Solomon&#39;: &#39;Mayowa&#39;,<br>    &#39;Blurryface:smiling_face_with_sunglasses:&#39;: &#39;Blurryface&#39;,<br>    &#39;Femi Clinton&#39;: &#39;Femi&#39;,<br>    &#39;+234 816 892 3626&#39;: &#39;Abdulbasit&#39;,<br>    &#39;Scholar Mukhtar&#39;: &#39;Mukhtar&#39;,<br>    &#39;+234 701 897 1552&#39;: &#39;Maryam&#39;,<br>    &#39;Nerry Kylen&#39;: &#39;Nerry&#39;<br>}<br>df[&#39;member&#39;] = df[&#39;member&#39;].replace(replace_dict)</pre><p>Now let&#39;s check them again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4jq4gZ3pthw-FlWDISTew.jpeg" /><figcaption>All members of the group.</figcaption></figure><h3><strong>Quick Stats.</strong></h3><pre>def split_count(text):<br><br>    emoji_list = []<br>    data = re.findall(r&#39;[^\s\u1f300-\u1f5ff]&#39;, text)<br>    for word in data:<br>        if any(char in emoji.distinct_emoji_list(text) for char in word):<br>            emoji_list.append(word)<br><br>    return emoji_list<br><br>total_messages = df.shape[0]<br>avg_message_length = df[&#39;message_length&#39;].mean()<br>media_messages = df[df[&#39;message&#39;] == &#39;&lt;Media omitted&gt;&#39;].shape[0]<br>df[&quot;emoji&quot;] = df[&quot;message&quot;].apply(split_count)<br>emojis = sum(df[&#39;emoji&#39;].str.len())<br>URLPATTERN = r&#39;(https?://\S+)&#39;<br>df[&#39;urlcount&#39;] = df.message.apply(lambda x: re.findall(URLPATTERN, x)).str.len()<br>links = np.sum(df.urlcount)<br><br>print(&quot;Stats&quot;)<br>print(&quot;Messages:&quot;, total_messages)<br>print(&#39;Average message length:&#39;, avg_message_length)<br>print(&quot;Media messages:&quot;, media_messages)<br>print(&quot;Emojis:&quot;, emojis)<br>print(&quot;Links:&quot;, links)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*Q55lpu6CB30eErrmu93vtw.jpeg" /></figure><p><strong>Messages sent messages sent per member, words per message,<br>emojis sent per message links sent per message and other stats.</strong></p><pre># Calculate messages sent per member<br>messages_sent = df.groupby(&#39;member&#39;)[&#39;message&#39;].count()<br><br># Calculate words per message<br>df[&#39;words_per_message&#39;] = df[&#39;message&#39;].apply(lambda x: len(x.split()) if isinstance(x, str) else 0)<br>words_per_message = df.groupby(&#39;member&#39;)[&#39;words_per_message&#39;].mean()<br><br># Calculate emojis sent per message<br>df[&#39;emojis_per_message&#39;] = df[&#39;emojis&#39;].apply(lambda x: len(x) if isinstance(x, str) else 0)<br>emojis_per_message = df.groupby(&#39;member&#39;)[&#39;emojis_per_message&#39;].mean()<br><br># Calculate links sent per message<br>df[&#39;links_per_message&#39;] = df[&#39;message&#39;].apply(lambda x: len(re.findall(r&#39;http\S+&#39;, x)) if isinstance(x, str) else 0)<br>links_per_message = df.groupby(&#39;member&#39;)[&#39;links_per_message&#39;].mean()<br><br># Combine stats into a single dataframe<br>stats_df = pd.concat([messages_sent, words_per_message, emojis_per_message, links_per_message], axis=1)<br>stats_df.columns = [&#39;messages_sent&#39;, &#39;words_per_message&#39;, &#39;emojis_per_message&#39;, &#39;links_per_message&#39;]<br><br># Sort by messages sent in descending order<br>stats_df = stats_df.sort_values(&#39;messages_sent&#39;, ascending=False)<br><br># Print results<br>stats_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*z3hhDHKspfMCObRPVSeqcw.jpeg" /><figcaption>Image by Author</figcaption></figure><h3><strong>Frequently used words.</strong></h3><p>Most commonly used words in the group.</p><pre># Filter out messages that contain media files<br>non_media = df[~df[&#39;message&#39;].str.contains(&#39;&lt;Media omitted&gt;&#39;)]<br><br># Extract all messages from the DataFrame and join them into a single string<br>all_messages = &#39; &#39;.join(non_media[&#39;message&#39;].astype(str).tolist())<br><br># Convert the string into a list of words<br>all_words = all_messages.split()<br><br># Count the frequency of each word using Python&#39;s Counter object<br>word_freq = Counter(all_words)<br><br># Select the top 10 most frequent words and their counts<br>top_words = word_freq.most_common(10)<br><br># Extract the words and counts into separate lists<br>words = [word[0] for word in top_words]<br>counts = [count[1] for count in top_words]<br><br># Create a bar chart of the top 10 most frequent words<br>plt.bar(words, counts)<br>plt.title(&#39;Top 10 Most Frequent Words (Excluding Media)&#39;)<br>plt.xlabel(&#39;Words&#39;)<br>plt.ylabel(&#39;Counts&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*3Z0pdZB6ElMn9L1x1IiP2Q.png" /><figcaption>Top 10 most frequently used words</figcaption></figure><h3><strong>Emojis.</strong></h3><p>In addition to words, I included emojis to gain insights into the most frequently used emojis and their corresponding meanings in the WhatsApp chat.</p><p>Frequency of emojis</p><pre>total_emojis_list = list([a for b in df.emojis for a in b])<br>emoji_dict = dict(collections.Counter(total_emojis_list))<br>emoji_dict = sorted(emoji_dict.items(), key=lambda x: x[1], reverse=True)<br><br>emoji_df = pd.DataFrame(emoji_dict, columns=[&#39;Emoji&#39;, &#39;Frequency&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*UDnnSpB2_ECXv6yahVbJ4g.jpeg" /><figcaption>The laughing emoji is the most commonly used emoji</figcaption></figure><p>Distribution of emojis</p><pre># Define custom colors for the pie chart<br>colors = [&#39;#ffd700&#39;, &#39;#ff69b4&#39;, &#39;#1e90ff&#39;, &#39;#ff8c00&#39;, &#39;#00ced1&#39;]<br><br># Create a pie chart of the emoji frequencies with custom colors<br>fig = px.pie(emoji_df, values=&#39;Frequency&#39;, names=&#39;Emoji&#39;, title=&#39;Overall emoji distribution&#39;, color_discrete_sequence=colors)<br>fig.update_traces(textposition=&#39;inside&#39;, textinfo=&#39;percent+label&#39;)<br>fig.update_layout(width=800, height=500, showlegend=True)<br><br># Show the plot<br>fig.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*c0pnvqozE1MTQnTh4UgDZQ.png" /><figcaption>Overall emoji distribution.</figcaption></figure><h3>Word Cloud.</h3><p>Creating a word cloud is a fun and informative way to visualize the most commonly used words in the chat, giving a better understanding of the overall tone and topics of conversation.</p><pre># Remove messages containing &quot;Media omitted&quot;<br>x = df[~df[&#39;message&#39;].str.contains(&#39;Media omitted&#39;)]<br><br># Concatenate all cleaned messages into a single string<br>all_messages = x[&#39;message&#39;].dropna().str.cat(sep=&#39; &#39;)<br><br># Generate word cloud<br>wordcloud = WordCloud(width=800, height=800,<br>                      background_color=&#39;white&#39;,<br>                      stopwords=STOPWORDS,<br>                      min_font_size=10).generate(all_messages)<br><br># Plot word cloud<br>plt.figure(figsize=(8,8))<br>plt.imshow(wordcloud)<br>plt.axis(&quot;off&quot;)<br>plt.tight_layout(pad=0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*AnFEVwgvfkKWT4kHjKoQcw.png" /><figcaption>Word cloud of messages</figcaption></figure><h3>Most Active dates.</h3><pre>plt.figure(figsize=[10, 8])<br>sns.barplot(x=&#39;count&#39;, y=&#39;date&#39;, data=df[&#39;date&#39;].value_counts().head(20).reset_index().rename(columns={&#39;index&#39;:&#39;date&#39;, &#39;date&#39;:&#39;count&#39;}), color=&#39;#F0D653&#39;)<br>plt.title(&#39;Top 10 days with highest number of Messages&#39;)<br>plt.xlabel(&#39;Number of Messages&#39;)<br>plt.ylabel(&#39;Date&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*67keAATihPH2QdTvh2U1Zg.png" /><figcaption>The group was most active on 16/11/2022.</figcaption></figure><h3>Most Active times of the day.</h3><pre>plt.figure(figsize=[10, 8])<br>sns.barplot(x=&#39;count&#39;, y=&#39;time&#39;, data=df[&#39;time&#39;].value_counts().head(20).reset_index().rename(columns={&#39;index&#39;:&#39;time&#39;, &#39;time&#39;:&#39;count&#39;}), color=&#39;#F0D653&#39;)<br>plt.title(&#39;Most Active Times&#39;)<br>plt.xlabel(&#39;Number of messages&#39;)<br>plt.ylabel(&#39;Time&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*764UeWyQaK0rVU2ucEOPqg.png" /><figcaption>The group is mostly active in the night.</figcaption></figure><h3>Most Active hours.</h3><pre># Extract the hour from the time column<br>df[&#39;hour&#39;] = df[&#39;time&#39;].str.split(&#39;:&#39;, expand=True)[0]<br><br># Plot the most active hours<br>plt.figure(figsize=[10, 8])<br>sns.barplot(x=&#39;count&#39;, y=&#39;hour&#39;, data=df[&#39;hour&#39;].value_counts().head(20).reset_index().rename(columns={&#39;index&#39;:&#39;hour&#39;, &#39;hour&#39;:&#39;count&#39;}), color=&#39;#F0D653&#39;)<br>plt.title(&#39;Most Active hours&#39;)<br>plt.xlabel(&#39;Number of Messages&#39;)<br>plt.ylabel(&#39;Hour&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*CkmuckQ90lauCvCQoEMQ_A.png" /><figcaption>Hour 20 of the day is the most active.</figcaption></figure><h3>Most Active days of the week.</h3><pre># Extract the weekday from the date column<br>df[&#39;weekday&#39;] = df[&#39;date&#39;].dt.day_name()<br><br># Plot the most active hours<br>plt.figure(figsize=[10, 8])<br>sns.barplot(x=&#39;count&#39;, y=&#39;weekday&#39;, data=df[&#39;weekday&#39;].value_counts().reset_index().rename(columns={&#39;index&#39;:&#39;weekday&#39;, &#39;weekday&#39;:&#39;count&#39;}), color=&#39;#F0D653&#39;)<br>plt.title(&#39;Most Active days of the week&#39;)<br>plt.xlabel(&#39;Number of Messages&#39;)<br>plt.ylabel(&#39;Weekday&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*g6XnEik3mRykUuKZQf9V9w.png" /><figcaption>Friday is the most active day.</figcaption></figure><h3>Most active and least active group participants.</h3><pre># most active<br>df[&#39;member&#39;].value_counts().sort_values(ascending=True).plot(kind=&#39;barh&#39;,figsize=(15,15), color=&#39;#F0D653&#39;)<br>plt.title(&#39;The least active group members&#39;)<br>plt.ylabel(&#39;Participant&#39;)<br>plt.xlabel(&#39;No of Messages&#39;);<br><br># least active<br>df[&#39;member&#39;].value_counts().tail(20).sort_values(ascending=True).plot(kind=&#39;barh&#39;,figsize=(15,15), color=&#39;#F0D653&#39;)<br>plt.title(&#39;The least active group members&#39;)<br>plt.ylabel(&#39;Participant&#39;)<br>plt.xlabel(&#39;No of Messages&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*xiegoYD5rqFumjMQMgC18Q.png" /><figcaption>Most active participants.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*5ZqOHZzdDJDOlW4jtPpN0w.png" /><figcaption>Least active participants</figcaption></figure><h3>Messaging progression</h3><p>Taking a closer look at how messaging has evolved and what it means for the daily interactions.</p><pre>date_df = df.groupby(&quot;date&quot;).sum()<br>date_df.reset_index(inplace=True)<br>fig = px.line(date_df, x=&quot;date&quot;, y=&quot;word_count&quot;, title=&#39;Messaging progression&#39;)<br>fig.update_xaxes(nticks=20)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoxxBL_ETudPzdVqcRJ3sg.png" /><figcaption>Messaging evolution from March 2022 to November 2023.</figcaption></figure><p>The analysis of these WhatsApp group chats reveals the evolution of messaging and its impact on communication. Insights into communication patterns - from active chatters to popular topics and peak activity times, trends, and habits were gained, providing a fascinating glimpse into interactions. Understanding all of this helps improve future communication. The power of data analysis was utilized to uncover valuable insights behind the vast amount of conversational data. These remind us of the power of data to reveal information about our daily interactions, leading to more meaningful and effective conversations in the future.</p><blockquote>Thanks for reading🤓. You can check out my <a href="https://github.com/Abdulraqib20/Whatsapp-Chat-analysis">GitHub repo</a> for the full code, documentation and other resources related to the project. If you found this piece of article insightful, kindly drop a clap and ensure you follow <a href="https://medium.com/@abdulraqibshakir03">me</a> for more insightful articles like this. Cheers!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe7a220f0796" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Short guide to getting unlimited tweets by Python without a Twitter API]]></title>
            <link>https://medium.com/@abdulraqibshakir03/get-unlimited-tweets-by-python-without-a-twitter-api-793467b201e9?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/793467b201e9</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 14:38:54 GMT</pubDate>
            <atom:updated>2023-01-02T22:21:07.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nTZS6O_ZIDnUTpGI" /><figcaption>Photo by <a href="https://unsplash.com/@alexbemore?utm_source=medium&amp;utm_medium=referral">Alexander Shatov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Social media is one of the richest sources of real-world data and this doesn’t exempt twitter. Everyday many thousands of developers make requests to the Twitter API. To manage the sheer volume of requests, Twitter has placed limits on the number of requests that can be made. This has in turn led to the API having some limitations including the ability to get not more than 3200 user tweets or even getting tweets that are just seven days old. I would teach you how to get Unlimited tweets without the API using a special python library called snscrape.snscrape means social networking scrape which means it is not just limited to twitter. It also be used on other social media networks like Instagram, Facebook, Mastodon, Reddit, Weibo and the Russian networking site, VKontakte. Without further ado, lets get to business.<strong>Installation</strong></p><p>python -m pip install snscrape</p><p>Now, I will import the required libraries to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*LTovFqwkw1xw1pjQODWOUg.jpeg" /></figure><p>Let start with user tweets of a limit of 100</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*becng6X5EIIRsBec9nkzbA.jpeg" /><figcaption>This print outs information about the query including URL, content, date, user, tweets, etc.</figcaption></figure><p>Next, I’ll extract the Date, User and Tweet from the query and then convert it to a pandas dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*setKAWUvxHxs9XD-fMqt_g.jpeg" /><figcaption>Exporting to a pandas dataframe</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*Ujw_d253UuBMKy4_i8rP0A.jpeg" /><figcaption>The dataframe</figcaption></figure><p>Next, let’s try make a query of over 10,000 tweets. I will extract info from the account of Twitter’s founder, Jack Dorsey over a course of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*K7hqsTg0KiVhq8o_BcwGIA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*3j5OLPZ_3rfnfO15pVcgbQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*ysxFzAVno6CbswIt9YbbUg.jpeg" /><figcaption>pandas dataframe</figcaption></figure><p>So this is a short guide on how to get unlimited tweets with <em>snscrape</em> without making use of the Twitter API. Thanks for reading. If you like this, like and give a follow. Cheers! You can also follow me on <a href="https://github.com/Abdulraqib20">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=793467b201e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TMDb Movie Data Analysis]]></title>
            <link>https://medium.com/@abdulraqibshakir03/project-tmbd-movie-data-analysis-8bba631b53a3?source=rss-b25e6936214d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bba631b53a3</guid>
            <dc:creator><![CDATA[Abdulraqib Omotosho]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 13:01:10 GMT</pubDate>
            <atom:updated>2022-12-29T09:08:55.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ol5jyJAN7jcGse-k" /><figcaption>Photo by <a href="https://unsplash.com/@jakobowens1?utm_source=medium&amp;utm_medium=referral">Jakob Owens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is a part of the projects I did in the Udacity Data Analyst Nanodegree Program. It is divided into 3 different parts. The introduction, data wrangling and the exploratory data analysis.</p><h3>The Introduction</h3><p>The data set contains observation of about 10,000 movies collected from The Movie Database (TMDb), including user ratings and revenue. You can find more about the dataset <a href="https://www.kaggle.com/datasets/juzershakir/tmdb-movies-dataset">here</a>. In this project, I’m going to investigate the dataset to find out the movies with highest profits, hits and other interesting stuff about movies from the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*-PSkQgyBvV0WKfkfZDqK8g.jpeg" /><figcaption>import libraries and packages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*F_0e-bZFneBtgSGlpRPPRg.jpeg" /><figcaption>reading the dataset.</figcaption></figure><h3>Data Wrangling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*wdIToMjDcIhitYqz0BK60A.jpeg" /></figure><p>The dataset has 10866 rows and columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*AMUwD1pDVPTOaSJMce_CYw.jpeg" /><figcaption>Dataset columns</figcaption></figure><p>Next, I’ll drop some columns here as they are not important in the analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*MeU1Yi2ccRJFcxhwBq-nqA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*ohNXFfw8a6TkflPyGk_eDg.jpeg" /><figcaption>checking for duplicate rows and removing.</figcaption></figure><p>Some columns in the data contain zero(0) values. Let’s check them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*N7Z3HDdp2QvEaSJ7FphW1g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*CeQzo-SBoO9lBECwKti0Ww.jpeg" /><figcaption>replacing the zeros with null values</figcaption></figure><p>Next, let’s have an overview of the null values in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*GnOFMO9bOESXkIL-z8d61g.jpeg" /><figcaption>There is a significant number of nulls in some columns.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*kzu1Pz7XWpTccw9ogwecuw.jpeg" /><figcaption>Null values are now gone</figcaption></figure><p>The <em>release_date </em>column is a string. I’ll convert it to a datetime column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*lvB5CqSkDxA-gVlEdNngMA.jpeg" /></figure><p>Some columns contain multiple values separated by pipe (|) characters. Let’s see them..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*_w3v9xeXGqLfHs6oQ_rCSw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*HVOOsBhWj9b5azF2_o61Fg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*DGCGka8g_O74M9qs11Ar7Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*PmfAzSnCbrDPKex3b1bSXA.jpeg" /></figure><p>Next, I’ll create new dataframes to hold the separated columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*zXpwPu_7nFRJT2qxc9ydpQ.jpeg" /></figure><p>concatenating the columns to the dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*wFisKXPHIZ9RFKewahhgow.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*10PjOsCQg097BDKks7LlJw.jpeg" /><figcaption>dropping the columns that contained pipes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*dkNA3OHS4p9YR2sYA7QklQ.jpeg" /><figcaption>columns of the new data.</figcaption></figure><p>Getting index labels of the new columns added to the dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*l71Qq_PDoF0vSs53wx7YhA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*wKyR87LmQi6OtC5JPfVUjw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*K1gUELohENyiwXcs4Qs-Eg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*Fon7AuUDASrS3lptGSbftg.jpeg" /></figure><p>Concatenating all the separated columns into a single column and dropping the null values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*8XF7ChTMEipcB8rCiPb0gw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*KiH6JZuMl0xKSZbi8_HhQA.jpeg" /><figcaption>drop the index labels of the new columns.</figcaption></figure><p>Thereafter, save the data to a new file for further analysis. Note: You might also choose to make a copy of the data to proceed to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*wHhXj_NuuUG4n5lXAU6RDQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*17oihohTBAJ3-G09ylbu3w.jpeg" /><figcaption>The first five columns of the dataset.</figcaption></figure><h3>Exploratory Data Analysis</h3><p>Now that the data is cleaned, we can proceed to explore it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*NCqwuOpRwZifGfMcrrEwRA.jpeg" /><figcaption>correlation between features.</figcaption></figure><p>Now, I’ll proceed to answering some questions that I posed using this data.</p><h3>1. What movies had the highest and least revenue?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*PghitdTqusjxc5bXB5BXWA.jpeg" /><figcaption>Comic movies generated the highest revenue while Science Fiction, Animation had the lowest revenue.</figcaption></figure><h3>2. What movies had the highest and least budget?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*c6OGuWityE8T1Iau8CQoUg.jpeg" /><figcaption>The same genre of movies with the highest and lowest revenue had the same for budget.</figcaption></figure><h3>3. Movies with the highest and lowest runtime.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*PAA8I-7vYi5zMq-4tgz67A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*dMmoeUNNhMGD3q1TEJfpKg.jpeg" /><figcaption>Top 5 movies with the highest runtime</figcaption></figure><h3>4. Genres with the highest and lowest runtime.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*SATIXLGLHXJ-SzTMDyhm2Q.jpeg" /><figcaption>Drama genres had the longest runtimes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Fl1Xc2OwktjzIi4HHQvPXg.jpeg" /><figcaption>Genres with the longest running times.</figcaption></figure><h3>5. Most profitable movies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*r0pNgNUuyR_6u91fvzfTaw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*qoK6OyHBUo3jKg6KzaXG2Q.jpeg" /><figcaption>Avatar was the most profitable movie.</figcaption></figure><h3>6. Hit movies!(most popular movies)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*532LJ0XYALgQN2Aj7rv5pw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*CYWk9EH2KR0h43K7i8bfNA.jpeg" /></figure><h3>7. Number of movie genres released over the years</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*WYIiLpSQA-KK-IWACcrtGg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*N36-Aon1LTTwfWODvI7few.jpeg" /></figure><h3>8. Most popular genres</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*19uvx9I6TR49jhLx006hdA.jpeg" /><figcaption>Adventure,Drama,Science Fiction genres were the most popular.</figcaption></figure><h3>9. Action movie releases over time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*9ir6WyaQhT5gjuaZsKIKsw.jpeg" /><figcaption>Action movie releases</figcaption></figure><h3>10. Month with highest number of movie releases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*onaElWyFGeZ8qNN7sNAmyQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*lXaRYylpdS1v5XI9Hy6-Pw.jpeg" /><figcaption>September was the month with most movie release.</figcaption></figure><h3>11. Day with highest number of movie releases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*g8osjGDB2heGWpYT8KR0sQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*Ev6IkQ1LwF-hCVQMlpRrmQ.jpeg" /><figcaption>Most movies were released on Friday.</figcaption></figure><p>So here comes the end of my analysis of the IMDB data. The dataset was somewhat limiting as many entries in the dataset were dropped due to missing data. Also, some zeros were turned into null values which significantly increased the number of missing data in the dataset.</p><blockquote>Thanks for reading, I hope you enjoyed it. If you like this, check out my <a href="https://github.com/Abdulraqib20/TMDb-Movie-Analysis">GitHub page</a> for the notebook. Ensure you also follow me. Cheers!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bba631b53a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>