<?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 Muturi David on Medium]]></title>
        <description><![CDATA[Stories by Muturi David on Medium]]></description>
        <link>https://medium.com/@muturidavid8?source=rss-239113ae0bf8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*UDGYPcb-4ozvvWnNAqYvjg.jpeg</url>
            <title>Stories by Muturi David on Medium</title>
            <link>https://medium.com/@muturidavid8?source=rss-239113ae0bf8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:15:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muturidavid8/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[Questions to unlock valuable insights for your analytics project]]></title>
            <link>https://medium.com/@muturidavid8/questions-to-unlock-valuable-insights-for-your-analytics-project-be88df3647ab?source=rss-239113ae0bf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/be88df3647ab</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Muturi David]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 13:53:29 GMT</pubDate>
            <atom:updated>2022-06-29T13:53:29.962Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>To ask the right question is already half the solution to a problem</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-B47CCkTE12yzYus.png" /></figure><p>There is a bad joke out there that a data scientist is someone who is very successful at solving the wrong business problems. This is due to many projects that data scientists and analysts undertake which do not necessarily deliver any business value.</p><p>It’s often easy for data analysts and data scientists to be carried away by fancy algorithms and start “forcing” business problems to be solved by the algorithm even if by solving the problem there will be no tangible business value. The quality of the insights you get from the analysis is greatly influenced by the quality of questions you ask. Asking the right question about the data and the business processes often leads to the right approaches for analyzing your data.</p><p>Asking questions helps you fit into your stakeholder’s shoes and understand the business problem they want to solve. Questions are a good way of assessing your stakeholder’s motivations and financial interests. But truth be told, it’s not as easy to get to that one right question that will give you all the insights you need to drive some form of decisions in the business. What you can do, you can start by asking lots and lots of questions. when you have a good grasp of the business, ask more direct questions to understand what your stakeholders want to solve. Now you have a few questions to concentrate on. Analyze them or discuss them with the stakeholders until you get to “the” question(s).</p><p>Mastering the art of asking questions is an invaluable skill to have for data-related professions. By raising many questions, you are able to filter the most significant question which shapes the course and impact of your analytics project. In this blog, we shall look into 5 levels of questions that should act as a guide when undertaking an analytics project</p><h3>1. What is the problem am trying to solve?</h3><p>This might sound obvious but many data analysts are quick to dive deep into data projects without a clear understanding of the underlying problem or expected results. Successful data analytics projects begin with an understanding of the problem the business is trying to solve. This is the stage where domain knowledge of the business comes in handy.</p><p>Sitting down to frame the business problem you are trying to solve places your project on the right course. Using the adjectives referred to by the famous S.M.A.R.T acronym can set you on the same page as your stakeholders.</p><h3>2. Which metrics will define my success?</h3><p>As the old adage goes “What can be measured can be improved”. This question helps you know the indicators that will define the direction and success of your analytics project.</p><p>This question helps to decide on which metrics and KPIs should be measured, how they should be measured, and what would be success indicators?</p><p>For instance, if you are running an analysis for call center data you can choose to measure the “average speed of answer” as a metric to define the performance of each agent. You can decide to set a threshold of an ideal spread to answer and measure the agents that fall below and above the thresholds as success indicators.</p><h3>3. What data do I need?</h3><p>After you have all the metrics you need for the project, the next set of questions revolves around which data you will need for the metrics. Analyzing the most important metrics before embarking on a data search makes your search for relevant data direct and focused.</p><p>In this phase, it’s important to write down a set of all variables you will need. Then ask if the data is available and indicate the source of it. Some you get by querying the database, some you might need to scrap from the web. Whichever the source, it’s important to know what’s available and what’s not. For the data that is not available, you indicate how you can get it and the process that will be involved.</p><p>Another set of questions to ask together with the data needed is the question of the accuracy and quality of your data. If it is a sample dataset, is it a true representation of the population you will be inferring to? Remember clean data always beats fancy algorithms.</p><h3>4. What statistical analysis and visualization will I need to apply?</h3><p>At this point, you are already clear about the problem you are intending to solve, the metrics you will be measuring and the data you will need. Now, you assess which statistical methods will work best in analyzing your data? and which models will you need to build? For EDA(Exploratory Data Analysis) which graphs will work best in visualizing your trends and uncovering patterns? Which tools will be used to clean and analyze the data?</p><p>A trick you can use to cub this question is to write down the visualization type and analysis method you need next for each metric you intend to measure. if you want to show a metric and compare categories, choose a bar graph. Line graphs work best for time series analysis. Scatter plots are best to show the relationship between two numeric variables e.g Age and salary. Pie charts are good to show proportions of categories that add up to 100%. Pie charts are recommended only when you have categories less than 5.</p><h3>5. How will I communicate the results of the project to the stakeholders?</h3><p>The epitome of a successful analytics project is the effectiveness of results communication to the stakeholders. After the analysis, you want to communicate your results to the stakeholders in a way that will make them feel a certain way and take certain decisions. It’s important to ask a set of questions about the best strategy to use when sharing your results with the stakeholders?</p><p>Other questions that can help shape the way you present your results would be; What actions will be taken from the results of my analysis? What would be the cost of implementation of my recommendations? Are my results controversial to the business norms? what level of resistance am I expecting?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*S9r6_lzMHFw6jM7j.jpeg" /></figure><h3>Conclusion</h3><p>All through the analytics project, you need to ask questions and filter the ones that you think answering will provide great insights. Being a curious cat and skeptical about your data is a skill that will often make you to uncover trends and insights that lie beyond the surface. Nobody is interested to know what they already know. The trick to getting good at asking excellent data questions is to keep on asking them.</p><blockquote><em>“If I had an hour to solve a problem and my life depended on the solution, I would spend the first 55 minutes determining the proper question to ask… for once I know the proper question, I could solve the problem in less than</em> five<em> minutes.”</em></blockquote><blockquote>Albert Einstein</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be88df3647ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[101 of Text Analysis and Classification]]></title>
            <link>https://medium.com/analytics-vidhya/101-of-text-analysis-and-classification-67dbc9a82f?source=rss-239113ae0bf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/67dbc9a82f</guid>
            <category><![CDATA[unstructured-data]]></category>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Muturi David]]></dc:creator>
            <pubDate>Sat, 25 Apr 2020 09:09:15 GMT</pubDate>
            <atom:updated>2020-05-07T14:16:08.121Z</atom:updated>
            <content:encoded><![CDATA[<h4>All you need to know to start rocking in Text Analysis with Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1l7dcWk9ZufYYAFzJqVzA.jpeg" /></figure><p>We are living in an interesting era. Organizations are evolving to lavage on data in their operations. Most, though not all, are running away from intuitive decision making and embracing data-informed decisions. Industries are waking up to the reality that data is the new fuel they need to power their operations and market strategies for immense profitability. McKinsey-Global consultancy giants- indicates that “data-driven organizations are 23 times more likely to acquire customers, six times as likely to retain those customers, and 19 times as likely to be profitable as a result.” I have attended several data summits and interacted with several business executives. I have been agile to note them sporadically throw some quotes like; “In God we trust, all others bring data”, ”data is the new oil”,” Without big data, you are blind and deaf and in the middle of a freeway”, “Data beats emotions”, ”Above all else, show the data” and many more. The point is, we are no longer in the era where data science was an enigma. The big differentiator in the market today is the mastery of operations and customer data. Whoever understands customers data is better positioned to win customers, heart.</p><p>In your quest for becoming a data scientist in this era of rapidly evolving industries, fluency in handling both structured and unstructured data is both mandatory and inevitable. I love to think of data as a highway and data science as the automobile to get me to the destination- solve a business problem. The more conversant you are with the roads, the smoother and faster your journey will be. Remember, the key goal of data science is to construct the means for extracting business-focused insights from data. It goes without saying, fancy data always beats fancy algorithms.</p><h4>What’s the difference between structured and unstructured data?</h4><p>Structured data is the most common type of data. As you can deduce from the name, structured data is the type of data that is well-formatted and highly organized. This data type conforms to tabular format with clear and labelled columns and rows. In often cases, the term structured is used to refer to what is commonly known as quantitative data. Working with structured data and running some analytical algorithms is very straightforward. The thousands, if not millions, of free learning resources online.</p><p>On the other hand, unstructured data is information not neatly organized or formatted. Wikipedia defines unstructured data as information that either does not have a pre-defined data model or is not organized in a pre-defined manner. Unstructured information is typically text-heavy but may contain data such as dates, numbers, and facts as well. Common examples of unstructured data include PDFs, Word files, audio, video files or No-SQL databases.</p><p>This blog is going to introduce you to some valuable analytical and machine learning techniques you need to master for a smooth introduction in text analysis. Have Fun, Enjoy😊😊</p><h3>What is Natural Language processing?</h3><p>I Can simply define Natural Language processing, commonly dubbed as NLP, as the branch of data science that aids computers to process, analyze and manipulate the human’s natural Languages. NLP seeks to bridge the gap between human communication and computer understanding. The evolution of NLP is dated back in the 1950’s though it has rapidly advanced in the modern era due to an increased interest of human to machine communications and availability of big data and enhanced algorithms.</p><p>Though the field is very interesting, I have to admit that it is not an easy task to train a machine to understand how we communicate.</p><h3>Uses of NLP</h3><p>The application of NLP extensively cut across all industry that generates and consumes big data. Basically, NLP is the technology behind all the virtual assistants, speech-to-text, chatbots, computer-based translations and many more.<br> Below are some common uses of NLP in the modern business world. You can read more on the same <a href="https://becominghuman.ai/8-thought-provoking-cases-of-nlp-and-text-mining-use-in-business-60bd8031c5b5">here</a>.</p><ul><li>Chatbots</li><li>Sentiment analysis</li><li>Hiring and recruitment</li><li>Advertising</li><li>Market intelligence</li></ul><p>In this blog, we shall be working with a dataset of messages which are classified as Spam or Ham. The goal is to explore the data then create an accurate classification model that identifies if a message is a spam or not. You can download the dataset <a href="https://www.kaggle.com/uciml/sms-spam-collection-dataset"><em>here</em></a>!</p><h3>1. Loading the required Packages</h3><ul><li><a href="https://www.nltk.org/"><strong>Natural Language Toolkit</strong></a><strong> (NLTK)</strong>-This is the leading module for natural language processing in python. It provides easy-to-use interfaces and very rich in libraries and functions.</li><li><strong>StopWords- </strong>Stopwords are commonly used words which don’t add much meaning to a sentence or our model, “the”, “a”, “is”, “on”. Stopword module contains all the English stopwords which we shall train our model to ignore.</li><li><a href="https://scikit-learn.org/"><strong>Sklearn</strong></a><strong>- </strong>Sklearn is the most popular machine learning and predictive analytics module in python. It offers a wide range of functionality in preparing features, creating supervised and unsupervised models and measuring the performance of the model.</li><li><a href="https://python-graph-gallery.com/wordcloud/"><strong>WordCloud</strong></a><strong>- </strong>This is the package we shall use to create some visual representations of our data text.</li><li><strong>Pandas and Numpy- </strong>We require the two packages to word with data frames.</li><li><a href="https://medium.com/@muturidavid8/python-visualization-101-3aee09809100"><strong>Matplotlib and Seaborn</strong></a><strong>- </strong>This are plotting packages in python. I have comprehensively discussed them in this cool blog <a href="https://medium.com/@muturidavid8/python-visualization-101-3aee09809100"><strong><em>here!</em></strong></a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Y0XO3hBZvVjlSx1sUR2vDg.png" /><figcaption>Necessary packages for text analysis</figcaption></figure><h3>2. Loading and preparing the data</h3><p>We use pandas to load and tidying up the dataset.</p><pre>## Importing the dataset<br>df=pd.read_csv(&quot;spam.csv&quot;,encoding=&quot;latin-1&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*RcTkEk--d-OofSm3vK9G-w.png" /><figcaption>First 5 rows of our dataset</figcaption></figure><p>Well, there some few things we need to do to make our data organized and ready for analysis.</p><ul><li>get rid of unnamed columns with NaN values</li><li>Rename the columns</li><li>Then add a column of labels where <strong>0</strong> represents ham and <strong>1 </strong>represents spam</li></ul><pre>## Droping the unceccesary columns and renaming <br>df.drop([&quot;Unnamed: 2&quot;,&quot;Unnamed: 3&quot;,&quot;Unnamed:4&quot;],axis=1,inplace=True)<br>df.columns=[&quot;Class&quot;,&quot;Text&quot;]<br>df[&quot;Lable&quot;]=df.Class.map({&quot;ham&quot;:0,&quot;spam&quot;:1})<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*8wI6jGanDymhHjfXIJ0-Ew.png" /></figure><h3>3. Exploring the data</h3><p>Now that our data is organized, we can perform some Exploratory analysis.<br>Let us begin by having a look at frequency summaries of each class by using the describe function.</p><pre>df.groupby(&#39;Class&#39;).describe(include=&#39;O&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*2_9jSEgzgyH9Rw_1Hvieow.png" /></figure><p>We have 4825 rows classified as ham messages with 4516 non-duplicates. Spam messages are 747 with 653 unique. We can use seaborn countplot function to visualize the frequencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*vm2j4HerSrBm0lBVgUVQIw.png" /></figure><h4>Counting the frequent words in every</h4><p>We want to see which words are common in ham messages and those which are common in spam messages. Before we create the word frequent summary, we need to clean up the data. By cleaning i mean;</p><ul><li>Break all the sentences into words</li><li>get rid of punctuation marks</li><li>convert all the words to lower case</li><li>Get rid of stopwords and all words with less than two character.</li></ul><p>We create a words_cleaner function with one argument of data being cleaned and returns a set of clean words.</p><pre>def words_cleaner(data):<br>    words=[re.sub(&#39;[^a-zA-Z]&#39;, &#39; &#39;,i) for i in df[&#39;Text&#39;]]<br>    words=[i.lower() for j in data for i in j.split()<br>    words=[i for i in words if not i in   set(stopwords.words(&#39;english&#39;))]<br>    words=[i for i in words if len(i)&gt;2]<br>    return words</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*g_CtixAcqQAyosHt1qpGJw.png" /><figcaption>Words_cleaner Function</figcaption></figure><p>Now we can extract all the words in ham messages and create a data frame of their frequencies.</p><pre>Ham_texts=df.query(&quot;Class==&#39;ham&#39;&quot;)[&#39;Text&#39;]<br>ham_words=words_cleaner(Ham_texts)<br>ham_words_freq=nltk.FreqDist(ham_words)<br>ham_words_freq=pd.DataFrame(ham_words_freq.most_common(10),<br>                            columns=[&#39;Top_Words&#39;,&#39;Frequency&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*H3bfVn3EzjsLRxXAAcJhUw.png" /></figure><p>Perfect! Now we have a dataframe of top 10 most used words in Ham messages. We can now create a bar graph to visualize the frequencies.</p><pre>plt.figure(figsize=(8,6))<br>sns.set_style(&#39;whitegrid&#39;)<br>ax=sns.barplot(x=&#39;Top_Words&#39;,y=&#39;Frequency&#39;,data=ham_words_freq)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*dRTgtqJjPs54_tmXMxi7zg.png" /><figcaption>Most used words in Ham messages.</figcaption></figure><p>Yeah, I know, that cool! 😎Now, you can do the same for Spam messages.</p><h4>Creating MindMaps</h4><p>To get a whole overview of word frequency in both classes, we can leverage on word clouds. It’s pretty easy to create word clouds in python, we just need to create a function with two arguments -data and background colour- then return a word cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*iNkqn6IeQDFPyOFGa0Y7NA.png" /><figcaption>Function for creating word clouds</figcaption></figure><h4>Ham Messages word cloud</h4><p>Now that we have a function for creating word clouds, we only need one line of code to return word clouds. in word clouds, the bigger the word, the frequent it is.</p><p>wc(words_cleaner(Spam_texts),’black’)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*76lAY9GdOmMipthdt7vghw.png" /><figcaption>Ham Messages word cloud</figcaption></figure><h4>Spam Messages Wordcloud</h4><pre>wc(words_cleaner(Spam_texts),&#39;black&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*cmv-ieULKHskLaRS1SRJNQ.png" /><figcaption>Word cloud for Spam messages</figcaption></figure><p>Spam messages mostly contain words like Free, Call, Text, Mobile, Claim and Call Now.</p><h3>Machine Learning</h3><p><strong>Creating a model to classify a message to either spam or ham.</strong></p><p>Before creating the classifier, we need to clean our features/independent variable i.e(Text column). To clean our features, we shall follow the following simple procedure:</p><ul><li>Remove all punctuation marks in each Text message</li><li>Convert the text message to lower case</li><li>Split each message into single words</li><li>Remove all the stopwords</li><li>Stem the words using PorterStemmer function. This involves cutting each word to its root form. e.g, the stem for these words: <em>[car, cars, car’s, cars’] </em>is <strong><em>car. </em></strong><em>A Stem for </em>[<em> loving,`love, lovely loverble</em>]<em> is </em><strong><em>Lov</em></strong></li><li>We join back the cleaned words into sentences.</li></ul><p>To achieve this, we shall create a function that loops through our data by cleaning each message at a time, then returns an array of cleaned words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*lPo-_3fFRYNfnhBHE6UUCw.png" /><figcaption>A Function to clean all the features in our data</figcaption></figure><p>See how the dataset looks after cleaning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*cCA2oRfUDFLhZLgzftrrMw.png" /><figcaption>First 3 messages of raw data and the same after cleaning.</figcaption></figure><p>I think the difference is clear! 😊</p><h4>Training the model.</h4><p>We shall use Naive Bayes Classifier which is proven to offer statistically satisfying results in text classifications especially <a href="https://en.wikipedia.org/wiki/Naive_Bayes_spam_filtering">email filtering</a>. <br>Below is a snipe of features preparation(<a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html">Vectorizing</a> <strong>CountVectorizer</strong>)and model train.</p><pre>cv=CountVectorizer() <br>X=cv.fit_transform(X)<br>X_train,X_test,y_train,y_test=train_test_split(X,y,<br>                                               test_size=0.25,<br>                                               random_state=50)<br>classifier=MultinomialNB() <br>classifier.fit(X_train,y_train)<br>y_pred=classifier.predict(X_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*1USWP37FbfhWPCI1Xi8DCw.png" /></figure><p>Testing the Accuracy of the model</p><pre>accuracy_score(y_pred,y_test)</pre><p>Our model is 97.77% accurate. That’s a commendable performance. <br>We can also generate a<a href="https://www.geeksforgeeks.org/confusion-matrix-machine-learning/"> confusion matrix</a> to zoom in to the performance of the model. The leading diagonal values indicate the correctly predicted test value by our model.</p><pre>confusion_matrix(y_test,y_pred)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*GgXkK73CIiZvSbmxN4LV7g.png" /><figcaption>Confusion matrix</figcaption></figure><p>You can access the entire script <a href="https://github.com/pyPRO2019/Medium-Blogs/blob/master/NLP%20Intro.ipynb"><strong>here</strong></a><strong>.</strong></p><h3>Recommendation</h3><p>This blog was inspired by a user request auto-responsive programme I helped engineer for <a href="http://www.esquekenya.com/"><strong><em>Esque Kenya</em></strong></a><strong><em>. </em></strong>They are the leading providers of school management and logistics solution<strong><em>. </em></strong>You can check on them <a href="http://www.esquekenya.com/"><strong><em>here</em></strong></a><em>.</em></p><p>If you enjoyed this blog, don’t forget to 👏🏼👏🏼👏🏼 and to follow for more.</p><p>Stay safe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67dbc9a82f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/101-of-text-analysis-and-classification-67dbc9a82f">101 of Text Analysis and Classification</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Visualization 101]]></title>
            <link>https://medium.com/@muturidavid8/python-visualization-101-3aee09809100?source=rss-239113ae0bf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aee09809100</guid>
            <dc:creator><![CDATA[Muturi David]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 19:52:11 GMT</pubDate>
            <atom:updated>2020-06-26T08:20:52.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bQ4QEy_lhxLtYy-4" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data visualization is usually the epitome of your data science project. A narrative of your data science project is captured from your visualizations. At the end of the day, your project should bring actionable insights that can help the business scale or solve an existing problem. In my career as a data scientist, I have come to learn that, if a project can not be translated to implementable and feasible actions, it’s a failed project. Regardless of the fancy codes and algorithms used. Clear and catch visualization is the way to your boss’s head.</p><p>if you desire to make business executives and relevant consumers of your insights excited and eager to act on your project, then delivering your insight visuals that capture both their mind and emotions is not an option. As a common adage goes, a picture is worth a 1000 words. People are quick to discard what they don’t understand. Therefore, a good visualization is mandatory for all successful data science project for it makes people connect to your project with ease.</p><p>Data Visualization is simply interpreting and transforming your data into visual contexts such as graphs, maps and summary tables. Data visualization makes big data and complex data science projects easy to understand and much interesting. Through data visualization, it’s easy to observe and explore <em>patterns, </em>trends and correlations that might not otherwise be detected or observed.</p><p>There are over 20 common types of visualization charts, both in 2D and 3D, that one can use to tell the story from data. Python offers multiple great graphical libraries that are packed with lots of different features to allow one to create beautiful and informative charts. With python’s visualization modules, one can easily create basic visualizations, interactive visualizations and even customize them into a dashboard.</p><p>In this blog, I hope to give you a smooth introduction to visualization in python. We shall look into the three most common visualization packages in python. That is; <strong><em>Pandas</em></strong>, <strong><em>Matplotlib</em></strong> and <strong><em>Seaborn </em></strong>in <a href="https://jupyter.org/">Jupyter Notebook</a>. We shall use students data which you can access <a href="https://gist.github.com/pyPRO2019/dc44ae45f7cfe2f2a34fec30db4678eb">here</a>.</p><p>Enjoy!</p><h3>Importing the packages to be used</h3><p>Before loading the packages, it’s always a good habit to set you working directory. I recommend setting your working directory to the folder that contains the resources -datasets- for your project. use cd &lt;path to your folder&gt; to change your directory.</p><p>Now we import all the packages we require using the importfunction.</p><pre><em>##Importing the  Packages</em><br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><pre><em># Importing Profiling package</em><br>from pandas_profiling import ProfileReport</pre><pre><em>#setting up the graphycal environment</em><br>%matplotlib inline<br>sns.set_style(&#39;whitegrid&#39;)<br>plt.style.use(&#39;fivethirtyeight&#39;)</pre><ul><li>Pandas — Pandas is the module we require to perform data manipulation and work with data frames. Pandas will offer some base visualization functionalities using the plotfunction.</li><li>Numpy — Numpy is a powerful python package that offers a wide functionality when it comes into carrying out some arithmetic operations.</li><li>Matplotlib — <a href="https://pypi.org/project/matplotlib/"><em>Matplotlib</em></a><em> </em>is a low-level visualization library in python for creating static, animated, and interactive charts.</li><li>Seaborn — <a href="https://seaborn.pydata.org/"><em>Seaborn</em></a> is a visualization library based on <a href="https://matplotlib.org/">matplotlib</a> that provides a high-level, attractive and informative visualizations.</li><li>Warnings — Warnings is used to manage warning messages in python. In our case, we chose to silence them by writing warnings.filterwarnings(&#39;ignore&#39;)</li><li><a href="https://pandas-profiling.github.io/pandas-profiling/docs/">Pandas Profiling</a> — This like a magical package to me. It’s very helpful in carrying out some quick EDA(exploratory data analysis). we shall use pandas profiling to generate an HTML summary report-including descriptive statistics- from our data. If you don&#39;t have pandas profiling installed, you can install it using pip package manager by running <strong>pip</strong> <strong>install</strong> <strong>pandas-profiling</strong></li></ul><h3>Loading the Dataset</h3><p>Use pandas you load data in several common formats using the read command. in our case, we shall use read_csv() method to read our students data since its in CSV format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*0cGoJ5rsDdauOPxJ8gUmZQ.png" /></figure><p>This is hypothetical data of students lifestyle and academic performance in a certain university in Kenya.</p><h3>Using Pandas profiling to perform EDA</h3><p>Pandas Profiling requires just one line of code to generate a comprehensive report with statistical summaries that helps to understand the dataset, its variables and relationships between them. The HTML report is interactive and can easily be shared with others even if they don’t know how to code.</p><p>Let’s generate a report from our data. Just type the code below.</p><pre>ProfileReport(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*IHkRJ08u_2BoMUcfH7ijzw.png" /></figure><p>With that one line of code, you can see a full report of missing values in the dataset, numerical variables statistics, frequencies summaries for categorical variable and relationships.</p><h3>Pandas Visualization</h3><p>As mentioned, Pandas is rich in data manipulation and analysis functions. Amongst this function is theplot function that you can use to make beautiful graphs. Let us look into the most common plots.</p><h4>1. Scatter Plot</h4><p>A scatterplot is a type of data display that shows the relationship between two numerical variables. To produce one using pandas, use plot function and specify kind to be scattered.</p><pre>df.plot(x=&#39;Age&#39;,y=&#39;ApproxHeight&#39;,kind=&#39;scatter&#39;,<br>        title=&#39;Students Age v/s Height&#39;,figsize=(10,6))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*570AxBnCYpGN7j4-Toa0iQ.png" /></figure><p>alternatively, you can use the following code to produce the same Pandas chart.</p><pre>df.plot.scatter(x=&#39;Age&#39;,y=&#39;ApproxHeight&#39;,<br>                title=&#39;Students Age v/s Height&#39;,figsize=(10,6))</pre><h4>2. Line Graph</h4><p>A line graph is common in time series, it’s used to visualize the change of a variable over time. Lets produce a line chart for age, approximate height and approximate weight from our data. Use loc function to select our variables of interest and plot function where kind=&#39;line&#39;</p><pre>plot_data=df.loc[:,[&quot;Age&quot;,&quot;ApproxHeight&quot;,&quot;ApproxWeight&quot;]]</pre><pre>plot_data.plot(kind=&#39;line&#39;,figsize=(12,6),<br>               title=&quot;Sample Line graphs from Students data&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*aU_iTMQgHJ96vfUCOXQZug.png" /></figure><h4>3. Histogram</h4><p>A histogram is an approximate representation of the distribution of numerical or categorical data. Producing one in pandas is as easy as the code below.</p><pre>df[&#39;Expense_Accommodation&#39;].hist(bins=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*Xj00N9HgBdz1L8XcllRoCg.png" /></figure><p>You can also do multiple histograms where you want to visualize two or more numerical variables distributions in one chart. Just add subplot=True and define your layout. For instance, lets visualize both accommodations and total semester expenses.</p><pre>plot_data=df.loc[:,[&quot;Expense_Accommodation&quot;,&quot;Expense_Semester&quot;]]</pre><pre>plot_data.plot(subplots=True, layout=(1,2),figsize=(12,5),bins=20,kind=&#39;hist&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*nWqTUIQQ1658SoWFBWVspw.png" /></figure><h4>3. Bar Charts</h4><p>A bar graph is used to presents categorical data with rectangular bars whose heights are proportional to their values. Let us create one from the previous grade variable.</p><pre>df[&#39;Previous_Exam_MeanGrade&#39;].value_counts().sort_index().plot(kind=&#39;bar&#39;,figsize=(7,5))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*hRLbZBrSseSTZPg5YoXYPA.png" /></figure><p>you can also make it horizontal by specifying that kind=&#39;barh&#39;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*mx4Uir4672KVoADBIwo8hg.png" /></figure><h3>Matplotlib Library</h3><p>making plots using matplotlib is slightly different from pandas. Matplotlib give you much flexibility for customizing your charts at the expense of writing more codes. we shall produce the same charts we did with pandas with matplotlib.</p><h4>1. Scatter Plots</h4><p>To create a scatter plot in Matplotlib we use the scatter function. We will first have to create a figure and an axis using plt.subplotthen define our plot a title and labels.</p><pre># create a figure and axis<br>fig, ax = plt.subplots(figsize=(11,5))</pre><pre># scatter the sepal_length against the sepal_width<br>ax.scatter(df[&#39;Age&#39;], df[&#39;ApproxHeight&#39;])<br># set a title and labels<br>ax.set_title(&#39;Students Dataset&#39;)<br>ax.set_xlabel(&#39;Age&#39;)<br>ax.set_ylabel(&#39;Weight&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*URpYUk2QMFNhEtbqNoNbyg.png" /></figure><h4>2. Line Charts</h4><p>Line charts in matplotlib are produced in the same manner as a scatter plot. In our case, we use the matplotlib.pyplot plot function to plot the line charts. We need to plot the same age, approximate weight and approximate height charts as in pandas. Here we shall use a for loop to draw each of the 3 line charts at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*US21wczdy3HF7BeY2sC8Ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*YNwj6sDoQPtJRvZNMoy_eA.png" /></figure><h4>3. Histogram</h4><pre>fig, ax = plt.subplots()<br>ax.hist(df[&#39;Expense_Accommodation&#39;])</pre><pre>ax.set_title(&#39;Accomodation Expenses Distribution&#39;)<br>ax.set_xlabel(&#39;Accomodation Expenses&#39;)<br>ax.set_ylabel(&#39;Frequency&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*NuK-nJXTob_grtVBDncIgA.png" /></figure><h3>Seaborn</h3><p>Seaborn is just fantastic. It is built on matplotlib and it allows us to make some prettier charts with fewer lines of codes. You gonna love it.</p><h4>1. Scatter plot</h4><p>in seaborn, you specify the size of your charts using matplotlib figure function. to make a scatter plot we just use seaborns scatterplot function. Note the argument; x-variable in x_axix, y- variable in y_axis,data-state your plotting dataset, hue- grouping variable. We use set_title function after creating the chart to title our graph.</p><pre>plt.figure(figsize=(11,5))</pre><pre>sns.scatterplot(x=&#39;ApproxHeight&#39;,y=&#39;Expense_Semester&#39;,<br>                data=df,hue=&quot;YearofStudy&quot;).set_title(&quot;Scatter plot for expenses against the year of joining campus&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*aG0OGQVXPK6KZMxYqSW5KQ.png" /></figure><h4>2. Regression plots</h4><p>Regression plots are used to visualize the relationship between two numerical variables as determined through regression. regplot draw a scatterplot of two variables, x and y, and then fit the regression model y ~ x and plot the resulting regression line and a 95% confidence interval for that regression.</p><p>let&#39;s make a regression plot to visualize the relationship between approximate weight and approximate height</p><pre>plt.figure(figsize=(10,5))<br>sns.regplot(x=&quot;ApproxHeight&quot;,y=&#39;ApproxWeight&#39;,data=df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*ksYc9yuyf2z-Bf8-a2HJ9w.png" /><figcaption>regression plot</figcaption></figure><h4>3. Histogram with a density plot</h4><p>With seaborn, its pretty easy to make a histogram with a desity plot. just use distplot function where kde=True</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*e7-6grVNYW9NAL0Ed5tlSg.png" /><figcaption>Histogram with a density plot</figcaption></figure><h4>4. Barplot</h4><p>Bar plots in seaborn are also very direct and easy to plot. Let us visualize the year of KCSE variable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*zu13vJfVf4mBV_KbGYjsHA.png" /></figure><h4>5. Box Plots</h4><p>A box plot is used to show the distribution of data based on five statistic summaries. minimum, first quartile, median, third quartile and maximum. Let plot a box plot for approximate weight distribution grouped by the year of study. we just need to use sns.boxplot function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*kFcn-0Bat3u1zeOadG4rvQ.png" /></figure><p>Thats pretty much what you need to know to get started with making impressive charts in python. But it will be nice to show how to create some other useful but not very popular charts in python</p><h3>Bonus</h3><h4>Heatmaps</h4><p>Heatmaps are some cool charts used to visualize a numerical variable using colour scales. <a href="https://en.wikipedia.org/wiki/Heat_map">Wikipedia</a> defines heatmaps as a graphical representation of data where the individual values contained in a matrix are represented as colours.</p><p>Let us use seaborn to create a heatmap to visualize the correlations between our numerical variables.</p><pre>plt.figure(figsize=(10,6))</pre><pre>## selecting the data with variables of interest  <br>plt_data=df.loc[:,[&#39;Age&#39;,&#39;ApproxHeight&#39;,&#39;ApproxWeight&#39;,<br>                   &#39;Expense_Semester&#39;,&#39;Expense_Accommodation&#39;]]</pre><pre>## Creating a heatmap<br>sns.heatmap(plt_data.corr(),annot=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*Qz1KcqHJN7AoO4YSD3CdIw.png" /></figure><p>each cell represents a correlation value between the two interacting variables. The colour index is shown by the bar on the right where the darker the colour the lower the correlation.</p><h4>Seaborn Pairplots</h4><p>Pair plots come in handy when carrying out EDA. They allow us to visualize the distribution of a single variable and relationship between two variables in a single matrix chart of histograms and scatterplots</p><p>You just need one line of code to produce one</p><pre>sns.pairplot(plt_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*NAK3j6PmrPBBTrRO1AOSaQ.png" /></figure><p>You can get the entire script <a href="https://gist.github.com/pyPRO2019/66fed3aa41d76c06605e0a6a4df4aeb3"><em>here</em></a><em>.</em></p><h3>Recommendation</h3><p>To enrich your data science skillset, I highly recommend you check out this cool site <a href="https://perfectresearchconsultancy.com/">https://perfectresearchconsultancy.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aee09809100" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>