<?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 Mohammad Mohtashim on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Mohtashim on Medium]]></description>
        <link>https://medium.com/@mohammadmohtashim?source=rss-7d8ce713c7a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wpcadq-z-3LvH3KcW7uzjw.jpeg</url>
            <title>Stories by Mohammad Mohtashim on Medium</title>
            <link>https://medium.com/@mohammadmohtashim?source=rss-7d8ce713c7a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:03:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammadmohtashim/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[Six Important Lessons from Storytelling with Data by Nussbaumer Knaflic-Part-2]]></title>
            <link>https://medium.com/analytics-vidhya/six-important-lessons-from-storytelling-with-data-by-nussbaumer-knaflic-part-2-737d8478bc0b?source=rss-7d8ce713c7a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/737d8478bc0b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Mohammad Mohtashim]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 12:28:20 GMT</pubDate>
            <atom:updated>2021-01-18T16:33:09.437Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this series of articles, I will be sharing a summary of the book Storytelling with Data by Nussbaumer Knaflic. All of the content is taken from her book but I have tried to summarise the content by explaining the six important lessons taught in the book regarding the subject matter. I hope these six lessons would go a long way in improving your visualization expertise and hence in the art of better storytelling from Data. This would be a series of articles, in each article I would be summarising one or two lessons. In this part, I will be summarising the third key lessons.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*q7Gwg7WnkRW4W3qT.png" /><figcaption>Image-0-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><h3>What is Clutter?</h3><p>In the third chapter, Knaflic elaborates upon clutter and how to avoid it in your own visualization. According, Knaflic clutter is, “these are visual elements that <strong>take up space</strong> but <strong>don’t increase understanding</strong>”[1]. The reason she believes clutter is an enemy of your visualization is that it does not convey any information to your audience while increasing the “cognitive load” which is basically, “processing that takes up mental resources but doesn’t help the audience understand the information”.</p><h3>Gestalt principles of visual perception</h3><p>Afterwards, she describes 5 key elements that make up common visual perception. She then uses this as a basis to further explain main issues related to clutter and then lays down detailed steps as to how to one can avoid it. The first element is, “<strong>Proximity</strong>”[1] which is that human tendency to think physically close object as belonging to the same group. The second element is “<strong>Similarity</strong>”[1] which means that, “Objects that are of similar colour, shape, size, or orientation are perceived as related or belonging to part of a group”[1]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*UWYMxTMlOPsLWitNuthI9w.png" /><figcaption>Figure-1-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>The third element is “<strong>Enclosure</strong>”[1] which is, “We think of objects that are physically enclosed together as belonging to part of a group”[1]. Further, the fourth element is “<strong>Closure</strong>”[1] which means human likes simplicity rather than complexity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*1lUHYzykTZ4-0CCECBxblg.png" /><figcaption>Figure-2-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>The final key element is “<strong>Continuity</strong>”[1], which is the human tendency to seek the most smooth path and even create one even if explicitly no such continuity exists.</p><h3>Main Causes of Clutter</h3><p>The author then uses these five key elements to elaborate upon what is actually clutter for human and how to avoid. The first cause that she mentions is the <strong>lack of visual order. </strong>This is basically no specific ordering and emphasising of the visualisation where everything is just spread white and grey:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*ZZDMI9D6tb306sWZxM4Brw.png" /><figcaption>Figure-3-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Clearly, the visualisation has no clear structuring and order which makes the conveying of information difficult to the user because it adds more complexity for the audience and also does not emphasis any sort of continuity for the audience. The author then improves this graph to improve its’ visual order and therefore reduce the clutter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*P9GWRT6z446HCrn0ODbV8g.png" /><figcaption>Figure-4-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Moreover, the above example also shows that a lack of alignment in any visualisation also adds to the clutter. Note as to how, in figure-4, the graph is centrally aligned which makes the visual interpretation smoother and hence easier. The author also talks about as to how many novices add data just for sake of adding data while leaving no leverage for “<strong>White Space</strong>”[1]. She mentions as to how “White space in visual communication is as important as pauses in public speaking”[1] &amp; “Can be used strategically to draw attention to the parts of the page that are not white space”[1].</p><p>Further, she elaborates that people use <strong>contrast</strong> <strong>randomly </strong>rather than <strong>strategically. Contrast </strong>can be used as a signal to the audience:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*K2KlrfgnZy71tdIBh9zNxQ.png" /><figcaption>Figure-5-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><h4>Decluttering Example</h4><p>Finally, she mentions six steps to avoid decluttering before finishing the chapter. The initial cluttered graph is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*gm0g8i3QCckQIg90dYlMFA.png" /><figcaption>Figure-6-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p><strong>After applying the six-steps which uses the five elements of visual perception and avoid the main causes of clutter:</strong></p><p>1- Remove chart border</p><p>2- Remove chart border</p><p>3- Remove data markers</p><p>4- Clean up axis labels</p><p>5- Label data directly</p><p>6- Leverage consistent colour</p><p>The final graph is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*PTD-bXBQSxPPOxBwoardUA.png" /><figcaption>Figure-7-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><h3>Conclusion</h3><p>In conclusion, this article summaries the third chapter in the book which is all about the causes of clutter and how to avoid it. I have tried to summaries the key ideas which capture the gist of the chapter so that you can easily apply the learning of the chapter and avoid the greatest enemy of any visualization.</p><p>In part three of this series of articles, I will discuss the fourth key lesson of the book.</p><h3>References</h3><blockquote>[1] Knaflic, Nussbaumer. <em>Storytelling with Data</em>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=737d8478bc0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/six-important-lessons-from-storytelling-with-data-by-nussbaumer-knaflic-part-2-737d8478bc0b">Six Important Lessons from Storytelling with Data by Nussbaumer Knaflic-Part-2</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[Six Important Lessons from Storytelling with Data by Nussbaumer Knaflic-Part-1]]></title>
            <link>https://medium.com/analytics-vidhya/six-important-lessons-from-storytelling-with-data-by-nussbaumer-knaflic-part-1-683f482ded9c?source=rss-7d8ce713c7a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/683f482ded9c</guid>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Mohammad Mohtashim]]></dc:creator>
            <pubDate>Tue, 07 Jul 2020 14:30:05 GMT</pubDate>
            <atom:updated>2020-07-08T14:49:58.844Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this series of articles, I will be sharing a short summary of the book Storytelling with Data by Nussbaumer Knaflic. All of the content is taken from her book but I have tried to summarise the content by explaining the six important lessons taught in the book regarding the subject matter. I hope these six lessons would go a long way in improving your visualization expertise and hence in the art of better storytelling from Data.This would be a series of articles ,in each article I would be summarising one or two lessons. In this part, I will be summarising the first two key lessons.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*KR43VJyOa2fNj-SPc54seQ.png" /><figcaption>Image-0-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><h3>1.Understand the context</h3><p>Nussbaumer explains how it is fundamental for you to understand the context for which you are going to use the data and generate value. Her tip is to ask three important questions to understand the context and then using this context to adapt your generated visualization.</p><p>a)<strong>Who</strong>?</p><p>She mentions repeatedly throughout the book that we must understand the audience for your visualisation. This way you will be able to adapt your visualisation according to the needs of your audience and avoid general graphs. Moreover, the needs of the audience allow us to be specific in using our data and hence generate better value.</p><p>b) <strong>What</strong>?</p><p>Firstly, you understand the underlying action that you want your audience to take by appreciating what do you need your audience to know or do? Afterwards, you ask what is the mechanism that you are going to use to communicate with your audience. Filtering out the most effective medium of communication to interact with your audience. The below illustration is quite effective to further elaborate the mentioned point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Jeijc_fmaNrKlizgRx9caQ.png" /><figcaption>Image 1-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Finally, you ask yourself as ‘what tone do you want your communication to set?’[1]</p><p>c) <strong>How</strong>?</p><p>Finally, this is the last question that you ask which is like the innermost layer of the series of questions you ask. You<strong> understand as what data will I need to use</strong> to elaborate my principle point which has been polished by asking the questions ‘What’ and ‘Who’.</p><p>Just to summarise, Nussbaumer Knaflic has given the following example to reflect the importance of understanding the context by asking the three mentioned questions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*zcoySkIZ6sjjSRn4ixJKvA.png" /><figcaption>Image 2-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Finally, she talks about the principle of <strong>3-minute Story </strong>and <strong>Big Idea</strong>. According to her, it is imperative you can summarise complete content that you would like to communicate in a 3-minute story which according to her is, ‘if you had only three minutes to tell your audience what they need to know, what would you say?’[1]. Moreover, the Big Idea is the <strong>main principle around which you are revolving around when utilizing the data to generate value for your audience.</strong> The idea of Big Idea is summarized well in the following illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*-AVndJu0wPRM5rg2IUP3Zg.png" /><figcaption>Image 3-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p><strong>Therefore, the first lesson is to understand the context and then embarking on your journey of utilizing the data as per the understood context.</strong></p><h3>2. Choosing an Effective Visualisation</h3><p>Next, Knaflic gives an important lesson which fundamentally teaches the reader to learn as to how to adapt to different choices of the graphs given the context. The author believes that the choice of the graph, according to the situation and data, is fundamentally important for effective communication. I will be restating all of the main graphs which she mentions and the situation she prescribes for the respective graphs.</p><p>1-<strong>Simple Text</strong>:</p><p>To my surprise, Knaflic warns that sometimes many people overdo it by bringing in the extra hassle of visualisation when the job is simple enough that it could be completed by the use of simple text. As she mentions,’ When you have just a number or two to share, a simple text can be a great way to communicate’[1]. To illustrate this, she gives the example as to how in April 2014 Pew Research Center used the following bar plot to compare the percentage of the married stay-at-home mothers with a working husband[1]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*s2N0wWPuChLdtLYEctHvrA.png" /><figcaption>Image-4-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>However, she shows how this is just overdoing as the same message could be delivered more effectively through simple text:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*l2C3dlx03Sq-fu4X6aGY0w.png" /><figcaption>Image-5- Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>2-<strong>Tables</strong>:</p><p>Tables are great when you want to communicate to a mixed audience whose interest lies in particular rows of tables. Further tables also to communicate in a detailed manner and the type of data being communicated could be diverse with the different metric systems. However, she warns that when using the table, your data must stand out and the design of the table must fade out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*NB6K5ZOgEqeLuXBLzaZYMw.png" /><figcaption>Image-6-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Knaflic encourages to use the Minimal borders as it allows the audience to not pay attention to extra clutter(more about this in later articles) and just focus on the data.</p><p>2a) <strong>Heatmap</strong></p><p>If you want to combine visual cue with the table then you can make use of colour to highlight the range of data and therefore making a heatmap. Mostly, there is a colour range and an associated key which is used to reflect the magnitude of the data(numbers) and consequently allow the audience to focus only on important rows. However, she suggests that the colour being used must be consistent and it must be not to dull or not too vibrant. She shows a good example of a heatmap with the proper use of the colour range:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*bJBb5LjVnWtQZ4cOu4bGzQ.png" /><figcaption>Image-7-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>3-<strong>Graphs</strong>:</p><p>She then states different types of graphs which can be used to deliver the value proposition of your data:</p><p>3a)- <strong>Scatterplot</strong>:</p><p>The scatterplot is mainly used to describe the relationship of two variables which are <strong>quantitative(continuous)</strong>. However, she also mentions how colour can be used in a scatterplot to highlight different aspects of the data. For example, she mentions as to how a scatterplot of miles and cost per mile can be used to highlight values which are above the average cost per mile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*v27MrGySyqxTvqgq8r-m4Q.png" /><figcaption>Image-8-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Just look as to how simple the scatterplot is with no added fanciness at all and how colour contrast has been used to highlight the main message of the data.</p><p>3b)- <strong>Line graph:</strong></p><p>The line graph is mostly used when you want to visualise time series data. Moreover, the line graph can be used to visualise either single series or multi-series data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*m6J3qY3B5PXjXCVq3ZNXSg.png" /><figcaption>Image-9-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>She emphasis that time-range interval(x-axis) must be consistent and therefore you should follow the same range for every time interval. For example, don’t follow the 10-year gap from the years 1970–2000 then start following one year gap. I know this mistake seems quite obvious but even I have been the victim of such a mistake in my journey of data science.</p><p>3c)- <strong>Slopegraph:</strong></p><p>According to author slope graph must be used when,’ <strong>when you have two time periods or points of comparison and want to quickly show relative increases and decreases or differences across various categories between the two data points</strong>’[1]. The use case of slope graph is self-explanatory, just remember that slope graph should be used when comparison at glance between different variables is more important than going into the details of the variable pattern over the years. The author shows the following example of a slope graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*H3Aou6CaomyWA2x4k1hl2A.png" /><figcaption>Image-10-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>However, slope graph can become confusing if you have too many lines therefore, in this case, it is better to make use of colour to highlight a particular aspect of the underlying data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*qrrtsUH4coghuFRrZq2-qw.png" /><figcaption>Image-11-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>4- <strong>Bars</strong></p><p>The bar should be used when you want to plot categorical data over different groups. However, the author states how many people tend to understate the importance of bars by labelling them <strong>as too simple</strong>. However, this should be avoided because the power of bars could be leveraged to represent the relationships among different categorical variables(qualitative variables). Furter the advantage of bars is that they are too easy and simple to understand.</p><p>One of the major tips when constructing bars is to have a zero baseline to make the comparison easier and unbiased between two bars. As shown in the example below that the non-zero baseline could distort the relative comparison of two bars:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*puyRm8kM4BbtMnKkzeDA5g.png" /><figcaption>Image-12-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Further, the authors also recommend that the width of the bars must not be greater than the white space between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*6JEqtbr4OG5M2Qf4k9eEPQ.png" /><figcaption>Image-13-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Now, I will briefly some variation of bars before ending this article:</p><p>4a)-<strong>Stacked vertical bar chart</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*WLf59JnS6hjN82FB1FgYUg.png" /><figcaption>Image-14-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>The author warns that stack vertical bar charts can become overwhelming as the comparison across different subcomponents is difficult, as shown in the above picture that comparing the blue region, when its near baseline, is easier. Therefore, be extra cautious when using a stacked vertical bar chart.</p><p>4b)-<strong>Waterfall chart</strong>:</p><p>It was the first time through this book that I was exposed to this variation of the bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*60N4McNUqpmSj_Eoj_ThKQ.png" /><figcaption>Image-15-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>The example author gives is as to how the headcount of the employees changed over one year(where x-axis shows the reasons for respective additions and deductions). Even though at first glance water chart might seem complex, but can be useful if you want to explain as to how the count of a variable changed over a specific time and what were the reasons for the change in the count.</p><p>4c)-<strong>Stacked horizontal bar chart</strong>:</p><p>The advantage of horizontal bar change is that it makes it easier to read the name of categories especially if they are longer. Further, authors state that most of the reading is done from left to right, therefore, horizontal bar chart allows the reader to first process the categories and then look at the data, which makes the processing of the data easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*eiPyd67J5-SiSo9J5AJfZg.png" /><figcaption>Image-16-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Moreover, the authors believe that <strong>stacked </strong>horizontal bar graphs are easier to process, as comparing the sub-components across the bar is easier because you get a consistent baseline from both far left and far right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*3HHuOsTQQokVYX6afjz2Fg.png" /><figcaption>Image-17-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>5-<strong>Area</strong>:</p><p>Another not so common graphs she mentions is Area graph. Even though her general advice is to avoid such graphs as, “Humans’ eyes don’t do a great job of attributing quantitative value to two‐dimensional space, which can render area graphs harder to read than some of the other types of visual displays we’ve discussed”[1]. However, she does suggest that when you need to ‘compare numbers of vastly different magnitudes’[1], the 2d aspect of Area graph makes the comparison more compact as compared to 1d bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*eN7ltuw2DOyXy1z8oaVu9w.png" /><figcaption>Image-18-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p><strong>WHICH GRAPHS TO AVOID?</strong></p><p>1-<strong>Pie Charts</strong>:</p><p>Pie chart makes the comparison of different proportions very difficult especially if two proportions are quite close to each other. The reason for this difficultly is that the pie chart is generally hard to read. As an example, she gives the following pie chart and asks the reader to answer ‘Which proportion is the largest’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*qYr-ZZ_GpKQMmY8E-LyjHQ.png" /><figcaption>Image-19(Can you tell me which is the larger pie?)-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*V77nvfbj7tmibpBGCBg-mg.png" /><figcaption>Image-20(No, Supplier B is not the largest)-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Even though labels can be used but still the pie chart has a lot of clutter(more on this later) therefore is not a good way of telling your data story. Further, a good and better alternative to pie chart is the horizontal bar graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*NNfBeCw5_1hmPQFE56dDSQ.png" /><figcaption>Image-21(Same Information on Bar Chart, Isn’t comparison easier now?)-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>Moreover, she also prohibits, for the same reasons, another visual treat i.e <strong>Donut chart</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*ZWQ075xhMpWntV2IxOdRww.png" /><figcaption>Image-22-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>2- <strong>Never use 3D as an effect</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*YN0ssxAmPUXcaMh7D7W12w.png" /><figcaption>Image-23-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>The 3d effect adds extra clutter and unnecessary elements like side, floor panels, shadows. Moreover, reading off the axis with the 3d effect is also an extra hassle(just see the above bar chart). Therefore the author prohibits the use of 3d effect. However, three-dimensional graphs are legitimate in the case of three-dimension plotting.</p><p>3-<strong>Secondary y‐axis: generally not a good idea</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*oT7y3-8dWMcbVQYAOgOG-g.png" /><figcaption>Image-24-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><p>This again makes reading the data more time consuming and is difficult to understand. The author proposes two alternatives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*s-B3p7EMzz8qKm3qxefYyw.png" /><figcaption>Image-25-Courtesy of Storytelling with Data by Nussbaumer Knaflic</figcaption></figure><h3>Conclusion:</h3><p>In conclusion, this article summarises the first two key lessons of the book Storytelling with Data by Nussbaumer Knaflic. The first is to always appreciate the importance of context and fully understand it before embarking on your visualisation. Second, is that given a wide choice of graphs, you must choose a graph which best suits your context and even that choice should be modified in a way which makes the communication more transparent and easier.</p><p>In part two of this series of articles, I will discuss the third key lesson of the book.</p><h3>References:</h3><p>[1] Knaflic, Nussbaumer. <em>Storytelling with Data</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=683f482ded9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/six-important-lessons-from-storytelling-with-data-by-nussbaumer-knaflic-part-1-683f482ded9c">Six Important Lessons from Storytelling with Data by Nussbaumer Knaflic-Part-1</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[Easily Implement Different Transformers through Hugging Face]]></title>
            <link>https://medium.com/analytics-vidhya/easily-implement-different-transformers-through-hugging-face-e471035e9c86?source=rss-7d8ce713c7a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e471035e9c86</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Mohammad Mohtashim]]></dc:creator>
            <pubDate>Sun, 28 Jun 2020 15:43:01 GMT</pubDate>
            <atom:updated>2020-07-03T11:01:35.506Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Transformers is the state of the art model which have been used to solve novel NLP tasks ranging from sentiment analysis to questions/answering in a very efficent way. However, transformers at its very basic is just stacks of Encoder Layers of Attention Mechanism. Implementing it from scratch could be quite difficult and challenging even with the use of DL frameworks such as Pytorch or Tensorflow. However hugging face has made it quite easy to implement various types of transformers. In this article, I am going to show to you as how through hugging face library you can easily implement transformers in Tensorflow(Keras).</blockquote><h3><strong>What you need:</strong></h3><p>Firstly you need to install the hugging face library which is really easy. Just simply pip install it:</p><pre>pip install transformers </pre><p>Secondly, you will be needing the latest TensorFlow version which can also be easily installed through pip.</p><p><strong>Data:</strong></p><p>For the purpose of testing and implementing different transformers, I have used data from a kaggle competition. It is a recent competition in which I took a part called <a href="https://www.kaggle.com/c/jigsaw-multilingual-toxic-comment-classification">jigsaw-multilingual-toxic-comment-classification</a>. However, it is not compulsory that you use the same data, as the following implementation can be easily adapted to any text data.</p><p>This competition gave different comments and our task was to detect whether that specific comment is toxic or not. Therefore this is a binary classification task.</p><p><strong>Heavy Compute Power:</strong></p><p>Also Note that transformers have millions of parameters, therefore I utilized the TPUS given by Kaggle Kernel to train my model. Alternatively, you could use google colab to follow the implementation of this article, given that you do not have a local powerful machine.</p><h3><strong>Let&#39;s Have Fun Implementing Transformers:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQQ9KJMud6uGsv82XNU3TA.png" /><figcaption>Image Courtesy <a href="https://huggingface.co/front/thumbnails/models.png">https://huggingface.co/front/thumbnails/models.png</a></figcaption></figure><p><strong>Imports</strong></p><pre>import numpy as np <em># linear algebra</em><br>import pandas as pd <em># data processing, CSV file I/O (e.g. pd.read_csv)</em><br>import tensorflow as tf<br>import tensorflow_hub as hub<br>from tqdm import tqdm<br>from tqdm import tqdm_notebook<br>from sklearn.metrics import auc<br>from sklearn.metrics import classification_report<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br>from transformers import AutoTokenizer,BertTokenizer,TFBertModel,TFOpenAIGPTModel,OpenAIGPTTokenizer,DistilBertTokenizer, TFDistilBertModel,XLMTokenizer, TFXLMModel<br>from transformers import TFAutoModel, AutoTokenizer<br>from kaggle_datasets import KaggleDatasets<br>from sklearn.metrics import roc_curve,confusion_matrix,auc<br>from tokenizers import Tokenizer, models, pre_tokenizers, decoders, processors<br><em># Input data files are available in the read-only &quot;../input/&quot; directory</em><br><em># For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory</em><br>import matplotlib as mpl<br><br><br>from sklearn.feature_extraction.text import CountVectorizer<br>from sklearn.metrics import confusion_matrix, accuracy_score<br>from sklearn.model_selection import train_test_split<br><br>from tensorflow.keras.preprocessing.text import Tokenizer<br>from tensorflow.keras.preprocessing.sequence import pad_sequences<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import *<br>from tensorflow.keras.initializers import Constant</pre><p><strong>Which Transformers:</strong></p><p>The following Transformers Architecture have been tested in the notebook</p><p>1-BERT</p><p>2-OpenAIGPT</p><p>3-DistillBERT</p><p>4-XLM</p><p>5-XLMRobertaLarge</p><p>Don&#39;t worry about the implementation of all these transformers. The implementation is straightforward and similar.</p><p><strong>Hyperparameters Used:</strong></p><pre>EPOCHS=2</pre><pre>max_seq_length = 192<br>LEARNING_RATE=1e-5<br>early_stopping=early_stopping = tf.keras.callbacks.EarlyStopping(<br>    monitor=&#39;val_loss&#39;, <br>    verbose=1,<br>    patience=10,<br>    mode=&#39;max&#39;,<br>    restore_best_weights=True)</pre><p><strong>Encoding Function:</strong></p><p>Every transformer encodes each sentence. I hope you do understand what it means to encode the sentence. If not then they are numerous good resource on the internet to understand the encoding. At a very basic level, encoding means to convert raw text data into numerical data by assigning a unique integer to each individual word(tokens) in our corpus. However, the transformer encoding is a little bit more complex as it also uses character level encoding where an unknown word is broke into individual characters and then encoded. However, I will not be further going into the details of how transformers encoding works as it quite detailed. It is just safe to say that the next function basically converts each sentence in your data into a list of special integers which are understandable by the various transformers:</p><pre>def single_encoding_function(text,tokenizer,name=&#39;BERT&#39;):<br>    input_ids=[]<br>    if name==&#39;BERT&#39;:<br>        tokenizer.pad_token =&#39;[PAD]&#39;<br>    elif name==&#39;OPENAIGPT2&#39;:<br>        tokenizer.pad_token=&#39;&lt;unk&gt;&#39;<br>    elif name==&#39;Transformer XL&#39;:<br>        print(tokenizer.eos_token)<br>        tokenizer.pad_token= tokenizer.eos_token<br>    elif name==&#39;DistilBert&#39;:<br>        tokenizer.pad_token=&#39;[PAD]&#39;<br>    <br>for sentence <strong>in</strong> tqdm(text):       encoded=tokenizer.encode(sentence,max_length=max_seq_length,<br>pad_to_aax_length=True)## this is inside the loop<br>        input_ids.append(encoded)<br>    return input_ids</pre><p><strong>Making Data Pipeline:</strong></p><p>a) Making Arrays:</p><pre>X_train=np.array(single_encoding_function(train_raw[&#39;comment_text&#39;].values.tolist(),tokenizer,name=&quot;BERT&quot;))<br>y_train=np.array(train_raw[&#39;toxic&#39;])<br>X_valid=np.array(single_encoding_function(valid_raw[&#39;comment_text&#39;].values.tolist(),tokenizer,name=&quot;BERT&quot;))<br>y_valid=np.array(valid_raw[&#39;toxic&#39;])<br>X_test=np.array(single_encoding_function(test_raw[&#39;content&#39;].values.tolist(),tokenizer,name=&quot;BERT&quot;))</pre><pre>steps_per_epoch = X_train.shape[0] // BATCH_SIZE</pre><p>The above code is self-explanatory, I am just taking the raw text data and giving it as input to the single encoding function and then converting the result into an array of encoded tokens which is the final data given to our TensorFlow pipelines.</p><p>b)Making Tensorflow pipelines:</p><pre>def make_data():<br>    train = (<br>        tf.data.Dataset<br>        .from_tensor_slices((X_train, y_train))<br>        .repeat()<br>        .shuffle(2048)<br>        .batch(BATCH_SIZE)<br>        .prefetch(AUTO))<br><br>    valid = (<br>        tf.data.Dataset<br>        .from_tensor_slices((X_valid, y_valid))<br>        .batch(BATCH_SIZE)<br>        .cache()<br>        .prefetch(AUTO)<br>    )<br><br>    test = (<br>        tf.data.Dataset<br>        .from_tensor_slices(X_test)<br>        .batch(BATCH_SIZE)<br>    )<br>    return train,valid,test </pre><p><strong>Actual Implementation with Keras:</strong></p><p>The next step is really important therefore carefully look at it:</p><pre>def build_model(transformer_layer,max_len=max_seq_length):<br>    input_word_ids = tf.keras.layers.Input(shape=(max_len,), dtype=tf.int32, name=&quot;input_word_ids&quot;)<br>    sequence_output = transformer_layer(input_word_ids)[0]<br>    <br>    cls_token = sequence_output[:, 0, :]<br>    out = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(cls_token)<br>    <br>    model = tf.keras.Model(inputs=input_word_ids, outputs=out)<br>    <br>    <br>    return model</pre><p>The code block is important therefore let me further elaborate upon it. Firstly there is an input layer which takes the <strong>encoded input of the given transformer </strong>for a particular instance. Afterwards, the input token is fed into the main transformer layer(which is loaded from a function named compile_model defined in the coming coding block). I wanted to make this code reusable for all of the transformers therefore instead of copying and pasting the whole model for each transformer, the only different layer is this transformer layer for each variant of the transformer. The transformer layer then outputs the sequence output. However, this is a classification task and therefore from sequence output, we will only be extracting the CLS(Classification token) for each word in the given sentence. This cls_token is then fed into the sigmoid layer which is used to differentiate between the toxicity of a given sentence.</p><p>Please note that you could have made the model more complex by adding more layers but I did not as it would have made our model more complex and would have taken more training time.</p><h4><strong>The next section only shows how to plot-relevant and useful graphs for each transformer’s performance so that one could run a comparative analysis of different models. They do have any bearing with the main implementation of any transformer.</strong></h4><p><strong>Plotting Useful Graphs to Compare Performance:</strong></p><p>a) Plotting Loss and Metric Graphs:</p><pre>mpl.rcParams[&#39;figure.figsize&#39;] = (12, 10)<br>colors = plt.rcParams[&#39;axes.prop_cycle&#39;].by_key()[&#39;color&#39;]<br><br>def plot_loss(history):<br><em># Use a log scale to show the wide range of values.</em><br>    plt.semilogy(history.epoch,  history.history[&#39;loss&#39;],<br>               color=&#39;red&#39;, label=&#39;Train Loss&#39;)<br>    plt.semilogy(history.epoch,  history.history[&#39;val_loss&#39;],<br>          color=&#39;green&#39;, label=&#39;Val Loss&#39;,<br>          linestyle=&quot;--&quot;)<br>    plt.xlabel(&#39;Epoch&#39;)<br>    plt.ylabel(&#39;Loss&#39;)<br>  <br>    plt.legend()<br>    <br>    <br>def plot_metrics(history):<br>    metrics =  [&#39;loss&#39;, &#39;auc&#39;, &#39;precision&#39;, &#39;recall&#39;]<br>    for n, metric <strong>in</strong> enumerate(metrics):<br>        name = metric.replace(&quot;_&quot;,&quot; &quot;).capitalize()<br>        plt.subplot(2,2,n+1)<br>        plt.plot(history.epoch,  history.history[metric], color=colors[0], label=&#39;Train&#39;)<br>        plt.plot(history.epoch, history.history[&#39;val_&#39;+metric],<br>                 color=colors[0], linestyle=&quot;--&quot;, label=&#39;Val&#39;)<br>        plt.xlabel(&#39;Epoch&#39;)<br>        plt.ylabel(name)<br>        if metric == &#39;loss&#39;:<br>            plt.ylim([0, plt.ylim()[1]])<br>        elif metric == &#39;auc&#39;:<br>            plt.ylim([0.8,1])<br>        else:<br>            plt.ylim([0,1])<br><br>        plt.legend()</pre><p>Both of the function takes the history of the training then plot the relevant function for loss and metrics i.e AUC, recall and precision over the number of epochs.</p><p>b) Plotting Confusion Matrix and ROC Curve:</p><p>The next code block takes the y_predicted from the model and ground truth to make a confusion matrix and ROC Curve for the model.</p><pre>def plot_cm(y_true, y_pred, title):<br>    <em>&#39;&#39;&#39;&#39;</em><br><em>    input y_true-Ground Truth Labels</em><br><em>          y_pred-Predicted Value of Model</em><br><em>          title-What Title to give to the confusion matrix</em><br><em>    </em><br><em>    Draws a Confusion Matrix for better understanding of how the model is working</em><br><em>    </em><br><em>    return None</em><br><em>    </em><br><em>    &#39;&#39;&#39;</em><br>    <br>    figsize=(10,10)<br>    cm = confusion_matrix(y_true, y_pred, labels=np.unique(y_true))<br>    cm_sum = np.sum(cm, axis=1, keepdims=True)<br>    cm_perc = cm / cm_sum.astype(float) * 100<br>    annot = np.empty_like(cm).astype(str)<br>    nrows, ncols = cm.shape<br>    for i <strong>in</strong> range(nrows):<br>        for j <strong>in</strong> range(ncols):<br>            c = cm[i, j]<br>            p = cm_perc[i, j]<br>            if i == j:<br>                s = cm_sum[i]<br>                annot[i, j] = &#39;<strong>%.1f%%\n%d</strong>/<strong>%d</strong>&#39; % (p, c, s)<br>            elif c == 0:<br>                annot[i, j] = &#39;&#39;<br>            else:<br>                annot[i, j] = &#39;<strong>%.1f%%\n%d</strong>&#39; % (p, c)<br>    cm = pd.DataFrame(cm, index=np.unique(y_true), columns=np.unique(y_true))<br>    cm.index.name = &#39;Actual&#39;<br>    cm.columns.name = &#39;Predicted&#39;<br>    fig, ax = plt.subplots(figsize=figsize)<br>    plt.title(title)<br>    sns.heatmap(cm, cmap= &quot;YlGnBu&quot;, annot=annot, fmt=&#39;&#39;, ax=ax)<br><br>def roc_curve_plot(fpr,tpr,roc_auc):<br>    plt.figure()<br>    lw = 2<br>    plt.plot(fpr, tpr, color=&#39;darkorange&#39;,<br>             lw=lw, label=&#39;ROC curve (area = <strong>%0.2f</strong>)&#39; %roc_auc)<br>    plt.plot([0, 1], [0, 1], color=&#39;navy&#39;, lw=lw, linestyle=&#39;--&#39;)<br>    plt.xlim([0.0, 1.0])<br>    plt.ylim([0.0, 1.05])<br>    plt.xlabel(&#39;False Positive Rate&#39;)<br>    plt.ylabel(&#39;True Positive Rate&#39;)<br>    plt.title(&#39;Receiver operating characteristic example&#39;)<br>    plt.legend(loc=&quot;lower right&quot;)<br>    plt.show()</pre><p><strong>Finally :D Training Different Transformer:</strong></p><p>a) Compile the Model:</p><pre>def compile_model(name):<br>    with strategy.scope():<br>        METRICS = [<br>          tf.keras.metrics.TruePositives(name=&#39;tp&#39;),<br>          tf.keras.metrics.FalsePositives(name=&#39;fp&#39;),<br>          tf.keras.metrics.TrueNegatives(name=&#39;tn&#39;),<br>          tf.keras.metrics.FalseNegatives(name=&#39;fn&#39;), <br>          tf.keras.metrics.BinaryAccuracy(name=&#39;accuracy&#39;),<br>          tf.keras.metrics.Precision(name=&#39;precision&#39;),<br>          tf.keras.metrics.Recall(name=&#39;recall&#39;),<br>          tf.keras.metrics.AUC(name=&#39;auc&#39;)]<br>        if name==&#39;bert-base-uncased&#39;:<br>            transformer_layer = (<br>                TFBertModel.from_pretrained(name)<br>            )<br>        elif name==&#39;openai-gpt&#39;:<br>            transformer_layer = (<br>                TFOpenAIGPTModel.from_pretrained(name)<br>            )<br>        elif name==&#39;distilbert-base-cased&#39;:<br>            transformer_layer = (<br>                TFDistilBertModel.from_pretrained(name)<br>            )<br>        elif name==&#39;xlm-mlm-en-2048&#39;:<br>            transformer_layer = (<br>                TFBertModel.from_pretrained(name)<br>            )<br>        elif name==&#39;jplu/tf-xlm-roberta-large&#39;:<br>            transformer_layer = (<br>                TFAutoModel.from_pretrained(name)<br>            )<br>        model = build_model(transformer_layer, max_len=max_seq_length)<br>        model.compile(optimizer=tf.keras.optimizers.Adam(<br>        learning_rate=LEARNING_RATE), loss=&#39;binary_crossentropy&#39;, metrics=METRICS)<br>    return model</pre><p>The above code block is really simple. As shown it takes the name of the transformer for which you want to compile the model then loads the relevant transformer layer from hugging face library. Afterwards, it feeds the loaded transformer layer to the function build_model(defined above) and then we compile the model. Please note I have also created a list named METRICS as I want to check model performance on different metrics rather restricting myself to only accuracy.</p><p>d) Actual Training:</p><p>The actual training process is now the same for each transformer. You just need to type in the relevant name and call the desire functions in order to fit the model.</p><p>In this article, I won&#39;t be showing the output graphs for every model as it would take a lot of space, however, I will show you the graphs for only one transformer i.e Distilled BERT. Same Graphs can be generated for other models in a similar fashion.</p><p>The next code blocks show how to use the functions defined above for distilled BERT. In order to train any other transformer, you just need to change the string named ‘distil-base-cased’ and ‘DistilBert’(highlighted in bold) to the relevant transformer name.</p><pre><em># # First load the real tokenizer</em><br>tokenizer = DistilBertTokenizer.from_pretrained(<strong>&#39;distilbert-base-cased&#39;</strong>)</pre><pre>X_train=np.array(single_encoding_function(train_raw[&#39;comment_text&#39;],tokenizer,<strong>&#39;DistilBert&#39;</strong>))#change the name<br>y_train=np.array(train_raw[&#39;toxic&#39;])<br>X_valid=np.array(single_encoding_function(valid_raw[&#39;comment_text&#39;],tokenizer,<strong>&#39;DistilBert&#39;</strong>))#change the name<br>y_valid=np.array(valid_raw[&#39;toxic&#39;])<br>X_test=np.array(single_encoding_function(test_raw[&#39;content&#39;],tokenizer,<strong>&#39;DistilBert&#39;</strong>))#change the name</pre><pre>train,valid,test=make_data()</pre><pre>steps_per_epoch = X_train.shape[0] // BATCH_SIZE</pre><pre>model=compile_model(<strong>&#39;distilbert-base-cased&#39;</strong>)#change the name<br>print(model.summary())<br><br>history=model.fit(<br>    train,steps_per_epoch=steps_per_epoch,<br>    epochs=EPOCHS,callbacks=[early_stopping], validation_data=valid<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*kQegPh6HQ8B-ieONnB5xCg.png" /><figcaption>Model Summary &amp; Training Information</figcaption></figure><p>The model would start training and would take much time depending on your data and compute power. Finally, you take the history and use the relevant functions defined above to generate the graphs:</p><pre>plot_loss(history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*N-KP-5zSDoJ3JYP0lsr1Ow.png" /><figcaption>Loss Over two Epochs for Distil-BERT</figcaption></figure><pre>plot_metrics(history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*mMX5azrJFp_PBlta6msWWw.png" /><figcaption>Loss, AUC, Precision and Recall over Epochs</figcaption></figure><pre>y_predict=model.predict(valid, verbose=1)<br>y_predict[ y_predict&gt; 0.5] = 1<br>y_predict[y_predict &lt;= 0.5] = 0<br>plot_cm(y_valid, y_predict, &#39;Distil BERT Performance-Confusion Matrix&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*-uJRAurMINyIC_o-p5zHkA.png" /><figcaption>Confusion Matrix for Distil-BERT</figcaption></figure><pre>y_predict_prob=model.predict(valid, verbose=1)<br>fpr, tpr, _ = roc_curve(y_valid,y_predict_prob)<br>roc_auc = auc(fpr, tpr)<br>roc_curve_plot(fpr,tpr,roc_auc)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*cEMpoJE_RThl-5dannOgWw.png" /><figcaption>ROC for Distil BERT</figcaption></figure><h3>Conclusion:</h3><p>Well, hugging face has really made transformer implementation quite easy. However, it&#39;s really important that you understand the underlying working of the transformer as well because otherwise the above implementation would only be a black box and you would not be able to further tune and optimize your model. The whole code is available on my kaggle account as well:<a href="https://www.kaggle.com/keenborder/comparing-different-transformers-lstms">https://www.kaggle.com/keenborder/comparing-different-transformers-lstms</a> and there are also links if you want to understand the transformer in more details.</p><p>I worked really hard for this article, therefore, please clap if you enjoyed it and want to see more awesome NLP content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e471035e9c86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/easily-implement-different-transformers-through-hugging-face-e471035e9c86">Easily Implement Different Transformers🤗🤗 through Hugging Face</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>
    </channel>
</rss>