<?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 Cees Roele on Medium]]></title>
        <description><![CDATA[Stories by Cees Roele on Medium]]></description>
        <link>https://medium.com/@cees-roele?source=rss-41bb53ef046d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TEwhJUNB4hkwxEv8Wx4EVg.jpeg</url>
            <title>Stories by Cees Roele on Medium</title>
            <link>https://medium.com/@cees-roele?source=rss-41bb53ef046d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:11:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cees-roele/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[Creating Multi Page Applications in Django with React]]></title>
            <link>https://cees-roele.medium.com/creating-multi-page-applications-in-django-with-react-837cb98ce45e?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/837cb98ce45e</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 09:03:29 GMT</pubDate>
            <atom:updated>2023-08-21T09:03:29.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article, I show how I used React, webpack, and Django to add dynamic features to a content-presenting Django-based website. The website’s data presentation and navigation are primarily provided by Django templates. React components are inserted to make specific interaction within a page possible.</p><h3>A Django website for data and transformations</h3><p>I research a dataset consisting of some sixteen thousand texts. Using Django I have created a website to present the texts and make them searchable. I apply numerous methods to draw conclusions from the texts. To understand how an analysis applies of any of the individual texts, I display transformations of those texts within the page. Below you see an image from the site where standard Named Entity Recognition (NER) is applied to a text. The present article focuses on using React for creating the set of radio buttons seen at the top and having clicking them display a transformed version of the content at the bottom.</p><figure><img alt="Screen displaying radiobuttons and transformed content." src="https://cdn-images-1.medium.com/max/1024/1*JQuoPQjy78x486_oBZzeCg.png" /><figcaption>Image by author</figcaption></figure><h3>Solutions presented in this article</h3><p>The focus of this article is on integrating interactive functionality developed with React with a templating-system. Although I refer to Django, this is mostly for illustrating the context, as what is presented here applies to using React with any templating system.</p><p>To integrate React with a <em>Multi Page Application</em> (MPA), where a template-system is leading to get data, we need to overcome a few hurdles which require design patterns atypical for React development.</p><p>I will explain the issues below and for summarise them by their solutions:</p><ol><li><em>Pass parameters and configuration</em> from Django templates to React</li><li>Functionally <em>link React components</em> spread over a template</li><li><em>Develop and deploy</em> React components for using with Django templates</li></ol><h3>Wait! Is this a good idea?</h3><p>React is <a href="https://www.bairesdev.com/blog/react-spa-single-page-application">often used to create Single Page Applications</a> (SPAs). This means that a webbrowser loads one page after which all interaction takes place within this page. Using Django-templating typically results in a <em>Multi Page Application</em> (MPA), meaning that there are different pages, identified by URLs, which are loaded from scratch.</p><p>Here are my reasons of creating an MPA using Django-templates:</p><ol><li>Emphasis of the website is more on content presentation than on interaction.</li><li>Django templates offer easier development and debugging of content presentation than React components.</li><li>No API creation is needed to bring data from the python backend to the Django template frontend. There is one full-stack developer for frontend and backend, so there is no organisational need for a clean interface.</li></ol><p>But is React the right instrument to create interactivity in the frontend for these requirements? For the relatively simple interactions presented here, <a href="https://jquery.com/">jQuery</a> might be <a href="https://www.linkedin.com/pulse/jquery-vs-react-difference-between-2023-khadar-valli/">more appropriate</a>.</p><p>My reasons for using React:</p><ul><li>Good frontend development environment</li><li>Clean declarative programming style</li><li>Future: I expect the amount of interaction of the site to be extended in the future and to become more complicated</li></ul><h3>Basics and problem formulation</h3><p>The focus of the present article is on integration, rather than on the specific components. I will give their implementations later, but for now I will present them as ready-made components and refer to them through <em>Javascript Syntax Extension</em> (JSX) notation, also called <em>JavaScript XML</em>.</p><p>React components can be represented as tags and these tags can be combined and given attributes in XML fashion. Let’s assume the availability of the following two components:</p><ul><li>A group of radio buttons to select a transformation function</li><li>An article identified by an id and given the name of a transformation function. Here “ner” stands for “Named Entity Recognition”, referring to a transformation function which highlights named entities in a text. In the screen image above, content is transformed using the <a href="https://spacy.io/usage/visualizers">displaCy visualizer</a>.</li></ul><p>The two components look like this.</p><pre>&lt;RadioButtonGroup /&gt;<br>&lt;Article article_id=&quot;48&quot; transformer=&quot;ner&quot; /&gt;</pre><p>Let’s assume we have a HTML file having an element with the id <em>content</em>.</p><pre>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;React replaces #content&lt;/title&gt;&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div id=&quot;content&quot; /&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now we create the code to bring React/javascript and HTML together. We identify the <em>content</em> element with <em>getElementById(..)</em>, create a root node in the React Virtual DOM tree using <em>ReactDOM.createRoot(..)</em>, and render our components. The rendered components will replace the div with the id <em>content</em> in the HTML.</p><p>Note that we can mix javascript and JSX notation.</p><pre>const domContainer = document.getElementById(&#39;content&#39;);<br>rootContent = ReactDOM.createRoot(domContainer);<br>rootContent.render(<br>  &lt;div&gt;<br>    &lt;RadioButtonGroup&gt;<br>    &lt;Article article_id=&quot;48&quot; transformer=&quot;ner&quot; /&gt;<br>  &lt;/div&gt;<br>);</pre><p>This works, but leaves us with a few problems to overcome:</p><ol><li>The <em>article_id</em> and <em>transformer</em> parameters are now coded into the React side, but we want to define them in our template and then pass them on to React.</li><li>The <em>RadioButtonGroup</em> and <em>Article</em> components now reside under the same HTML DOM element <em>content</em>, but we want them in separate locations on the page with template-controlled content or HTML in between.</li><li>In practice, the React components are not a given. To write their code, we need a comfortable development environment and we need deployment to our template system.</li></ol><h3>1. Passing parameters from a template to React</h3><p>React kind of lives in its own “bubble”. How can we bring parameters from the outside in? The solution is that we should pass any parameters through the HTML which is under control of the template system.</p><p>Think of the above example of a HTML file where a React component is injected into a HTML div element with id <em>content</em>. Instead of using the HTML element as a mere placeholder of which only the <em>id</em> attribute is relevant, we will now use it to pass data:</p><pre>&lt;div id=&quot;content&quot; data-article-id=&quot;48&quot; data-transformer=&quot;ner&quot;&gt;&lt;/div&gt;</pre><p>Any attribute name will do, but for clarity, we use the <a href="https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes">data-*</a> convention. Instead of just injecting the component into the HTML, we will now first read data from it:</p><pre>// React code<br>const domContainer = document.getElementById(&#39;content&#39;);<br>// Read data from HTML attributes<br>let article_id = domContainer.getAttribute(&quot;data-article-id&quot;);<br>let transformer = domContainer.getAttribute(&quot;data-transformer&quot;);<br><br>const root = ReactDOM.createRoot(domContainer);<br>root.render(<br>  &lt;Article article_id={article_id} transformer={transformer} /&gt;<br>);</pre><p>As the HTML is controlled by our template system we can dynamically set the attribute values, where the template variables <em>article_id</em> and <em>transformer</em> are evaluated using double curly brackets in Django.</p><pre>&lt;!-- Django template --&gt;<br>&lt;div  id=&quot;content&quot; <br>      data-article-id=&quot;{{ article_id }}&quot; <br>      data-transformer=&quot;{{ transformer }}&quot;<br>&gt;</pre><p>We can do something similar for the <em>RadioButtonGroup</em>. We want the interaction between selection and the Article group to be controlled by React, but the configuration of what options are available should be controlled by Django. E.g. if we add a new transformation function in the Django backend, we want to just change the Django template, not recreate and re-deploy the React frontend application.</p><p>We can pass such a configuration in the body of a div tag in the template, for which we now set the id to <em>transformerchoice</em>:</p><pre>&lt;!-- Django template --&gt;    <br>&lt;div id=&quot;transformerchoice&quot;&gt;<br>        {&quot;radiobuttons&quot;: [<br>            [&quot;Raw&quot;, &quot;raw&quot;, true],<br>            [&quot;NER&quot;, &quot;ner&quot;, false],<br>            [&quot;Weasel Words&quot;, &quot;weaselwords&quot;, false],<br>            [&quot;Manipulation&quot;, &quot;manipulative_techniques&quot;, false],<br>            [&quot;Clusters&quot;, &quot;clusters&quot;, false]<br>        ]}&lt;/div&gt;</pre><p>Here we have a configuration with for each radiobutton a label, a value, and an indicator whether it is checked or not.</p><p>Then in React we can read this configuration, convert it to a JSON object, and actually render the <em>RadioButtonGroup</em>:</p><pre>// React code<br>const menuContainer = document.getElementById(&#39;transformerchoice&#39;);<br>const menu_def_string = menuContainer.textContent;<br>menu_def = JSON.parse(menu_def_string);<br>const root = ReactDOM.createRoot(menuContainer);<br>root.render(&lt;RadioButtonGroup menu_def={menu_def} /&gt;);</pre><p>This design gives us a clean separation between content being controlled by the Django templating system and interaction functionality being controlled by React.</p><pre># TO AVOID:<br><br>1. Putting React code directly into the template using <br> &lt;script type=&quot;text/babel&quot;&gt;...&lt;/script&gt; tags. It requires transpiling in the <br>browser (slow), is harder to set up, is harder to debug, and gives rise to all<br>kinds of additional difficulties.<br>2. Trying to connect to React from the browser through a javascript function <br>exported from the React application, e.g. <br>&lt;script type=&quot;text/javascript&quot;&gt;displayArticle(48, &#39;ner&#39;)&lt;/script&gt;. <br>You&#39;ll be struggling with exports and webpack configuration on the React side,<br>and with namespaces in the browser.<br></pre><h3>2. Link React components spread over a template</h3><p>React components are located in a <a href="https://adhithiravi.medium.com/react-virtual-dom-explained-in-simple-english-fc2d0b277bc5">“Virtual Document Object Model (DOM)”</a>. It is through the DOM tree that React components are related with each other. As a whole, the Virtual DOM is related through its rendering function with the HTML DOM which the browser presents.</p><p>This works well when React is fully responsible for the creation of a webpage, but is complicated when a template system is leading in creating the HTML DOM.</p><p>Here is an example from the development environment I created and used for the functionality of the webpage displayed higher up in this article. Here I’m using red to indicate that HTML DOM elements come from the template system and green to indicate HTML DOM elements rendered from the Virtual DOM by React.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3AwDgHsi5mjx3yluEfcEOg.png" /><figcaption>Image by author</figcaption></figure><p>From the perspective of rendering, we can generate this page by using two root elements:</p><pre>// Root 1: radiobuttons<br>// For: &lt;div id=&quot;transformerchoice&quot; /&gt;<br>const menuContainer = document.getElementById(&#39;transformerchoice&#39;);<br>const menuRoot = ReactDOM.createRoot(menuContainer);<br>menuRoot.render(&lt;RadioButtonGroup menu_def={menu_def} /&gt;)<br><br>// Root 2: content<br>// For: &lt;div id=&quot;content&quot; /&gt;<br>const contentContainer = document.getElementById(&#39;content&#39;);<br>const contentRoot = ReactDOM.createRoot(contentContainer);<br>contentRoot.render(<br>  &lt;Article article_id={article_id} transformer={transformer} /&gt;<br>);</pre><p>We can now render the React components onto the page, but as the two components are in different Virtual DOMs they cannot communicate with each other.</p><p>To resolve this, instead of using multiple root elements, we use the notion of a <a href="https://react.dev/reference/react-dom/createPortal">Portal</a>. Portals are typically used to create modal content, e.g. a dialog window somewhere in or over a page. Here we use it by wrapping our <em>Article</em> in a portal.</p><pre>    &lt;RadioButtonGroup menu_def={props.menu_def}/&gt;<br>    &lt;ContentPortal&gt;<br>      &lt;Article article_id={props.article_id} transformer={transformer} /&gt;<br>    &lt;/ContentPortal&gt;</pre><p>This portal we now make responsible for rendering the HTML DOM element <em>content</em>.</p><pre>// See: https://react.dev/reference/react-dom/createPortal<br>const ContentPortal = ({children}) =&gt; {<br>  // This is the id of a div in our HTML document<br>  const mount = document.getElementById(&quot;content&quot;);<br>  const el = document.createElement(&quot;div&quot;);<br><br>  useEffect(() =&gt; {<br>     // Be sure to remove any remaining child elements<br>     var child = mount.lastElementChild;<br>     while (child) {<br>            mount.removeChild(child);<br>            child = mount.lastElementChild;<br>     }<br>     mount.appendChild(el);<br>     return () =&gt; mount.removeChild(el);<br>  }, [el, mount]);<br><br>  return createPortal(children, el)<br>};</pre><p>This creates an override for <em>Article</em> when rendering the set of <em>RadioButtonGroup</em> and <em>Article</em>: when whatever is wrapped in <em>ContentPortal </em>is rendered, it will end up under the <em>content</em> element in the DOM, rather than under the created root under which the render call takes place.</p><p>This leaves us with the actual linking of the components, where we want the content to be updated when a radiobutton is checked. We do this by creating a context variable <em>transformer</em> which is accessed both by the <em>RadioButtonGroup</em> and the <em>Article</em>.</p><p>First we define the context:</p><pre>import { createContext } from &#39;react&#39;;<br><br>const TransformerContext = createContext({<br>  transformer: &#39;&#39;,<br>  setTransformer: () =&gt; {},<br>});<br><br>export default TransformerContext;</pre><p>then we wrap our existing elements in it, so they can access it through the Virtual DOM:</p><pre>  &lt;TransformerContext.Provider value={[transformer, setTransformer]}&gt;<br>      &lt;RadioButtonGroup menu_def={props.menu_def}/&gt;<br>      &lt;ContentPortal&gt;<br>        &lt;Article article_id={props.article_id} transformer={transformer} /&gt;<br>      &lt;/ContentPortal&gt;<br>  &lt;/TransformerContext.Provider&gt;</pre><p>Note that <em>Article</em> already has an attribute transformer, so when this value is updated, then the <em>Article</em> object will be re-rendered.</p><h3><em>3. Develop and deploy</em> React components for using with Django templates</h3><p>So far, we assumed to already have some React components, but in practice we will want to develop them ourselves. The following helps creating React applications for inclusion in Django templates:</p><ul><li>Develop using <em>webpack serve</em> for seeing the result of any javascript changes immediately</li><li>Generate multiple bundles for multiple templates</li><li>Split React and custom chunks for cached loading of React in MPA</li><li>Mimic the template environment — create a .html file for each template you want to use React differently in</li><li>Deploy into the <em>static</em> directory of the Django project</li></ul><p><strong>Webpack serve</strong></p><p>When changing React/javascript code we’d like to see the result immediately, that is, without any manual deployment.</p><p>We configure:</p><pre># package.json<br>&quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;webpack --mode production&quot;,<br>    &quot;start&quot;: &quot;webpack serve --mode development&quot;<br>},<br>...<br>&quot;dependencies&quot;: {<br>    ...<br>    &quot;webpack&quot;: &quot;^5.88.1&quot;,<br>    &quot;webpack-cli&quot;: &quot;^5.1.4&quot;<br>}</pre><p>After which we can:</p><p><em>npm run start — </em>to run the interactive environment</p><p>and</p><p><em>npm run build</em> — to create files for production deployment.</p><p><strong>Generate multiple bundles</strong></p><p>For an MPA we typically work with multiple templates in Django. Here I want to deal with templates for articles, claims, and newsletters. We assume that the React code for each of them is in a javascript file in the <em>src</em> directory. As each will have specific React functionality, we create a “bundle” — containing all relevant javascript code — for each of these templates.</p><pre># package.json<br># main: {}  # normally for a single bundle file, but now we don&#39;t use it<br>&quot;exports&quot;: {<br>    &quot;article&quot;: &quot;./src/article.js&quot;,<br>    &quot;claim&quot;: &quot;./src/claim.js&quot;,<br>    &quot;newsletter&quot;: &quot;./src/newsletter.js&quot;<br>  }</pre><p>and</p><pre># webpack.config.js<br>module.exports {<br>  entry: {<br>    article: &quot;./src/article.js&quot;,<br>    newsletter: &quot;./src/newsletter.js&quot;,<br>    claim: &quot;./src/claim.js&quot;<br>    },<br>  output: {<br>    filename: &quot;./static/[name].bundle.js&quot;,<br>    path: path.resolve(__dirname, &quot;build&quot;),<br>    publicPath: &#39;/&#39;<br>  }<br>...<br>}</pre><p>where <em>[name]</em> in <em>output.filename</em> will be replaced with the name of each key in the entry to give the name and path to the output bundle.</p><p><strong>Split React and custom chunks</strong></p><p>In the example above, we created three bundles. Typically, each will contain React in addition to custom code, e.g. for an article. This means that React will be reloaded every time a new type of template is accessed, which is not optimal for users. To allow the browser to cache React, we encapsulate it into a bundle of its own.</p><p>We do this by adding the following to <em>webpack.config.js</em>:</p><pre>module.exports {<br>...<br> optimization: {<br>    splitChunks: {<br>      cacheGroups: {<br>        reactVendor: {<br>          test: /[\\/]node_modules[\\/](react|react-dom|react-router-dom)[\\/]/,<br>          name: &#39;vendor-react&#39;,<br>          chunks: &#39;all&#39;,<br>        },<br>      },<br>    },<br>  }<br>...<br>}</pre><p>This will create a new bundle <em>vendor-react.bundle.js.</em></p><p>We now have to load the combination of React and our custom article code as:</p><pre>&lt;!-- article.html --&gt;<br>&lt;script src=&quot;/static/vendor-react.bundle.js&quot; defer=&quot;defer&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;/static/article.bundle.js&quot; defer=&quot;defer&quot;&gt;&lt;/script&gt;</pre><p>or alternatively for another template:</p><pre>&lt;!-- claim.html --&gt;<br>&lt;script src=&quot;/static/vendor-react.bundle.js&quot; defer=&quot;defer&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;/static/claim.bundle.js&quot; defer=&quot;defer&quot;&gt;&lt;/script&gt;</pre><p>The result will be that when loading the page <em>claim.html</em> after <em>article.html</em>, the script file <em>vendor-react.bundle.js</em> will already be cached by the browser and hence not reloaded.</p><p><strong>Mimicking templates in the development environment</strong></p><p>To create a SPA it is typically enough to have a single file <em>index.html</em> for development. For an MPA it is sensible to create a file in the development environment for each template:</p><pre>public/<br>|- index.html<br>|- article.html<br>|- claim.html<br>|- newsletter.html</pre><p>Opening the browser for the webpack development server will open <em>index.html</em>. Convenient access to the individual pages is possible by having <em>index.html</em> display links to the individual templates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*MUUEzyYVvY0T75OcDWz0Qg.png" /><figcaption>Image by author</figcaption></figure><h3>Deploying to Django</h3><p>From the perspective of Django, the React applications we create are <a href="https://docs.djangoproject.com/en/4.2/howto/static-files/">static files</a>, and they are normally placed under the <em>static</em> directory.</p><p>After developing the React functionality to satisfaction, and testing them with the use of the webpack server, we create “bundles” and copy them to Django.</p><p>We install a webpack <em>FileManagerPlugin</em> and let it copy the generated <em>[name].bundle.js</em> files to the Django <em>static</em> files directory upon the <em>“onEnd” </em>event, which means: after a build.</p><pre>const myDjangoStaticFilesDirectory = &quot;&lt;your directory here&gt;&quot;;<br><br>module.exports = {<br>... <br> output: {<br>    filename: &quot;./static/[name].bundle.js&quot;,<br>    path: path.resolve(__dirname, &quot;build&quot;),<br>    publicPath: &#39;/&#39;<br>  },<br>...<br>plugins: [<br>        // https://www.npmjs.com/package/filemanager-webpack-plugin<br>        new FileManagerPlugin({<br>                events: {<br>                    onEnd: {<br>                        copy: [<br>                            {<br>                                source: path.join(__dirname, <br>                                                  &#39;build/static/*.js&#39;),<br>                                destination: myDjangoStaticFilesDirectory<br>                            }<br>                        ]<br>                    }<br>                }<br>            })<br>        ]<br>}</pre><p>The bundles will now be created and copied to Django by <em>npm run build.</em></p><p>After deployment, we can create Django templates having the same relevant elements as the templates in our React development environment, but now using the Django reference to the static directory to create the path:</p><pre>{% load static %}<br>&lt;script defer=&#39;defer&#39; type=&quot;text/javascript&quot; <br>    src=&quot;{% static &#39;vendor-react.bundle.js&#39; %}&quot;&gt;&lt;/script&gt;<br>&lt;script defer=&#39;defer&#39; type=&quot;text/javascript&quot; <br>    src=&quot;{% static &#39;article.bundle.js&#39; %}&quot;&gt;&lt;/script&gt;<br><br>...<br>&lt;div id=&quot;transformerchoice&quot; /&gt;<br>...<br>&lt;div id=&quot;content&quot; /&gt;<br>...</pre><p>That completes the integration of our React functions with our Django templates.</p><h3>Conclusion</h3><p>We have seen how to create interactive functionality using React for a Multi Page Application in Django. Important elements are how to pass parameters from Django templates to React, how to create React components that are visible in separate places in a template, and how to set up development for a Multi Page Application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=837cb98ce45e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Styling complex values in a dataframe]]></title>
            <link>https://cees-roele.medium.com/styling-complex-values-in-a-dataframe-7ebc5a17b3e7?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ebc5a17b3e7</guid>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 15:58:05 GMT</pubDate>
            <atom:updated>2022-10-26T16:51:37.652Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Displaying one value styled using a second value in a pandas dataframe</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bs2ApOi4bTSKcfy0VHE7sQ.png" /><figcaption>Term Score Matrix: terms coloured with a <strong>qualitative</strong> colormap; no gradient represented (image by author)</figcaption></figure><h3>Introduction</h3><p>Pandas dataframes can be used for a styled presentation of data. In this article I will show how to use one value in a cell to provide the style for a second value. This is relevant for applications like the <em>Term Score Matrix </em>displayed above this article, where the terms are displayed, while the scores serve to define the styling.</p><h3>Basic styling with pandas dataframes</h3><p>Based on the minimum and maximum values in a cell, pandas can create a <a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.background_gradient.html">background gradient</a> for cells.</p><pre># Create a 5x5 matrix of random numbers between [-0.3,0.7)<br>m = np.random.rand(5,5) - 0.3<br>df = pd.DataFrame(m)<br>df.style.background_gradient()</pre><p>The result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*0ktbqKzgQYUyd5Jd3ninng.png" /><figcaption>Background gradient on a 5x5 matrix with random numbers (image by author)</figcaption></figure><h3>Applying CSS to all cells</h3><p>We can use DataFrame.style.<a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.applymap.html">applymap</a> to apply a CSS-styling function to all elements, which updates the HTML representation with the result. This method takes a function as its argument, which processes the value of the cell and returns <em>CSS styles as strings, in the format ‘attribute: value; attribute2: value2; …’ or, if nothing is to be applied to that element, an empty string or </em><em>None</em>. If any keyword arguments are given to applymap, they are passed to the function argument.</p><p>Let’s highlight the negative values in the above matrix.</p><pre>def style_negative(v, props=&#39;&#39;):<br>    return props if v &lt; 0 else None</pre><pre>df.style.applymap(style_negative, props=&#39;color:red;&#39;)</pre><p>The result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*mPs0bF66awVmMpCULUiVYA.png" /><figcaption>Styling: negative values coloured red with applymap (image by author)</figcaption></figure><h3>Complex values</h3><p>Pandas documentation on <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html">applying styles to tables</a> is limited to discussing how the actual values in a dataframe are to be styled.</p><p>But what if we have complex values in our dataframe, e.g. a word/value pair, where the word is to be displayed and the value is used to define the styling?</p><p>Let’s create a dataframe of (word, length) pairs out of the words of a poem:</p><pre>import re<br># &quot;A Visit from St. Nicholas&quot; by Clement Clarke Moore<br># <a href="https://www.poetryfoundation.org/poems/43171/a-visit-from-st-nicholas">https://www.poetryfoundation.org/poems/43171/a-visit-from-st-nicholas</a><br>poem = &quot;&quot;&quot;<br>&#39;Twas the night before Christmas, when all through the house<br>Not a creature was stirring, not even a mouse;<br>The stockings were hung by the chimney with care,<br>In hopes that St. Nicholas soon would be there;<br>&quot;&quot;&quot;</pre><pre>words = re.split(r&#39;\W+&#39;, poem)<br>pairs = [(x, len(x)) for x in words]<br># Create a 5x5 matrix of tuples: (word, length)<br>matrix = []<br>for i in range(0,5):<br>    matrix.append(pairs[5*i:5*(i+1)])<br>df2 = pd.DataFrame(matrix)</pre><p>The dataframe looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*0QvVAWXScrYPH_jb6iEKng.png" /><figcaption>A dataframe of (word, length) pairs (image by author)</figcaption></figure><h3>Displaying words only</h3><p>To display the value of a cell from a dataframe we use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.format.html">format</a> method. Out of the different possibilities this method offers, we are now interested only in passing it a <em>function</em> to convert the value of the cell to whatever is to be displayed. Right now, that is the <em>word</em>, the first element of the tuple in the cells.</p><pre>df2.style.format(lambda x: x[0])</pre><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*X6OeVKyqyvWMBwFkBor4Rw.png" /><figcaption>Display only the first element of the tuples in the dataframe (image by author)</figcaption></figure><h3>Styling values</h3><p>As earlier with colouring negative values, we use applymap to style the value of the cells. Here we use the second element of the pair to apply a font weight and font colour if the length of the word is shorter than 4. We must now apply both format and applymap to the DataFrame.style element, a <a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.html">Styler</a> object.</p><pre>def font_short(v, weight, color):<br>    &quot;&quot;&quot;<br>    Mark short words<br>    <br>    Parameters<br>    ----------<br>    v: tuple of (word, length)<br>    weight: CSS term accepted as a font-weight value<br>    color: CSS term accepted as a color<br>    &quot;&quot;&quot;<br>    return f&quot;font-weight: {weight}; color: {color}&quot; if v[1] &lt; 4 else None</pre><pre># We must apply both `format` and `applymap` to the DataFrame.style<br>styler = df2.style.format(lambda x: x[0])<br>styler.applymap(font_short, weight=&#39;bold&#39;, color=&#39;orange&#39;)</pre><p>Now we see a matrix of words, as above, but with the words shorter than four characters being marked bold and orange:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*5oBmbY5JLl9AHDmIICbKsQ.png" /><figcaption>Mark words shorter than four characters (image by author)</figcaption></figure><h3>Using a gradient to represent word lengths</h3><p>Next, let’s represent the length of words as a gradient. Long words become dark, short words light. To do this, we must convert the length of the word to a fraction between 0 and 1, relative to the length of the shortest word and the length of the longest word.</p><p>We use matplotlib to convert that fraction to a hexadecimal term which we then use to define the background colour in CSS. We can use any matplotlib <a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html">colormap</a>, but to represent a gradient, we must use a <em>sequential colormap</em>.</p><blockquote>For contrast: The image at the top of this article is based on declining values from left to right in all rows, but this decline is not represented because a <em>qualitative</em> colormap is used instead of a <em>sequential</em> colormap.</blockquote><p>Below I use the colormap YlGn, which is short for “yellow-to-green”, where yellow stands for a low value and green for a high value.</p><pre>import matplotlib as mpl<br>def make_gradient(v, min_length, max_length, cmap=&#39;YlGn&#39;):<br>    &quot;&quot;&quot;<br>    Parameters<br>    ----------<br>    <br>    v: tuple of (word, length)<br>    min_length: int <br>        minimum length of all words in the matrix<br>    max_length: int<br>        maximum length of all words in the matrix<br>    cmap: matplotlib color map, default value here is &#39;YlGn&#39;<br>        <br>    Returns<br>    -------<br>    <br>    string:<br>        CSS setting a colour<br>              <br>    For Matplotlib colormaps:<br>    See: <a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html">https://matplotlib.org/stable/tutorials/colors/colormaps.html</a></pre><pre>&quot;&quot;&quot;<br>    # normalize the word length as a fraction of the range <br>    # between min_length and max_length<br>    rel_v = (v[1] - min_length) / (max_length - min_length)<br>    # define the colormap<br>    cmap = mpl.cm.get_cmap(cmap)<br>    # Get a colour out of the given colormap based on a value [0,1]<br>    rgba = cmap(rel_v)  <br>    # convert the colour to a hexadecimal string representation<br>    return f&#39;background-color: {mpl.colors.rgb2hex(rgba)};&#39;</pre><pre># We must apply both `format` and `applymap` to the DataFrame.style<br>styler = df2.style.format(lambda x: x[0])<br>min_length = min([x[1] for x in pairs])<br>max_length = max([x[1] for x in pairs])<br>styler.applymap(lambda x: make_gradient(x, min_length, max_length))</pre><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*7gH5BHyszUsemUTWa4gIyQ.png" /><figcaption>Gradient based on word lengths (image by author)</figcaption></figure><h3>Using the background_gradient again</h3><p>At the beginning of this article we saw how the background_gradient method can be used on values in a dataframe. It doesn’t work on tuples, but it does have a parameter gmap which can take a dataframe with the same index and columns as input for styling. As we will use the entire dataframe we need to set axis=None as an additional argument.</p><p>As the values on which the styling is based are now presented in a separated dataframe, we can refrain from having tuples and instead use one dataframe with words and a second one with their lengths.</p><pre># Create one dataframe with only words<br>df_words = df2.applymap(lambda x: x[0])<br># .. and a second one with only lengths<br>df_lengths = df2.applymap(lambda x: x[1])<br># Now use the lengths to apply the background gradient to the words<br>df_words.style.background_gradient(gmap=df_lengths, axis=None)</pre><p>That was easy to do! The outcome is quite similar to the previous image, so let’s skip showing it for now.</p><h3>Adding tooltips</h3><p>Gradient colours give us a good idea of relative lengths, but we still might want to be able to see the exact lengths of words if they interest us.</p><p>Let’s add a tooltip to our dataframe that displays the length. For this we use the Styler’s <a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_tooltips.html">set_tooltips</a> method. It takes a dataframe and CSS properties as its arguments. The dataframe doesn’t need to be the one which we display, it just needs to correspond to it, just as our df_lengths dataframe corresponds to df_words.</p><p>Let’s create a dataframe of tooltips based on df_lengths where the cells have the content: “length: n”, where n stands for the word length.</p><pre>df_lengths.applymap(lambda x: f&#39;length: {x}&#39;)</pre><p>we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*G5Sfl19_skNlYabL6tvUkg.png" /><figcaption>Matrix corresponding to df_words with tooltips only (image by author)</figcaption></figure><p>Now we do this again in a call to set_tooltips(dataframe, props). Never mind the exact CSS properties I use here. Also, I use a different colormap for the background_gradient.</p><pre>styler = df_words.style.background_gradient(gmap=df_lengths,     axis=None, cmap=&#39;YlOrRd&#39;)<br>styler.set_tooltips(<br>    df_lengths.applymap(lambda x: f&#39;length: {x}&#39;), <br>    props=[<br>        (&#39;visibility&#39;, &#39;hidden&#39;),<br>        (&#39;position&#39;, &#39;absolute&#39;),<br>        (&#39;background-color&#39;, &#39;white&#39;),<br>        (&#39;color&#39;, &#39;black&#39;),<br>        (&#39;z-index&#39;, 1),<br>        (&#39;padding&#39;, &#39;3px 3px&#39;),<br>        (&#39;margin&#39;, &#39;2px&#39;)<br>    ])</pre><p>The result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*971o7_cvHbPCffUlcqE14A.png" /><figcaption>Gradients and tooltips applied to a matrix with words (image by author)</figcaption></figure><p>You see the tooltip at the word “when” indicating that its length is 4. Also, you see that background_gradient provides an improvement over the earlier “manual” creation of gradient colours: here the font color is set to white when the colour gets dark, which improves readability.</p><h3>Conclusion</h3><p>We saw two ways of using values that are not visible in a dataframe to style the visible cells:</p><ol><li>Create a dataframe with tuples and then use format and applymap to display and style the cells.</li><li>Create two corresponding dataframes where the second is used to apply style to the first.</li></ol><h3>Example</h3><p>For an application of using this technique, see my following article:</p><p><a href="https://cees-roele.medium.com/a-term-score-matrix-for-bertopic-821e78e198ee">A Term Score Matrix for BERTopic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ebc5a17b3e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Term Score Matrix for BERTopic]]></title>
            <link>https://cees-roele.medium.com/a-term-score-matrix-for-bertopic-821e78e198ee?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/821e78e198ee</guid>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[bertopic]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[disinformation]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Tue, 25 Oct 2022 19:27:39 GMT</pubDate>
            <atom:updated>2022-10-26T16:00:54.005Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An improved visualisation of term scores for topics with BERTopic</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eLdtlBpulTliiv3ALyh4Q.png" /><figcaption>Term Score Matrix (image by author)</figcaption></figure><h3>In short</h3><p>This article demonstrates a <em>Term Score Matrix</em>, a visualisation of pairs of terms and scores characterising topics in <a href="https://maartengr.github.io/BERTopic/index.html">BERTopic</a>. Focus is on functionality. You can find a link to the notebook containing the implementation of the stylised dataframe for the Term Score Matrix at the bottom of this article.</p><p>The used dataset is based on the over 14,000 reports on <em>“pro-Kremlin disinformation cases”</em> at the website <a href="https://euvsdisinfo.eu/">EU vs Disinformation</a>. This reflects political contention between the EU and Russia over the past seven years. You can find more information on the dataset and on topic modelling with BERTopic of this dataset in the following article:</p><p><a href="https://cees-roele.medium.com/disinformation-topics-over-time-5c9ec21300f9">Disinformation Topics over Time</a></p><h3>Topic modelling: terms and scores</h3><p>Based on a notion of distance calculation, the process of clustering defines a number of clusters and assigns each sample of the dataset to a cluster.</p><p>Assuming we have assigned our dataset to a variable docs, we can model topics with BERTopic by:</p><pre>from bertopic import BERTopic<br>docs = [ ... list of documents/strings ...]<br>topic_model = BERTopic(min_topic_size=100, top_n_words=20)<br>topic_model.fit_transform(docs)</pre><p>The result is a set of thirty clusters with a size of at least 100 samples. Here are the resulting topics with the largest frequencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*9vMocOivFgrd5K2IoDMGVg.png" /><figcaption>Top 8 of 30 topics after topic modelling with BERTopic (image by author)</figcaption></figure><p>Topic modelling applies clustering to linguistic samples and provides a characterisation of the resulting clusters as a ranked list of <em>terms</em> with their c-TF-IDF <em>scores</em>. We see an example in the table below. Note that the <em>name</em> of the topic — above the table — is generated on the basis of the topic id — here 2— and the highest ranking terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*TNVHSzSt0K07T9SluDDzDA.png" /><figcaption>Term Score table for topic 2 (image by author)</figcaption></figure><h3>Term Score Decline</h3><p>Having names for topics based on relevant terms helps identifying and understanding the different topics. But what are we otherwise to do with the list? Just considering the sequence of terms gives us limited understanding of the <em>relevance</em> of these terms to the topic.</p><p>The <em>Term score decline diagram</em> gives us insight in how the scores of terms decrease to a level where their influence is hardly distinguishable from that of other terms.</p><p>For the illustration below we have configured BERTopic to create term-scores for twenty terms by initialising it with top_n_words=20. For most topics, we see a steep decline of the c-TF-IDF score from the term ranked first to the term ranked third. After the third rank the scores are gradually flattening with increasing rank.</p><p>To get this diagram, we run: topic_model.visualize_term_rank() The annotations in red are manually added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtmhmxel7m1lhrWOkEtH0A.png" /><figcaption>Term Score Decline (image by author)</figcaption></figure><p>Only by using tooltips in BERTopics plotly-based diagram can we see what line in the diagram corresponds to what topic (see the little arrow on the left of the tooltip in the image). At the eleventh ranked term we see that topics <em>29_kerch_strait</em> and <em>12_MH17_JIT</em> stand out by having higher c-TF-IDF values than the others. Their values at this term are even higher than the scores for the first items of several other topics.</p><p>The Term Score Decline diagram helps us decide whether we can cut off the number of terms we want to distinguish. E.g. we might consider that only the top 11 terms are important enough for us to consider. But how to deal with the outliers, like the two topics having relatively high c-TF-IDF values even at the eleventh rank?</p><h3>Bar chart</h3><p>Let’s take a closer look at these topics and their terms. We use BERTopic’s visualize_barchart() to take a closer look at these topics and their terms. In the following diagram we look at the 15 highest ranked terms and include two other topics as reference.</p><p>Ignoring arguments for setting the title, height, and custom labels, we run: topic_model.visualize_barchart(topics=[0,29,12,30], n_words=12)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kT3l5UKgjcsYaU-dAaCGkw.png" /><figcaption>Barchart for selected topics (image by author)</figcaption></figure><p>We see — with added annotation and a tooltip — the ranked terms with their relative scores for four topics, including the two we saw standing out in the <em>Term decline score diagram</em>. Looking at the terms we can understand <em>why</em> the scores for these topics decline relatively little, that is, they keep standing out compared to other topics: <em>both involve specific events</em>.</p><p><em>Topic 29</em> is about the waterway <em>Kerch Strait</em> and we see terms like <em>sea</em>, <em>waters</em>, <em>vessels</em>, <em>boats</em>, <em>crews</em>, and <em>ships</em>. Topic 12 is about the downing of the airplane MH17 and we see terms like <em>BUK</em> (anti-aircraft missile), <em>missile</em>, <em>JIT</em> (Joint Investigation Team), <em>flight</em>, <em>crash</em>, <em>downing</em>.</p><h3>Term Score Matrix</h3><p>Above we saw that the bar chart can help us answer the question: <em>“What are the highest ranking terms of any topic and how do their scores decline?”</em></p><p>But it doesn’t show us the other direction: terms for any topic by rank. First, because the scales of the different bar charts are different, as indicated by the annotation in the image. Second, because the length of bars in sequence — rather than in parallel — is hard to compare visually. Comparison in the multiple bar chart layout works only in <em>one dimension</em>: between the scores of terms of one topic in one bar chart.</p><p>Additionally, the bar chart uses space to represent a scalar value. If we would represent all thirty topics in a layout of multiple bar charts, it would take us eight rows of up to four bar charts.</p><p>We can address these drawbacks of the bar chart representation by having <em>colour</em> represent the score, similar to a <em>heatmap</em>.</p><p>We can use a pandas DataFrame to do this for the same topics as we displayed in the bar chart above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_EfA7SiRY7k7xf14_p0Sw.png" /><figcaption>Term Score Matrix for topics 0, 12, 29, and 30 (image by author)</figcaption></figure><p>We see that now our ability to compare is <em>two-dimensional</em>: we can <em>horizontally</em> compare relative value of ranked terms for one topic — as in the bar chart — and <em>vertically</em> the relative value for any topic of a specific rank. As with BERTopic’s plotly-based diagrams, we display a tooltip with the c-TF-IDF value — in the image with the example for <em>boat</em>.</p><p>Note that the bar chart allows for infinite extension of the number of terms as it stacks them vertically, and here we are restricted to the width of the screen. We are displaying only eight ranks instead of fifteen.</p><p>Let’s look at the Term Score Matrix for all topics now. Colours may vary as long as they indicate the scale. In the next image we use a colour scheme of yellow, orange, and red. As the whole image is zoomed out, we can now include fifteen ranks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A82f-axueWwBcL-cPZ3oDw.png" /><figcaption>Term Score Matrix for EUvsDisinfo (image by author)</figcaption></figure><p>Much more information than we get from the multiple bar chart layout fits into this single matrix and it is much easier to compare values in all directions.</p><h3>Conclusion</h3><p>The Term Score Matrix is a space-efficient diagram representing c-TF-IDF scores for terms along the two dimensions of topics and ranks. It enables us to quickly identify term decline for topics and what terms are prevalent in topics.</p><h3>Programming code</h3><p>A Jupyter notebook with the python code used in this article is available at github.</p><p><a href="https://github.com/ceesroele/disinformation/blob/main/TermScoreMatrix.ipynb">disinformation/TermScoreMatrix.ipynb at main · ceesroele/disinformation</a></p><p>You can find a simple explanation of the styling technique behind the Term Score Matrix in another article of mine:</p><p><a href="https://cees-roele.medium.com/styling-complex-values-in-a-dataframe-7ebc5a17b3e7">Styling complex values in a dataframe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821e78e198ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disinformation Topics over Time]]></title>
            <link>https://cees-roele.medium.com/disinformation-topics-over-time-5c9ec21300f9?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9ec21300f9</guid>
            <category><![CDATA[european-union]]></category>
            <category><![CDATA[geopolitics]]></category>
            <category><![CDATA[bertopic]]></category>
            <category><![CDATA[disinformation]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Thu, 20 Oct 2022 11:14:22 GMT</pubDate>
            <atom:updated>2022-10-20T11:14:22.421Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Visualising the development of topics over time in the EUvsDisinfo database</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*x60cgWA3vzAGC6bgjDtPcQ.png" /><figcaption>Visualising topics over time in the EUvsDisinfo database (image by author)</figcaption></figure><h3>Introduction</h3><p>The <a href="https://euvsdisinfo.eu/">EUvsDisinfo</a> database is a treasure trove of the European Union’s strategic communication about Russia. It contains over 14,000 reports expressing the EU’s political contention of “pro-Kremlin” claims.</p><p>In this article we will model the topics in that database, scrutinise their nature, and track them over time.</p><h3>Data</h3><p>Since 2015 the <a href="https://www.eeas.europa.eu/eeas/questions-and-answers-about-east-stratcom-task-force_en">East StratCom Task Force</a> of the <a href="https://www.eeas.europa.eu/_en">European External Action Service</a> has created over 14,000 reports on <em>“pro-Kremlin disinformation cases”</em> at its website <a href="https://euvsdisinfo.eu/">EU vs Disinformation</a>.</p><blockquote>Cases in the EUvsDisinfo database focus on messages in the international information space that are identified as providing a partial, distorted, or false depiction of reality and spread key pro-Kremlin messages. This does not necessarily imply, however, that a given outlet is linked to the Kremlin or editorially pro-Kremlin, or that it has intentionally sought to disinform.</blockquote><p>Presently, we are interested only in the <em>topics</em> we can distinguish in the data and will <em>not</em> touch on the notion of <em>disinformation</em>.</p><p>Below an image of what a report of a case in the database looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtC16YxU02469tsTzfUjDw.png" /><figcaption>Annotated case report (image by author)</figcaption></figure><p>For the purpose of identifying topics we are interested in:</p><ul><li><em>title</em></li><li><em>summary</em>: a representation of the claim that is disputed</li><li><em>disproof</em>: disputation of the claim</li><li><em>publication date</em>: date on which the <strong>report</strong> was published (not on which the claim was made in the “publication/media” source)</li></ul><p>By extracting the data from the EUvsDisinfo webpages containing the reports we have come to a dataset with 14,382 records with publication dates between 6 Jan 2015 and 13 Sept 2022.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCxILprWpxR1OsiQ2GDoxQ.png" /><figcaption>Distribution of publication dates in EUvsDisinfo database (image by author)</figcaption></figure><p>In tabular form, the data looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkvFMfNRWLd5OU4NwDlC4Q.png" /><figcaption>Dataset in tabular format (image by author)</figcaption></figure><h3>Topics</h3><p>We are looking for <em>patterns</em> in what the cases are about. For this, we don’t need the <em>urls</em> in our data and we concatenate the words of the <em>title</em>, <em>summary</em>, and <em>disproof</em> into a single text or <em>document</em>. What the cases <em>are about</em> we call a <em>topic</em>. We assume that each document has a single topic.</p><p>Our goal is to identify and characterise a set of topics which recur in the documents.</p><p>To automatically identify and visualise topics, we will use <a href="https://maartengr.github.io/BERTopic/index.html">BERTopic</a> which …</p><blockquote>… is a topic modelling technique that leverages transformers and c-TF-IDF to create dense clusters allowing for easily interpretable topics whilst keeping important words in the topic descriptions.</blockquote><p>The present article is focused on analysis, not on techniques. Let me phrase what happens in a relatively untechnical way.</p><p>Using a general model of the English language, the words in the documents of our dataset are encoded as numbers in a space with hundreds of dimensions. To be manageable this multi-dimensional space is reduced to a few dimensions. Now an algorithm divides the documents into <em>clusters</em> based on the similarity of their encodings. For each cluster, we determine a list pairing the most representative terms with a score for how representative they are. The topmost terms are used to automatically create a name for the cluster. With this added information the cluster — which is just a set of documents — gains a characterisation and we call it a <em>topic</em>.</p><h3>Finding topics</h3><p>When we use default parameters for BERTopic we find <strong>225 topics in our dataset</strong>, with each having a minimum of 10 matching documents.</p><p>This might be a desirable result e.g. if want want to create a recommendation system to enrich the information on the documents: <em>“If you like this report, you might also like the following related reports”</em>. But right now we are interested in a general overview of topics in our data, not in relations between documents, and we’d like to cut down on the list of resulting topics.</p><p>We therefor set the minimum size of records per topic to 100. Additionally, we remove stopwords (e.g. ‘and’, ‘or’, ‘the’) from the topics as they don’t contribute to their meaning.</p><p>The result is the following list of 27 topics with their respective number of publications. <em>Topic</em> stands for the id of a topic, <em>Count</em> for the number of publications for that topic, and <em>Name</em> is generated on the basis of the Topic id and the most prevalent terms of the topic.)</p><blockquote>Note that <strong>-1</strong> signifies the group of <strong>outliers</strong>. These are documents which the algorithm did not include in a topic.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*V7O3TTsnBsb5yixEGuaGTA.png" /><figcaption>Overview of topics (image by author)</figcaption></figure><p>For a better insight in the number of publications per topic, we can display the <em>Count, </em>the number of publications per topic, in a bar chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGJmFmAiLIzMMv-q9Xbunw.png" /><figcaption>Number of publications per topic (image by author)</figcaption></figure><h3>About the numbers</h3><p>Let’s look at some percentages based on the data presented above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*LKJi3eBxNdcgqkOOBhLMpA.png" /><figcaption>Vital statistics (image by author)</figcaption></figure><p>In words:</p><ul><li>22% of all documents is considered an <em>outlier</em>, that is, it is not assigned to any topic</li><li>almost a quarter of all documents (24.3%) is allocated to the first topic (id=0), which is over 30% of all documents that are <em>not</em> outliers</li><li>Little over 50% of all documents is allocated to any <em>other</em> topic than the first</li></ul><p>We see that the topic named <em>ukraine_ukrainian_donbas_war</em> is by far the most frequent in our dataset. Based on a notion of <em>similarity</em> — more on that later in this article — we can find the document in the database that is most representative for the topic, and I conclude hence, for the entire EUvsDisinfo database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jx8MlUKnwjjRLuXr2zGSdg.png" /><figcaption>Most representative document of EUvsDisinfo database: <a href="https://euvsdisinfo.eu/report/ukraine-lost-its-independence-and-ability-to-determine-its-own-foreign-policy">https://euvsdisinfo.eu/report/ukraine-lost-its-independence-and-ability-to-determine-its-own-foreign-policy</a></figcaption></figure><p>It is from the 14th of September 2021.</p><h3>Characterising topics</h3><p>Remember that our dataset consists of 14,382 documents. Basic clustering would do nothing more than creating a list of cluster ids and attributing such a cluster id to each document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*Z_mpsd_H2jeWA_f3BnPk9w.png" /><figcaption>Attributing a cluster id to each document (image by author)</figcaption></figure><p><em>Topic modelling</em> adds to clustering a characterisation of each cluster by a list of pairs of representative terms with their scores. This score is based not just on a term occurring many times in the documents of the cluster, but also on it <em>not</em> being so prevalent in the documents of other clusters. They indicate <em>what makes this cluster special</em>.</p><p>Below you see the table of <em>terms</em> and <em>scores</em> for one topic. Note how the generated name for the topic is derived from the highest ranking terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*Puf12citbBUWi2En97PCtQ.png" /><figcaption>Top terms and their scores for one topic (image by author)</figcaption></figure><p>The overview of topics with their generated names already gave us insight in what the different topics are about. Now we extend this to more terms and using the score to indicate how relatively representative any term is. Bright red indicates a high score, a colour towards white indicates a low score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmBh7m3srxVbl3HIYpCeOA.png" /><figcaption>Topic Term matrix (image by author)</figcaption></figure><p>Two examples:</p><ol><li>Topic <em>14_vaccine_sputnik_vaccines_ema</em> displays a bright red <em>vaccine</em> and <em>24_soros_george_foundation_society</em> displays <em>soros</em> and <em>george</em> in bright red. It means that these topics can pretty much be identified by only these terms.</li><li>In <em>16_interference_election_2016_elections</em> we see that none of the terms is marked very red. It means that to identify whether this is the topic for a document, the <em>combination</em> of a number of terms is important. If we find in a document <em>interference</em>, and <em>election</em>, and <em>meddling</em>, and <em>trump</em>, and <em>presidential</em>, then there is a good chance that this is the topic. Note that this topic is “competing” with the very similar topic <em>23_election_trump_biden_fraud</em>.</li></ol><h3>Relating topics</h3><p>Looking at the table showing term scores for all topics, we see the numerous terms occur in different topics. This leads to a thought:</p><p><em>If topics are </em><strong><em>similar</em></strong><em>, we might conflate them and end up with fewer topics.</em></p><p>Terms and scores are used to define topics and allocate documents to them. Additionally, a notion of <em>distance</em> can be defined as a measure of how similar two topics are.</p><p>We can project the topics onto a two-dimensional plane which makes such a distance visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*k6gbul2vuc2OoArgeEQ4_Q.png" /><figcaption>Intertopic Distance Map (image by author)</figcaption></figure><p>In the diagram we see <strong>seven groups of circles</strong>. Each circle represents a topic — and the size of the circle the number of documents allocated to it.</p><p>This suggests we might reduce we number of topics to seven and conflate the topics in each group. Trying this, the result was seven topics which were mostly the same as the seven topics with the highest frequency above, but now about half of all documents ended up as <em>outlier.</em> This approach therefore didn’t lead to a simplification, but to a truncation.</p><h3>Hierarchically relating topics</h3><p>Another approach is to calculate the distance between any two topics, pick the two topics with the shortest distance, and merge them. We then calculate the distance for all other topics to the topic newly created by merging and repeating the process of picking the two topics with the shortest distance, and merge those. We continue doing this until all topics have merged into one single topic.</p><p>We can make this visible using a <em>dendrogram:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BGlY6p4Tw8n42pCVDFfH8g.png" /><figcaption>Dendrogram: hierarchy of topics (image by author)</figcaption></figure><p>Note that the column with topic names is now reordered in order to be able to draw the dendrogram. The more the dot of connecting topics is located to the left, the smaller the distance between them.</p><p>In the marked green rectangle we see that <em>21_italy_coronavirus_eu</em>, 7<em>_coronivirus_virus_covid19</em>, and <em>14_vaccine_sputnik_vaccines</em> are closely together. The red arrows indicate the nodes where the topics are in two steps merged together in a new topic.</p><p>As terms and scores can also be calculated for the topics created by merging, we can automatically generate names for them. In another view of the same information the nodes that are connecting topics are <em>named</em> in the same way that the most salient words of any topic are used to create the name of a topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38UE6HDQh9PJ1XWjN8VOYg.png" /></figure><p>Note that the second dendrogram is ordered differently: the leaves are on the right side and the root is in the top-left corner. We see here that the three earlier mentioned topics are combined into one which we can name <em>coronavirus_vaccine_sputnik_covid19_pandemic</em>.</p><blockquote>To distinguish merged topics from the — very similar- topics they are merged out of, in this diagram <strong>five</strong> terms are used to generate the name of topics.</blockquote><blockquote>Merged topicsin the hierarchy are “virtual” and have no topic id<strong>.</strong></blockquote><h3>Topics over time</h3><p>Above we looked at topics, their characterisation in terms of top terms, and the similarity of topics. We will now look at the number of documents per interval in the EUvsDisinfo database for each topic. Arbitrarily, we select time intervals of two months so we get forty-two intervals for the seven years EUvsDisinfo has been active. We place this in a line chart, with one line per topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*j5hXDCYNVYqa5QnTm3HMaA.png" /><figcaption>Top 10 topics over time in the EUvsDinfo database (image by author)</figcaption></figure><p>We see that <em>0_ukraine_ukrainian_donbas_war</em> has been the topic consistently having the most publications, except for a peak in early 2020 when <em>7_coronavirus_virus_covid19_china</em> had a peak.</p><p>In BERTopic the above diagram is interactive and it is possible to get a better overview of the development over time in each topic.</p><p>Here we chose to display only the ten topics with the most documents published. If all topics were included, there would have been many more lines near the bottom of the diagram, which would make them difficult to distinguish and compare.</p><p>Let’s look at two topics that according to the hierarchical clustering diagram are closely related:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zWroanXJ70rQsW6n6GVwsQ.png" /><figcaption>Navalny/Skripal cases over time (image by author)</figcaption></figure><p>Given that the bases for these cases are in very specific events, we see that there are clear peaks for each of them. As a word of caution: we also see that the interpolation in the diagram — which might be appropriate in other cases — is misleading: the Skripal-line makes a long ascent from early 2017 to early 2018, but the event occurred only in 2018.</p><p>In the <em>Hierarchy Chart with Named Nodes</em> we can track interesting nodes at which several topics are merged. Taking one of such nodes, e.g. <em>coronavirus_vaccine_sputnik_covid19_vaccines,</em> we can look at how the different topics coming together in that node are developing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*19aCDAxhFQ3I4LMW9odciA.png" /><figcaption>coronavirus_vaccine_sputnik_covid19_vaccines node over time (image by author)</figcaption></figure><p>Here we see clear peaks for the period in early 2020 when COVID19 required the most understanding and decision-making and another peak for vaccines around 2021.</p><blockquote>By using our knowledge of the topic hierarchy we can find selections of topics for interesting comparisons of their development over time.</blockquote><p>A third way of selecting topics — after taking the top 10 and taking nodes from the hierarchy — is to find topics for some keywords that interest us.</p><p>Just as the relative similarity of topics is based on scores for terms, individual terms or search strings can be scored, after which the topics can be selected which most closely match them.</p><p>Here we search for “european union and sanctions” and find three topics which relatively closely match it:</p><pre>Similar topics for the word &#39;european union and sanctions&#39; (similarity threshold=0.40):<br>- 6_sanctions_russia_eu (0.609)<br>- 12_eu_european_member (0.489)<br>- 5_nato_alliance_russia (0.438)</pre><p>Let’s visualise them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-N5HijoAHGMMygZ07A9VLQ.png" /><figcaption>Topics similar to “european union and sanctions” over time (image by author)</figcaption></figure><p>Note that the above is not a filter for the search string: we see just the frequencies for the topics. But what is interesting is that these three topics have a relatively similar pattern of frequencies over time.</p><h3>Conclusions</h3><p>We defined 27 topics to which we assigned three-quarters of our dataset of 14,000 documents from the EUvsDisinfo database of “disinformation cases”, leaving the rest of the documents as <em>outliers</em>.</p><p>The topic <em>ukraine_ukrainian_donbas_war</em> dominates during almost the entire existence of EUvsDisinfo in terms of frequency, making up over 30% of the documents we assigned to topics. It shows that the focus of East StratCom Task Force, the producer of EUvsDisinfo, has been very much on Ukraine.</p><p>Based on a notion of <em>similarity</em>, we found that the document most representative for the dominating topic, and hence for the entire EUvsDisinfo database, is <a href="https://euvsdisinfo.eu/report/ukraine-lost-its-independence-and-ability-to-determine-its-own-foreign-policy"><em>“Ukraine lost its independence and ability to determine its own foreign policy”</em></a> (careful: the point of the title is for the EU to disprove it).</p><p>Using term scores we <em>characterised the different topics</em> by the terms that are most prevalent for them and most outstanding compared to other topics.</p><p>We displayed what topics are similar using a <em>hierarchical tree</em>.</p><p>Based on relevance by most publications, nodes in the hierarchical tree, and search for terms, we selected subsets of topics to display the number of their documents over time in order to find interesting patterns. What we found is that certain topics are really time/event bound, like Navalny/Skripal or Covid19, while <em>ukraine_ukrainian_donbas_war</em> kept dominating the output for most of the seven year period.</p><h3>Post scriptum</h3><p>You can find the code I used for the above research here:</p><p><a href="https://github.com/ceesroele/disinformation/blob/main/DisinformationTopicsOverTime.ipynb">disinformation/DisinformationTopicsOverTime.ipynb at main · ceesroele/disinformation</a></p><p>Great thanks to <a href="https://medium.com/@maartengrootendorst">Maarten Grootendorst</a> for the creation &amp; publication of the splendid <a href="https://maartengr.github.io/BERTopic/index.html">BERTopic</a> topic modelling tool!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9ec21300f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Displaying SpaCy Spans]]></title>
            <link>https://cees-roele.medium.com/displaying-spacy-spans-fc3a43810524?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3a43810524</guid>
            <category><![CDATA[spans]]></category>
            <category><![CDATA[displacy]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[spacy]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 10:03:30 GMT</pubDate>
            <atom:updated>2022-09-12T10:03:30.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rJJCHe9H-3xP9x8QaCO8w.png" /><figcaption>DisplaCy visualising spans. Data originally from [1]</figcaption></figure><h3>Introduction</h3><p>The displaCy visualiser shows <em>dependencies</em> and <em>entities</em> in a spaCy document. Since spaCy 3.3 it also displays <em>spans.</em></p><p>This article first gives a brief introduction on spans and then goes into two issues I had to resolve to make displaCy work for my data:</p><ol><li>Giving spans attractive colours.</li><li>Transforming the labels to abbreviations to display them with correct alignment.</li></ol><h3>Displaying entities with displaCy</h3><p>As one might do on paper with a coloured marker, <a href="https://spacy.io/usage/visualizers">displaCy</a> uses colouring the background to mark <em>entities</em> in a text. An entity visualisation of <em>“Welcome to the Bank of China”</em> looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z66IvD4KJdzZEXocM0r9rg.png" /><figcaption>displaCy visualisation of the ORG type entity ‘the Bank of China’</figcaption></figure><p>To create this visualisation we let spaCy parse the sentence and visualise it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d1be2a5f6d1d49d231c11e7dc02496a/href">https://medium.com/media/3d1be2a5f6d1d49d231c11e7dc02496a/href</a></iframe><p>The last line opens a webserver which displays the picture shown above so it can be viewed with a browser. Alternatively, within a Jupyter notebook the method render can be called instead of serve which will display the visualisation within the notebook.</p><h3>Spans</h3><p>Unlike entities, spans can <em>overlap</em>. E.g. we can recognise <em>“Bank of China”</em> as an ORG (organisation), but also, in the same sentence, <em>“China”</em> as a GPE (Geopolitical Entity). In this example we will define the spans explicitly.</p><p>To display such overlapping spans, we will use the serve method of thedisplaCy generator of visualisations withstyle=span . This will create a web service generating a single web page containing the result. Note that the spans are defined with the spans_key labelled sc. This is the default for the SpanCategorizer and used by displaCy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDxiTanfuQpw6IqimTqW3g.png" /><figcaption>Example from the displaCy documentation at <a href="https://spacy.io/usage/visualizers">https://spacy.io/usage/visualizers</a></figcaption></figure><p>Opening the highlighted URL from the previous image we see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35UwGvtShGH8TCkpYFhK_A.png" /><figcaption>Overlapping spans displayed by displaCy</figcaption></figure><p>We again see the standard NER labels like ORG and GPE , but now with overlapping spans. Let’s introduce our own categories now.</p><h3>Using span categories of our own</h3><p><a href="https://cees-roele.medium.com/detecting-persuasion-with-spacy-6b6beba51076">Detecting Persuasion with spaCy</a></p><p>In my previous article <em>“Detecting Persuasion with spaCy”</em> I addressed training a model for detecting spans in a dataset for twenty categories of manipulative techniques. In the dataset, the spans in the text are identified and labelled.</p><p>Presently, we focus on visualising data from that dataset, which consists of “memes” presenting images with text. Below an example from the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*o6UMg6cgBfxGaRq59pGDNw.png" /><figcaption>Image from “SemEval-2021 Task 6: Detection of Persuasion Techniques in Texts and Images” (2021) Dimitrov et all [1]</figcaption></figure><p>For this meme, spans with the following persuasion techniques have been marked:</p><ul><li>Loaded Language</li><li>Exaggeration/Minimisation</li><li>Name calling/Labeling</li><li>Smears</li><li>Glittering generalities (Virtue)</li></ul><p>As above in the <em>“Welcome to the Bank of China”</em> example, we define a spaCy document with our text and spans. Now let’s see what it looks like for the above meme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pi6D6bxSZryz3iRozZqNvg.png" /><figcaption>displacy.serve(doc, style=’span’) without other options</figcaption></figure><p>This looks neither appealing nor insightful as all labels are now grey and they look garbled.</p><h3>Colours</h3><p>Let’s start with the colours. Displacy.serve comes with a keyword argument options , which is a python dictionary. One of these options is colors which is itself a dictionary from labels to colours. Let’s define colours for the labels that we use in this sentence:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe4d4fc2722eebdcaf5f41e59582c0a/href">https://medium.com/media/8fe4d4fc2722eebdcaf5f41e59582c0a/href</a></iframe><p>When setting these colours to the colors key in the options parameter we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyWjFuru6UV7Y-L99O3R4Q.png" /><figcaption>displacy.serve(doc, options={‘colors’: primary_colours}) # `primary_colours` as dictionary from labels to colours</figcaption></figure><p>Now we can distinguish the different spans by colour, but our colours are not nice. How can we get the colour-scheme that displaCy uses for entities? Well, by consulting the displaCy source! Here is the relevant part of render.py which shows what colours are used for what NER labels. We see that the default colour is grey (#ddd) and we see the definition of the colours for ORG and GPE which we encountered as labels in the <em>“Welcome to the Bank of China” </em>example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47fdaa3a66764060fb77bacdc76a974c/href">https://medium.com/media/47fdaa3a66764060fb77bacdc76a974c/href</a></iframe><p>To set our own colours, we create a dictionary like our earlier primary_colours example, but now we use the above colours as values for our own labels.</p><h3>Alignment of labels</h3><p>Having resolved the issue of defining colours for our labels, we still have to deal with the garbled alignment. It is caused by having long labels like Exaggeration/Minimisation and Glittering generalities (Virtue). These are the labels used in the original dataset and there was no problem training the model using them.</p><p>However, when we try to visualise these labels the graphical alignment breaks down. The solution is to use abbreviations for the labels.</p><p>As I had already trained my model for identifying the original labels, I don’t use a different set of labels altogether, but start out with the original long labels. Using a script, the spans in the document with the long labels are subsequently relabelled to the abbreviated labels.</p><h3>Scripting it</h3><p>To make it easier to display docs if I encounter the same issue in the future I created a wrapper class Redisplacy around displaCy which:</p><ul><li>Uses a dictionary to translate long labels to shorter ones, e.g. {‘Exaggeration/Minimisation’: ‘ExMin’}</li><li>Automatically attributes standard spaCy colours to the elements of this dictionary.</li></ul><p>The attribution of colours to labels is done when the Redisplacy class is initialised based on the translation dictionary. If no abbreviation is needed, the labels can be provided as a list. Note however, that all labels to be coloured must be either in the dictionary or in the list with which Redisplacy is initialised.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f4dbb652201f30b95eeb63560ded7ab/href">https://medium.com/media/6f4dbb652201f30b95eeb63560ded7ab/href</a></iframe><p>If you look at the code, you see that the class can be used as is, only the translate dictionary has to be defined and used as an argument to initialise a Redisplacy instance. Subsequently, the created instance can be used to visualise a document just as with displaCy. Note that the above code assumes that the spans in the document are created by spaCy parsing the document.</p><h3>Conclusion</h3><p>By using the standard spaCy colour scheme and abbreviating the labels we use for our spans, we now see the visualisation of the spans in our meme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rJJCHe9H-3xP9x8QaCO8w.png" /><figcaption>Result of using colours and abbreviating labels</figcaption></figure><p>DisplaCy in all its beauty!</p><h3>References</h3><p>[1] <a href="https://arxiv.org/abs/2105.09284"><em>“SemEval-2021 Task 6: Detection of Persuasion Techniques in Texts and Images”</em></a> (2021) D. Dimitrov et al</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3a43810524" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Persuasion with spaCy]]></title>
            <link>https://cees-roele.medium.com/detecting-persuasion-with-spacy-6b6beba51076?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b6beba51076</guid>
            <category><![CDATA[persuasion-techniques]]></category>
            <category><![CDATA[spacy]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 14:47:59 GMT</pubDate>
            <atom:updated>2022-06-07T14:47:59.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*xQpW86PJIZcnHOdE58-ZNQ.png" /><figcaption>Image from “SemEval-2021 Task 6: Detection of Persuasion Techniques in Texts and Images” (2021) Dimitrov et all <a href="#3583">[1]</a></figcaption></figure><h3>Introduction</h3><p>Persuasion techniques express shortcuts in the argumentation process, e.g., by leveraging on the <em>emotions</em> of the audience or by using <em>logical fallacies</em> to influence it. In this article we will create a spaCy pipeline with a SpanCategorizer to detect and classify spans in which persuasion techniques are used in a text.</p><p>Our training data identifies 20 categories. Spans may overlap, that is, a word can be part of different spans.</p><p>Here is a partial example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*pu6wUQuiSH1f-ACy6VJOxg.png" /><figcaption>Overlapping spans. Image from reference <a href="#904f">[2]</a></figcaption></figure><p>We will train different models with the dataset, use different spaCy configurations, and compare the results.</p><p><strong>Table of Contents:</strong></p><ul><li>Persuasion techniques</li><li>Dataset</li><li>Creating the corpus</li><li>Training the model</li><li>Suggesting spans</li><li>Results</li><li>Conclusion</li></ul><blockquote><strong>SpaCy configuration and python code to create the corpus </strong>used for this article<strong> </strong>are available on <a href="https://github.com/ceesroele/persuasion_spans">github</a>.</blockquote><blockquote><strong>Looking for a “HOWTO” on using spaCy for span categorisation?</strong></blockquote><blockquote>If you are looking for a walk-through on how to use spaCy for span categorisation, check out my “<a href="https://medium.com/p/c5533786bbf8">Detecting Toxic Spans with spaCy</a>”. There you will find relevant spaCy project configuration, training configuration, additional python code, and interpretation of evaluation metrics. Toxicity is only one category, but extending the approach to multiple categories and overlapping spans is technically trivial. You can find how it is done in the code accompanying the present article on <a href="https://github.com/ceesroele/persuasion_spans">github</a>.</blockquote><h3>Persuasion techniques</h3><p>Unwarranted reasoning goes by different names. Philosophers talk of <em>fallacies</em>, psychologists focus on <em>manipulation</em>, political scientists speak of <em>propaganda</em>, and linguists interested in the venerable tradition of rhetorics address <em>persuasion</em>. Each domain has its own focus on what the relevant impact of unwarranted reasoning is.</p><p>Detecting and explaining unwarranted reasoning might require epistemology, logic, estimation of intention, psychological biases, knowledge of pre-existing narrative, and even physical context. As all this doesn’t fit a feasible machine learning problem description, we convert unwarranted reasoning into a problem of classification: given a set of categories and a dataset of texts with marked spans belonging to categories, we train a model to detect such spans and classify them. We call these categories <em>persuasion techniques</em>.</p><p>Different studies have come up with different sets of persuasion techniques, e.g. ranging from a single classification of a whole text as “propaganda” to distinguishing 69 different techniques.<a href="#1dff">[4]</a> Presently, we will not discuss whether some categorisation is “better” than another or whether any categorisation is fit for purpose. Here we adopt one set of twenty techniques, with the understanding that a different set would be possible.</p><p>Let’s look at the description of some of the techniques described in <a href="#3583">[1]</a>:</p><blockquote><strong>Loaded language</strong>: Using specific words and phrases with strong emotional implications (either positive or negative) to influence an audience.</blockquote><blockquote><strong>Slogans</strong>: A brief and striking phrase that may include labelling and stereotyping. Slogans tend to act as emotional appeals.</blockquote><blockquote><strong>Causal oversimplification</strong>: Assuming a single cause or reason when there are actually multiple causes for an issue. This includes transferring blame to one person or group of people without investigating the complexities of the issue.</blockquote><blockquote><strong>Presenting irrelevant data (Red Herring)</strong>: Introducing irrelevant material to the issue being discussed, so that everyone’s attention is diverted away from the points made.</blockquote><p>These techniques are described in the context of subtask 2 of <a href="https://arxiv.org/pdf/2105.09284.pdf"><em>SemEval-2021 Task 6: “Detection of Persuasion Techniques in Texts and Images”</em></a><em> </em><a href="#3583">[1]</a>.</p><p>The present article focuses on the implementation of a system detecting and classifying spans using the spaCy SpanCategorizer and will pay only cursory attention to the meaning of techniques and to the used dataset. For detailed information on the dataset and on the meaning of the different techniques into which we classify spans, please check out the mentioned article.</p><h3>Dataset</h3><p>The dataset we use was created for SemEval-2021 task 6 <em>“Detection of Persuasion Techniques in Texts and Images”.</em> It can be found on <a href="https://github.com/di-dimitrov/SEMEVAL-2021-task6-corpus">github</a> <a href="#2674">[3]</a>.</p><p>The dataset consists of a total of 951 “memes”, short texts taken from social media posts, in which 2083 <em>spans</em> with <em>persuasion techniques</em> are identified by a team of annotators. The texts are overlaid on an image — hence they contain numerous line breaks— and many are written in uppercase. We ignore the images.</p><p>Here is an example:</p><blockquote>Our elders were called to war to save lives.\nWe are being called to sit on the couch to save theirs.\nWe can do this.\n</blockquote><p>Persuasion spans in this text:</p><ul><li><strong>Exaggeration/Minimisation</strong>: <em>“Our elders were called to war to save lives.\nWe are being called to sit on the couch to save theirs.”</em></li><li><strong>Appeal to fear/prejudice</strong>: <em>“war”</em></li><li><strong>Appeal to fear/prejudice</strong>: “<em>sit on the couch to save theirs</em>”</li><li><strong>Slogans</strong>: “<em>We can do this.</em>”</li></ul><p>Below the overview of persuasion techniques distinguished in the dataset with for each the number of occurrences in the dataset and the average number of tokens in a span. To determine the number of words in a span the standard spaCy tokeniser was used. Note that interpunction and whitespace tokens are included in the counting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFmeSrfom0tBahKk35Gqjg.png" /><figcaption>Total occurrences for each technique and average number of tokens for span labelled as technique</figcaption></figure><p>In total there are <strong>2083 spans</strong>.</p><p>Looking at the table you see:</p><ul><li>The first two categories make up <em>more than half</em> the dataset and are on <em>average under three words</em> long which is much shorter than almost all other categories.</li><li>Almost two thirds of the categories have ten or more tokens on average in the spans in which they occur.</li></ul><p>Generally:</p><ul><li>The dataset is rather small</li><li>Distribution over classes is uneven. Most classes in the dataset have less than 50 samples, which is small. Only <em>Loaded Language</em>, <em>Name Calling/Labeling</em>, and <em>Smears</em> have a sizeable number of instances.</li></ul><h3>Creating a corpus</h3><p>Defining spans is like taking a coloured marker and highlighting a fragment of the original text. As we need exact fragments, we will not modify the original text by pre-processing it in any way.</p><p>Our dataset is already divided into train, dev, and test parts. We convert each of these files separately into a binary .spacy file which is used as input for training.</p><h3>Training the model</h3><p>As it is an open question what base model would best fit our requirements we will try <em>small</em>, <em>large</em>, and <em>transformer</em> models and compare the results.</p><p>Once our corpus is defined we can start a training using the spacy train <a href="https://spacy.io/api/cli#train">command</a>. For readability and repeatability we define this in a spaCy <a href="https://spacy.io/usage/projects">project</a>. You can find an example of a regular pipeline consisting of <em>corpus</em>, <em>train</em>, and <em>evaluate</em> steps in the <a href="https://github.com/ceesroele/toxic_spans/blob/main/project.yml">project.yml</a> of my article <em>“</em><a href="https://cees-roele.medium.com/detecting-toxic-spans-with-spacy-c5533786bbf8"><em>Detecting Toxic Spans with Spacy</em></a><em>”</em>.</p><p>Such a pipeline makes fine-tuning training of one model easy. Here we will not tune, but instead use three basis models and see how they perform. To define their configuration we use the <a href="https://spacy.io/usage/training#quickstart">“Quickstart” dialog</a> in the spaCy documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*KY4YqTm1oMhg50Ms_3sK5g.png" /><figcaption>Configuration “quickstart” at <a href="https://spacy.io/usage/training#quickstart">https://spacy.io/usage/training#quickstart</a></figcaption></figure><p>We select the spancat component and generate three configurations:</p><ol><li>CPU + efficiency (<em>small</em>)</li><li>CPU + accuracy (<em>large</em>)</li><li>GPU (doesn’t distinguish between efficiency and accuracy) (<em>transformer</em>)</li></ol><p>This will result in <em>small</em>, <em>large</em>, and <em>transformer</em> models. The default spaCy transformer model is RoBERTa-base.</p><p>Using default configuration values, we will train each of these models and compare the results.</p><h3>Suggesting spans</h3><p>To detect spans, spaCy first generates a set of <em>possible</em> spans for a document. This is done by a component named <a href="https://spacy.io/api/spancategorizer#suggesters">Suggester</a>.</p><blockquote>Spans can only be detected if they are first generated or “suggested”.</blockquote><p>SpaCy 3.3 comes with two implementations of Suggesters, both based on generating <em>n-grams</em>, that is, spans of n tokens. The ngram_suggester is configured with a list of lengths of n-grams, e.g. [1, 2, 3, 4]. The ngram_range_suggester is configured with a <em>minimum</em> and <em>maximum</em> of a range of lengths, e.g. min_size=1, max_size=4.</p><blockquote>Corollary: Spans longer than the maximum length of suggest n-grams will <strong>not</strong> be detected.</blockquote><p>Named entities typically consist of only a few tokens. With a token-length of 5 the named entity <em>“Berlin Brandenburg Airport Willy Brandt”</em> is relatively long. In our current dataset, however, we deal with spans that might even range across sentences. Here is an example fragment from our dataset of the category Causal Simplification: <em>“Childish Trump Won’t Meet With Pelosi On Coronavirus\nBecause He Doesn’t Like Her”.</em> SpaCy tokenises this fragment into 15 tokens, including one for the newline, where <em>“won’t”</em> is broken up into [<em>“wo”</em>, <em>“n’t”</em>].</p><p>As training, evaluation, and prediction of any span can only succeed if it doesn’t contain more tokens than generated by the Suggester, we must look into our dataset and see how many samples are cut off.</p><p>In the table below, we take 8-grams, 16-grams, and 32-grams as maximums for the ngram-range-suggester.</p><p>We apply some markup based on arbitrary limits:</p><ul><li>&lt; 10%: <em>satisfactory</em> (greyed)</li><li>&gt; 10% &amp; &lt; 30%: <em>cause for concern</em> (black)</li><li>&gt; 30% : <em>bad</em> (red)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDwUDkECu1EvHunDAvqsoQ.png" /><figcaption>Samples cut off because containing more tokens than the Suggester supports</figcaption></figure><p>What we see:</p><ul><li><em>Loaded Language</em> and <em>Name Calling/Labeling</em> satisfy all chosen n-gram maxima</li><li>For a maximum of 8-grams only 6 techniques have a smaller cut rate than 30%</li><li>For a maximum of 16-grams only 10 techniques have a smaller rate cut than 30%</li><li>For a maximum of 32-grams there are still 4 techniques having a cut rate between 10% and 30%</li></ul><p>We will train with suggesters with maximums of 16-grams and 32-grams. We will ignore a suggester with a maximum of 8-grams as this looks unpromising given that so many techniques are not covered satisfactorily by that suggester.</p><blockquote>Note: More suggester functions are currently <a href="https://github.com/explosion/spacy-experimental">experimentally available</a>, e.g. subtree_suggester, (noun) chunk_suggester, and sentence_suggester.</blockquote><h3>Results</h3><p>Looking at F1 scores for the n-gram suggester set to maximums of 16 and of 32 tokens we find:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyZzKEDZ6Yf_8hGdISAAkQ.png" /></figure><p>As expected, the <em>large</em> (lg) model does better than the <em>small</em> (sm) model and the <em>transformer</em> (trf) model does better than the large model. Surprisingly, however, the small and large models do <em>worse</em> with 32-grams than with 16-grams. Also we find that the transformer model is doing <em>significantly better</em> with 32-grams than with 16-grams.</p><p>In the table below the data for the F1 score used in the diagram above plus precision and recall measure. Values that have <em>decreased</em> for the 32-grams suggester are marked in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*rArUce8d_i_WFDOqWk1eQw.png" /><figcaption>F1 scores for small (sm), large (lg), and transformer (trf) models for 16/32-grams suggesters</figcaption></figure><p>What we see is that for the small and large models the recall <em>decreases</em> for the 32-gram suggester, but the precision <em>increases</em>.</p><p>This means that the small and large models label too many tokens that shouldn’t be labelled for the 32-gram suggester, although they do cover more of those that should be labelled. Let’s call is over-optimistic labelling. The transformer models don’t suffer from that defect.</p><p>It would be interesting to determine <em>why</em> this is happening, but that would require further research.</p><p>Let’s look at the F1 scores for each individual persuasion technique:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIbgCpuYZ1fkoVJpf5BupQ.png" /></figure><p>We see:</p><ul><li><em>Name Calling/Labeling</em> and <em>Loaded Language</em> are predicted best. This is understandable given that for these categories we have the largest number of samples while they also have on average among the fewest tokens per span</li><li>Prediction for 32-grams for small and large models gets <em>worse</em> or remains <em>on a par</em> for these two techniques compared to 16-grams.</li><li>Remarkably, the small model picks up two technique with 16-grams which the others don’t but it doesn’t pick them up with 32-grams.</li><li>Transformer models pick up additional techniques in 32-grams suggesters, but the other models don’t.</li><li>Transformer models do better even for the short spans of <em>Name Calling/Labeling</em> and <em>Loaded Language</em> when using a 32-gram suggester than when using a 16-gram suggester.</li></ul><h3>Duplicate predictions</h3><p>Created models should be able to predict spans for different classes that overlap each other. However, what happens — and what should not happen — is that there are predictions of spans with the same label that overlap each other. The following image illustrates the prediction of a 32-grams transformer-based model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVfVombIzIqzSVkG38vR0Q.png" /><figcaption>Duplicates: prediction of overlapping spans with the same label</figcaption></figure><p>I consider this an error of the SpanCategorizer.</p><h3>Comparison with other span detection systems</h3><p>Metrics are merely numbers unless serving to compare different systems producing them. As we effectively implemented subtask 2 of Task 6 of SemEval 2021, we can compare our outcome with other systems on the leaderboard for that task. SpaCy uses token-based metrics, but the mentioned contest uses character-based metrics.</p><p>Using the best model to produce a prediction for the test dataset and having the result evaluated by the scorer method provided for the contest leads to a character-based F1 of 0.449. That would place it second in the Task 6 ranking published in <a href="#3583">[1]</a>!</p><p>This encourages future research comparing the architecture of the spaCy model-with-suggester with the models participating in Task 6.</p><h3>Conclusion</h3><p>We have seen that spaCy’s SpanCategorizer can be used to detect spans and classify them. As the dataset used for the present article contains spans of widely varying length, we needed to take the functionality and configuration of the spaCy Suggester into account, which is the function generating spans. For this dataset transformer models proved significantly more accurate than spaCy’s small and large models. The resulting model ranked well within alternative systems for detecting and classifying spans.</p><h3>References</h3><p>[1] <a href="https://arxiv.org/abs/2105.09284"><em>“SemEval-2021 Task 6: Detection of Persuasion Techniques in Texts and Images”</em></a> (2021) D. Dimitrov et al</p><p>[2] <a href="https://aclanthology.org/2021.semeval-1.32.pdf"><em>“WVOQ at SemEval-2021 Task 6: BART for Span Detection and<br>Classification”</em></a> (2021) Cees Roele</p><p>[3] <a href="https://github.com/di-dimitrov/SEMEVAL-2021-task6-corpus"><em>“Data for SemEval-2021 Task 6: Detection of Persuasive Techniques in Texts and Images”</em></a>, github</p><p>[4] <a href="https://aclanthology.org/D19-1565.pdf"><em>“Fine-Grained Analysis of Propaganda in News Articles”</em></a> (2019) G. Da San Martino et al</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b6beba51076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom evaluation of spans in spaCy]]></title>
            <link>https://cees-roele.medium.com/custom-evaluation-of-spans-in-spacy-f1f2e7a99ad8?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1f2e7a99ad8</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[toxicity]]></category>
            <category><![CDATA[spacy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Fri, 06 May 2022 14:48:24 GMT</pubDate>
            <atom:updated>2022-08-25T02:50:29.283Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom Evaluation of Spans in spaCy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGQOUxQ5TPR6Nt1JotLL9A.png" /><figcaption>Toxic fragments in the ‘Toxic Spans Detection’ dataset [1]</figcaption></figure><h3>Introduction</h3><p>Spans are fragments of a text belonging to a particular class. To evaluate the prediction of spans we chop a text into atomic pieces and determine for each of them if they have been correctly classified. Out-of-the-box spaCy provides token-based metrics for span-prediction. In my earlier article “<a href="https://medium.com/@cees-roele/detecting-toxic-spans-with-spacy-c5533786bbf8"><em>Detecting Toxic Spans with spaCy</em></a>” I provided a script to create character-based metrics. The present article will go into more depth on the different methods of calculation and will replace the standard spaCy token-based <em>scorer</em> with a character-based one in the created spaCy pipeline.</p><blockquote><em>You can find the full code for this article tagged as release 2.0.0 at: </em><a href="https://github.com/ceesroele/toxic_spans"><em>https://github.com/ceesroele/toxic_spans</em></a></blockquote><blockquote><em>To download this release:</em></blockquote><blockquote><em>git clone https://github.com/ceesroele/toxic_spans.git --branch v2.0.0</em></blockquote><h3>Precision, Recall, and F1</h3><p>We evaluate predictions of spans for a given text by splitting the text into atomic entities and checking for each of these if they have been correctly labelled.</p><p>We quantify the outcome using the following measures:</p><ul><li><em>Precision</em> — fraction of correctly predicted labels as part of all predicted labels</li><li><em>Recall</em> — fraction of correctly predicted labels as part of the number of all correctly applied labels</li><li><em>F1</em> — harmonic mean of precision and recall</li></ul><p>The actual calculation depends on how we split up the text. In the next section you first see the standard way for spaCy to do this and in the section after that our replacement for it.</p><h3>SpaCy’s span metrics: token-based</h3><p>SpaCy’s standard precision, recall, and F1 metrics are based on atomisation through spaCy’s tokenisation.</p><p>Let’s identify spans in a text — <em>“We are on the misty battlements of Elsinore Castle.”</em> — and categorise them. We won’t worry about the meaning of categories, just say that <em>“misty battlements”</em> and <em>“Elsinore Castle”</em> are correct spans. The predicted spans are <em>“on” </em>and<em> “Castle”.</em></p><p>In the table headers, correct definitions of spans are called <em>“gold” (in green)</em>, <em>“pred”</em> is called the prediction (in yellow), and under <em>“compare”</em> we find how the correct spans compare with the predicted spans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfoIbE3THZe67i2fCt86jg.png" /><figcaption>Token-based atomisation</figcaption></figure><p>Let’s go through the comparison:</p><ul><li><em>“on”</em> is predicted, but not correct. It is a False Positive (FP)</li><li><em>“misty battlements”</em> and <em>“Elsinore ”</em> are correct, but not predicted. They are False Negatives (FN)</li><li><em>“Castle”</em> is both correct and predicted. Is is a True Positive (TP)</li><li>anything neither correct nor predicted is a True Negative (TN)</li></ul><p>We calculate Precision, Recall, and F1 as follows:</p><blockquote><em>Precision = TP / (TP + FP)</em> (correct predictions divided by all predictions)</blockquote><blockquote><em>Recall = TP / (TP + FN)</em> (correct predictions divided by all correctly labelled entities)</blockquote><blockquote><em>F1 = (2 * Precision * Recall) / (Precision + Recall)</em> (harmonic mean)</blockquote><p>Note that TN, the correctly <em>not</em> predicted absence of labels, doesn’t influence the calculations. This means that the length of the total text doesn’t matter, only the predictions and correct labels.</p><p>Now, let’s calculate the values for the above example. We find:</p><ul><li>FN=3</li><li>FP=1</li><li>TP=1</li></ul><blockquote><em>Precision = TP / (TP + FP) = 1 / (1 + 1) = 0.5</em></blockquote><blockquote><em>Recall = TP / (TP + FN) = 1 / (1 + 3) = 0.25</em></blockquote><blockquote><em>F1 = (2 * Precision * Recall) / (Precision + Recall) = 2 * 0.5 * 0.25 / (0.5 + 0.25) = 0.33</em></blockquote><h3>SemEval-2021 Task 5 metrics: character-based</h3><p>For the <a href="https://aclanthology.org/2021.semeval-1.6.pdf">“Detecting Toxic Spans” task of SemEval-2021</a>[1] a character-based metric was used. As we want to compare the outcome of our SpanCategorizer based system with the published performance of the participants of that task, we want to use the same metric. Note that for a contest with different participants using different system, it is good not to assume any specific method of tokenisation, hence using a character-based metric.</p><p>Let’s see how the same prediction as in the previous section works out per character:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWR-cmdFwg19_p4VQJoy_A.png" /><figcaption>Character-based atomisation</figcaption></figure><p>When we calculate values for our metrics now, we find:</p><ul><li>FP=2</li><li>FN=17+9=26</li><li>TP=6</li></ul><blockquote>Precision = TP / (TP + FP) = 6/ (6 + 2) = 0.75</blockquote><blockquote>Recall = TP / (TP + FN) = 6/ (6 + 26) = 0.19</blockquote><blockquote>F1 = (2 * Precision * Recall) / (Precision + Recall) = 0.24</blockquote><p>We see that the outcome for the F1-score differs significantly : 0.24 vs 0.33 for the character-based calculation versus the token-based calculation.</p><p>To evaluate a model we typically look at a set of examples, rather than just one. SpaCy effectively treats multiple records as one big text: it sums up all values of TP, FP, and FN and then calculates the precision, recall, and F1 values.</p><p>The SemEval calculation takes the precision, recall, and F1 values of each individual text in a set and then takes their mean value.</p><h3>Integration</h3><p>In the earlier article on <a href="https://medium.com/p/c5533786bbf8"><em>“Detecting Toxic Spans with spaCy”</em></a> we added a character-based evaluation as an additional script to our project, running after the standard evaluation.</p><p>What we will do now is integrate this method of evaluation into our training and evaluation so that the character-based method will be:</p><ol><li>Displayed using training</li><li>Basis of evaluation</li><li>Packaged with the created pipeline as standard evaluation method</li></ol><p>Rather than create a separate system of evaluation, which includes reporting, we will replace the method performing the actual calculation, the <em>scorer</em>.</p><h3>Implementing the scoring method</h3><p>We need to implement a method that takes a set of Example objects as its argument and returns a dictionary with Precision, Recall, and F1 values.</p><p>Examples here are spaCy objects that consist of a two spaCy Doc objects:</p><ul><li>reference : document with correct or “gold” spans</li><li>prediction : document with the spans predicted by the model</li></ul><p>Here is a prototype of the method we seek to implement, for now with constants as values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QijcxDD1Nmg5PQuCTPYEFg.png" /><figcaption>Prototype of scoring method: it takes examples and a spans_key and returns a dictionary with metric values.</figcaption></figure><h3>Registering our new scorer</h3><p>Now that we have implemented a scoring algorithm, we need to <a href="https://spacy.io/api/top-level#registry">register</a> it. In our configuration file we define the name we want to use for our scorer. Note that we use a custom spans_key value of txs to set apart toxic spans from any other spans you may want to attribute to a document. If you don’t want to mix sources of spans, you can stick with SpanCategorizer’s default spans_key=sc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLeJbkynGFd_s42tFVH5EQ.png" /><figcaption>Fragment of our adapted configuration file</figcaption></figure><p>This name must match the name we use to register a method in our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXLUiJyM9D9KC1sBtvZYsw.png" /><figcaption>Registration of method <em>returning our actual scoring method</em></figcaption></figure><p>We can now implement the method that does the actual calculation of the scores. The algorithm is based on the <a href="https://github.com/ipavlopoulos/toxic_spans/tree/master/SemEval2021">original code</a> from the SemEval 2021 <em>Toxic Spans Detection</em> task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be7d33a2b9ff84d48d6c49b45163308/href">https://medium.com/media/9be7d33a2b9ff84d48d6c49b45163308/href</a></iframe><p>Note that the scoring function we implemented here is not only different from the standard spaCy function but also more limited: it assumes there is only one label and it doesn’t provide a score per label.</p><p>To actually display our new metrics during training, we need to define output columns in our configuration for our spans_key with the value txs and silence the default sc. (No need to do this is you stick with the default spans_key=sc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXlIX8eezUBcqFl_aJWoew.png" /><figcaption>Defining training score weights for our spans_key ‘txs’ and silencing default spans_key ‘sc’.</figcaption></figure><p>Now that we have integrated our new scorer into the pipeline, the standard evaluation method will calculate the metrics according to the custom way.</p><h3>Loading the generated model</h3><p>In the previous article we loaded the model from ./training/model-best . When we try this now, we will get an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bE-q5TteL3gkWnhyrQbbMw.png" /><figcaption>Last part of error message after: spacy.load(‘training/model-best’): RegistryError: Could not find function…</figcaption></figure><p>What is happening? Remember that we “registered” our scorer method in our configuration file? That file ends up as part of our pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3GP2Byblc094_4wa304PA.png" /><figcaption>Configuration file as part of generated pipeline ‘model-best’</figcaption></figure><p>To be able to load the model, we need to <strong>import the registered scorer method into the scope of our code,</strong> e.g.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ny9jlTsZi78MSSbnDTex_A.png" /><figcaption>Import the registered scorer method to load model without errors</figcaption></figure><h3>Packaging</h3><p>Once we are confident that the generated model is satisfactory, we can “package” it using spaCy’s <a href="https://spacy.io/api/cli#package">package command</a> . Basically, it takes a directory with a model, like our ./training/model-best , and transforms this into a single .tar.gz or .whl file. As the next step, we can use pip to install the file locally after which it is available for loading as a model in spaCy.</p><p>First, we need to add the code with our customised scorer using the --code parameter, similar to the manual import we enacted above.</p><p>To add our custom code and define a name and version, we can package our pipeline as follows, writing the output to the ./packages directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec77c71fb693931b7a6ff1254305fcd0/href">https://medium.com/media/ec77c71fb693931b7a6ff1254305fcd0/href</a></iframe><p>Note that the name will be prefixed with the used language, in this case en. The result will be: ./packages/en_toxic_detector-1.0.0/dist/en_toxic_detector-1.0.0.tar.gz</p><p>You can find additional variables in ./training/model-best/meta.json . Here is the originally generated version for our project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d3fab53c745bb07b968bf73cbcf6654/href">https://medium.com/media/1d3fab53c745bb07b968bf73cbcf6654/href</a></iframe><p>You can run the package command with your own version of meta.json through --meta-pathor you can create a new one interactively through --create-meta . Check out the <a href="https://spacy.io/api/cli#package">documentation</a> of the package command.</p><p>As spaCy won’t load a pipeline from a file, we must install it where it can be read. We do this using pip:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e57a6ec3eca1e8ef3f73e67dad7993b/href">https://medium.com/media/6e57a6ec3eca1e8ef3f73e67dad7993b/href</a></iframe><p>After this, we can load our model using:</p><blockquote>nlp = spacy.load(“en_toxic_detector”)</blockquote><p>That’s it! We created our span detecting pipeline with a customised evaluation scorer.</p><h3>Conclusion</h3><p>In this article you saw how to create a custom scorer function for the spaCy SpanCategorizer in order to provide your method of calculating metrics during training and evaluation. You also saw how to package the resulting model together with the custom code, so you can load and invoke it as a pipeline in spaCy.</p><h3>References</h3><p><em>[1] “</em><a href="https://aclanthology.org/2021.semeval-1.6.pdf"><em>SemEval-2021 Task 5: Toxic Spans Detection</em></a><em>”</em> (2021) by John Pavlopoulos et al.</p><h3>Update history</h3><p>25 Aug 2022:<br>1. Added instruction to clone release v2.0.0 at the top of the article.</p><p>2. Explained why I use a custom spans_key, rather than SpanCategorizer’s default sc .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1f2e7a99ad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Toxic Spans with spaCy]]></title>
            <link>https://cees-roele.medium.com/detecting-toxic-spans-with-spacy-c5533786bbf8?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5533786bbf8</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[toxicity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[spacy]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Sat, 09 Apr 2022 08:29:15 GMT</pubDate>
            <atom:updated>2022-09-06T07:27:40.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>An expression is toxic if it uses rude, disrespectful, or unreasonable language that is likely to make someone leave a discussion. Toxic language can be short like <em>“idiot”</em> or longer like <em>“your ‘posts’ are as usual ignorant of reality”.</em></p><p>We will use the SpanCategorizer from spaCy to detect toxic spans. For illustration we will use a well-researched dataset. The present article focuses on the spaCy configuration and usage. Part two, <a href="https://medium.com/p/f1f2e7a99ad8"><em>“Custom evaluation of spans in spaCy”</em></a>, focuses on integrating the metric calculations presented here as a <em>scorer</em> in the spaCy pipeline.</p><blockquote>You can find the full code for this article tagged as release 1.0.0 at: <a href="https://github.com/ceesroele/toxic_spans">https://github.com/ceesroele/toxic_spans</a></blockquote><blockquote>To download this release:</blockquote><blockquote>git clone https://github.com/ceesroele/toxic_spans.git —-branch v1.0.0</blockquote><h3>Categorizing spans</h3><p>A <em>span</em> is a fragment of a text which we may label as belonging to some category. A text can consists of multiple spans which may have different labels. Spans are similar to <em>Named Entity Recognition (NER).</em></p><p>However, in addition to tokens representing entities, spans may overlap: a word may be part of two different spans at the same time.</p><p>SpaCy contains a <a href="https://spacy.io/api/spancategorizer">SpanCategorizer</a> since version 3.1. This is an element — briefly named spancat — in the spaCy pipeline that can detect spans for which it has been trained.</p><h3>Toxic spans dataset</h3><p>We use the dataset from task 5 of SemEval2021. You can find a description of the task and a discussion of the outcome for different participants in <em>“</em><a href="https://aclanthology.org/2021.semeval-1.6.pdf"><em>SemEval-2021 Task 5: Toxic Spans Detection</em></a><em>”</em> (2021) by John Pavlopoulos et al¹. The dataset and baseline code are available at <a href="https://github.com/ipavlopoulos/toxic_spans">github</a>.</p><p>The dataset contains some ten thousand posts with annotations for toxic spans. These annotations consist of a list of all indexes of the characters of the post that are part of a toxic span.</p><p>Example from the CSV file containing the data:</p><blockquote>“[11, 12, 13, 14, 16, 17, 18, 19, 20]”,you’re one sick puppy.</blockquote><p>The character indexes 11 to 20 refer to “sick puppy”.</p><p>Generally, about the dataset:</p><ul><li>Many of the posts contain one span</li><li>The vast majority of the spans consists of one one word, e.g. “idiot”.</li></ul><p>Note that there is only one category (“toxic”) and the identification of spans is per character, so even though it would theoretically be possible to have two partially overlapping toxic spans, in practice in our dataset it doesn’t occur. One result is that it is possible to treat the problem as a NER-problem, rather than as a span problem. Actually, this is how detecting toxic spans was implemented in a <a href="https://github.com/ipavlopoulos/toxic_spans/blob/master/SemEval2021/baselines/spacy_tagging.py">spaCy NER example script</a> provided with the dataset.</p><h3>Project</h3><p>Our goal is to create a spaCy <em>pipe</em> that detects toxic spans in a text. To do this, we must <em>train</em> a model using our dataset. Once the model is trained we want to <em>evaluate</em> it. If it is to our satisfaction, we will <em>deploy</em> our model.</p><p>Here are our steps:</p><ol><li>Download the CSV data files (already divided in train, dev, and test sets)</li><li>Convert the data into a format that can be used for training.</li><li>Train</li><li>Evaluate</li><li>Deploy the resulting model</li></ol><p>SpaCy provides standard functionality for training and evaluating models. This can be called as part of programming code, but also be called through a <a href="https://spacy.io/usage/projects"><em>project</em></a>.</p><p>We will go the latter way and define a spaCy project for our steps. As a basis we take the <a href="https://github.com/explosion/projects/blob/v3/experimental/ner_spancat/project.yml">project.yml</a> from the experimental <em>NER-spancat</em> project. This project provides NER for the Indonesian language using SpanCategorizer functionality.</p><h3>Download datafiles</h3><p>In our project file we define the location of our assets, that is the data we are looking for. Here we get all files from a <a href="https://github.com/ipavlopoulos/toxic_spans/tree/master/SemEval2021/data">path in a repository in github</a> and place them in the subdirectory or destination “assets”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCHsL8FqRaECjS3fE41lDQ.png" /></figure><p>Let’s download the assets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l-HXe5M1Z67iuYMDvoOruQ.png" /></figure><p>We see that the “1 asset(s)” consists of three CSV files. These are the ones that were in the path SemEval2021/data in the repository defined above.</p><h3>Convert</h3><p>Now that we have our data files, we need to convert the data to a format suitable for training. Here we merge the list of indexes and text strings in the rows of our three CSV files into Doc objects with defined spans.</p><p>These Doc objects we bundle into a single DocBin object which we save to a file in the custom binaryspacy format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7e6b1ae6ea229c2f2dbd71e4153d80e/href">https://medium.com/media/f7e6b1ae6ea229c2f2dbd71e4153d80e/href</a></iframe><p>We call these methods from a file named make_corpus.py . Note that we transform the original names of the data files to <em>train</em>, <em>dev</em>, and <em>eval</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWwNhCSuS-sfw_fvGFJ-Xw.png" /></figure><p>In our project definition we define a command from calling the above make_corpus.py:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGMwyBmdmqpSVLwD554JnQ.png" /></figure><p>To actually create the corpus of spacy files from the CSV assets by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Yt9ibc8tGIstG9IIxzmdQ.png" /></figure><h3>Train</h3><p>We now have train and dev datasets in a format we can process. In order to actually train a model to recognise toxic span using this data, we need to configure such a model and some parameters for our training process first.</p><p>SpaCy provides an easy way to define such a configuration through a quickstart widget on its webpage documenting the <a href="https://spacy.io/usage/training">training process</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iP4g9vTmJkLADPxwstcBig.png" /><figcaption>Training configuration widget. Bottom left shows part of generate configuration code.</figcaption></figure><p>The only change compared to the default settings we make in the widget above is that we check spancat to enable the SpanCategorizer pipe. Note that selecting accuracy for “optimize for” would lead to a large language model being used.</p><p>The displayed part of the generated configuration is only part of the entire file.</p><p>We copy the contents of the configured widget and paste it into a file configs/base_config.cfg . We then fill it in with all default values and save the result as configs/config.cfg with the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3n71NJ9wnECOSoKGTuCzA.png" /><figcaption>Running init fill-config</figcaption></figure><blockquote>Note on the next step:</blockquote><blockquote>The default spans_key for SpanCategorizer is sc . You can use this default, which will spare you some of the extra steps I have made below. However, I think it is good practice to let each application adding spans, here toxic spans, set its own spans_key as it allows you to mix spans from different sources. E.g. SpaCy’s <a href="https://spacy.io/api/spanruler">SpanRuler</a> uses default spans_key=ruler .</blockquote><p>We make a few modifications in our new configs/config.cfg:</p><ul><li>We set our spans_key to txs so as not to use the default sc value.</li><li>We define sizes for ngrams for the Suggester to everything from 1 to 8. ( Suggesteris beyond the scope of this article. For info see spaCy SpanCategorizer <a href="https://spacy.io/api/spancategorizer#suggesters">documentation</a>.)</li><li>We define columns for representing scores during training by excluding those for the default sc spans_key and including those for our newly definedtxs spans_key.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4rxUejLgMY8bmBIiJb9c9Q.png" /><figcaption>Changes in configs/config.cfg</figcaption></figure><p>In our project file we define how to run our training. Most importantly, we refer to our config file ( configs/${vars.config}.cfg , where vars.config was defined as “config”), use our created corpus/train.spacy for basic training, and corpus/dev.spacy for the development set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXQqI7NGmb5N611TPZ89Eg.png" /><figcaption>Definition of the training command in project.yml</figcaption></figure><p>Now, let’s start the training process and follow the results as the training is executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBW21ay7NgUaJ2_Hi35QEA.png" /><figcaption>Start training and follow the the output</figcaption></figure><p>We see that we have a highest score — equaling spans_txs_f — of 0.57. The model that was used to generate the best score is saved in ./training/model-best.</p><h3>Evaluate</h3><p>As we already saw during the training, the standard metric used for evaluating spans is <a href="https://machinelearningmastery.com/precision-recall-and-f-measure-for-imbalanced-classification/">Precision — Recall — F1</a>.</p><p>F1 combines precision and recall into a single measure that captures both properties.</p><blockquote>Precision = TruePositives / (TruePositives + FalsePositives)</blockquote><blockquote>Recall = TruePositives / (TruePositives + FalseNegatives)</blockquote><blockquote>F1 = (2 * Precision * Recall) / (Precision + Recall)</blockquote><p>Standard, the scorer for the spaCy SpanCategorizer calculates these metrics over entire tokens. As we want to compare our outcome with the published scores of participants in the SemEval2021 Task where a character-based score was used, we also want to generate a character-based F1 score for our evaluation. This means that in “Hello idiot world!” we count idiot not as 1 <em>TruePositive</em>, but as 5 <em>TruePositives</em>, that is, one for each character of the token idiot. There is a slight numerical difference between these two methods of calculation.</p><p>In our project file we define how to run our evaluation. Most importantly, we use our created corpus/eval.spacy to provide the data for evaluating the model, use training/best-model , and we invoke scripts for the standard token-based — and the custom character-based scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBaK_LwH2-_efcx5E0qQcQ.png" /><figcaption>Definition of the evaluate command in project.yml</figcaption></figure><p>Let’s start the evaluation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pvmfU_VizIFKeanItSggQ.png" /><figcaption>Start evaluation and follow the output</figcaption></figure><p>At the bottom we see that our character-based F1 score: F1 = 63.01 which is one percent point lower than the token-based F1 score.</p><p>How does this compare to the results of participants of SemEval2021 Task 5: Toxic Span Detection? Let’s see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*NhdbBdgYOU7Re-iOGjS-uQ.png" /><figcaption>Participant results of SemEval2021 Task 5: Toxic Span Detection. Table from Pavlopoulos et al (2021)¹.</figcaption></figure><p>We see that our outcome trails at the bottom of the ranking, but not below it. Interpretation of the outcome will be done in a separate article, but for now let it suffice that we created the functionality without any optimization.</p><h3>Deploy the resulting model</h3><p>For illustration purposes it suffices to just load the best model from the directory where the training process has saved it, in training/model-best .</p><p>The script below uses the trained model and displays predicted spans using <a href="https://spacy.io/api/top-level/#displacy">displaCy</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b78d5a7d0070443018d63c8cbe207aa/href">https://medium.com/media/2b78d5a7d0070443018d63c8cbe207aa/href</a></iframe><p>Running the above script in a Jupyter notebook we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bz9UGUB4nXSwNEbkNHxB-A.png" /><figcaption>Displaying predicted toxic spans using displacy</figcaption></figure><p>Good, this works!</p><h3>Conclusion</h3><p>We implemented toxic span detection using spaCy and came to a usable but non-optimized result. Although our dataset covers only the simplest case with only non-overlapping spans and only one category, our steps illustrate how to train and use the spaCy SpanCategorizer .</p><p>Interpretation of the results was not part of the scope of the article. It will be covered in a follow-up article.</p><h3>References</h3><p><em>[1] “</em><a href="https://aclanthology.org/2021.semeval-1.6.pdf"><em>SemEval-2021 Task 5: Toxic Spans Detection</em></a><em>”</em> (2021) by John Pavlopoulos et al.</p><h3>Update history</h3><p>8 May 2022: linked to part 2:<em> </em><a href="https://medium.com/p/f1f2e7a99ad8"><em>“Custom evaluation of spans in spaCy”</em></a></p><p>25 Aug 2022: <br> 1. Added link to clone release v1.0.0 at the top of the article.</p><p>2. Explained why I use a custom spans_key, rather than SpanCategorizer’s default sc .</p><p>6 Sept 2022:</p><p>Displaying spans now uses displaCy. Removed reference to custom-code for displaying spans.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5533786bbf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring “disinformation” at EUvsDisinfo]]></title>
            <link>https://cees-roele.medium.com/exploring-disinformation-at-euvsdisinfo-6cec6c7f05e2?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cec6c7f05e2</guid>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[disinformation]]></category>
            <category><![CDATA[narrative]]></category>
            <category><![CDATA[cluster]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 14:44:52 GMT</pubDate>
            <atom:updated>2022-03-18T14:44:52.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p><em>“Disinformation”</em> is a term used by governments to justify regulation of public communication. The present article presents a quantitative exploration of the actual use of the term “disinformation” based on data from the EUvsDisinfo website. Over the past six years this website published over nine hundred news articles and over thirteen thousand “disinformation cases”.</p><p>From this body of articles a set of sentences was extracted containing the word “disinformation”. Using <em>Wordcloud</em> and <em>TF-IDF</em> it was found that central to “disinformation” is the word “narrative”. We therefore changed the dataset to be studied to be those of sentences containing the word “narrative”.</p><p>To identify narratives we tried to distinguish which ones are mentioned in the dataset. <em>K-means</em> clustering was applied on a <em>TF-IDF</em> matrix of the dataset resulting in sixteen clusters of sentences.</p><p>The challenge was to learn something about narratives from our data on clusters. For this purpose, we presented the clusters as summaries using <em>BART-large-CNN</em>, on a 2D plan using <em>word vectors</em> and <em>PCA</em>, and in a custom structured format using <em>spaCy</em> tokenisation into entities and part-of-sentence analysis.</p><p>As this is an exploration, we end with an overview of findings and suggestions for continuing research.</p><h3><strong>Goal, methodology, and dataset</strong></h3><p>A short definition of <em>“disinformation”</em> is <em>“verifiably false or misleading information”</em>.</p><p>EUvsDisinfo uses the definition of the European Commission, which defines disinformation as</p><blockquote>“the creation, presentation and dissemination of verifiably false or misleading information for the purposes of economic gain or intentionally deceiving the public, and which may cause public harm. Such harm may include undermining democratic processes or threats to public goods such as health, the environment and security. As opposed to illegal content (which includes hate speech, terrorist content or child sexual abuse material), disinformation covers content that is legal. It therefore intersects with fundamental core European Union (EU) values of freedom of expression and the press. Under the Commission’s definition, disinformation does not include misleading advertising, reporting errors, satire and parody, or clearly identified partisan news and commentary.”</blockquote><p>Source: <em>“Action Plan Against Disinformation”</em>, European Commission, 5 December 2018, <a href="https://ec.europa.eu/info/sites/default/files/eu-communication-disinformation-euco-05122018_en.pdf">https://ec.europa.eu/info/sites/default/files/eu-communication-disinformation-euco-05122018_en.pdf</a></p><p>Apart from “verifiably false or misleading information”, this definition contains numerous exceptions and complications, e.g. <em>“disinformation does not include … clearly identified partisan news and commentary”</em>.</p><p>Our goal is to get a better understanding of the notion of “disinformation”. We do this by quantitatively exploring a dataset and creating a number of proof-of-concept implementations to present the results. This article only sketches the technical steps in the exploration. The python code is presented in the <a href="https://github.com/ceesroele/disinformation/blob/main/disinformation.ipynb">accompanying notebook at github</a>.</p><p>The original body of data comes from the <a href="https://euvsdisinfo.eu/">euvsdisinfo.eu</a> website. It consists of downloaded <a href="https://euvsdisinfo.eu/news/">news &amp; analysis articles</a> and <a href="https://euvsdisinfo.eu/disinformation-cases/">disinformation cases</a>. The news set contains over nine hundred items, the cases set over thirteen thousand items. To focus on “disinformation”, this body of data is reduced to 13,190 sentences containing the word “disinformation” in news articles and in the disproofs of disinformation cases.</p><p>Some examples of sentences in our dataset:</p><blockquote>- The latest disinformation from that show we have in our database was about the West pushing Poroshenko to power again and him using a military clash with Russia to postpone the election.</blockquote><blockquote>- The world of disinformation indeed is a dark and alienating one.</blockquote><blockquote>- This message is consistent with recurring pro-Kremlin disinformation narratives about the moral decay of the West and the propaganda of the morally corrupt West, aiming to encourage Russophobia.</blockquote><blockquote>- Most pro-Kremlin disinformation focusses on promoting the safety and efficacy of the Sputnik V vaccine while disparaging the safety of Western vaccines, in articles particular against the Pfizer/BioNTech vaccine.</blockquote><blockquote>- In other words, disinformation has claimed total dominance in the Kremlin’s current communications strategy, whereas even Soviet authorities were capable of seeing a long-term reason for not systematically lying.</blockquote><p>Drawback of the dataset is that it comes from a single source. On the positive side, given that this represents the European Union’s primary output for the lengthy period of six years, we can assume that this is at least how the European Union uses and wishes to use the term “disinformation”.</p><h3>Wordcloud</h3><p>A Wordcloud is a visual presentation of the prevalence of words in a body of text. As a word occurs relatively more frequently it will be presented larger. Let’s see what a Wordcloud of our dataset looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhxDtJBHPoT9cXRxHz50jw.png" /><figcaption>Wordcloud visualising the prevalence of words in the dataset</figcaption></figure><p>Obviously, the word “disinformation” is most prevalent, after all, our dataset consists of sentences that all contain it. Other prominent words are “pro-Kremlin”, “recur” (the lemma of “recurring”), “narrative”, “Russia”, and “Ukraine”.</p><p>As you see, the domain is relatively limited. Given the name “EU vs Disinformation” one might be misled about the scope of this website. It is published by the European Union’s <a href="https://eeas.europa.eu/headquarters/headquarters-homepage/2116/-questions-and-answers-about-the-east-"><em>East StratCom Task Force</em></a> and is in practice and according to its mission statement exclusively focused on “revealing pro-Kremlin disinformation”. StratCom stands for Strategic Communication.</p><p>Note that the limitation of the domain is not an issue for the present exploration: our question is not “what disinformation is out there?” but “how is the word ‘disinformation’ used in practice?” For the latter question, this extensive dataset is still suitable.</p><h3>TF-IDF</h3><p><a href="https://monkeylearn.com/blog/what-is-tf-idf/">Term Frequency / Inverse Document Frequency</a> is a metric for the prevalence of terms in a document in the context of other documents. If a term occurs in a document that raises the term frequency. But if it also occurs in many other documents, it is less exceptional and the score is diminished. Reversed: if a term occurs in one document but not in others, its score for that one document is raised.</p><p>We use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">TfidfVectorizer</a> from sklearn to create a TF-IDF score for our dataset. We treat our dataset as a single document, so for now the “Inverse Document Frequency”, a calculation over the entire set of documents, is not used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lfw5hwNJIIc-AeU_h4SzQ.png" /><figcaption>TF-IDF score for dataset</figcaption></figure><p>We get basically the same information as in the Wordcloud, but now displayed with clear ranking and scale.</p><h3>Ngrams / noun chunks</h3><p>So far, we looked only at individual words. But in the Wordcloud we saw both “chemical” and “attack”, we saw “Alexei” and “Navalny”. Let’s look at combinations of words. We can look at strict combinations like bigrams and trigrams, respectively combinations of two words (like “chemical attack”) or three words (“Joint Investigation Team”). Here we used not such trigrams but the <a href="https://spacy.io/usage/linguistic-features#noun-chunks">“noun chunks”</a> from the <a href="https://spacy.io/">spaCy</a> tokeniser. These are basically nouns with a variable number of words describing the noun, e.g. “the lavish green grass”. Tokenising not into words, but into noun chunks of at least two words, we get the following Wordcloud for our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUgBKgeLvjMlAxw0uoNp6w.png" /><figcaption>Prevalent noun chunks in the dataset</figcaption></figure><p>Here we see many compound terms worth making visible, e.g. “George Soros”, “Alexei Navalny”, “Baltic States”, “flight MH17”, and “White Helmets”.</p><p>But the biggest presence is for “recur(ring) pro-Kremlin disinformation narrative”. What is going on here? Let’s look at the actual occurrences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iM99EWf0CDptJ_DD4Czh7g.png" /><figcaption>Number of occurrences of noun chunks</figcaption></figure><p>We see that “recur(ring) pro-Kremlin disinformation narrative” occurs over three thousand times in the dataset of of about thirteen thousand sentences. That comes down to about one in four sentences!</p><p>Additionally, we see a few other compounds:</p><ul><li>disinformation message</li><li>disinformation case</li><li>disinformation campaign</li></ul><p>Let’s look at the most frequently occurring compounds of the format “<em>disinformation </em>(term)”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4GNMjPQMV2pEaIi0Y9yCg.png" /><figcaption>Occurrences of compounds like “disinformation (term)”</figcaption></figure><p>We see that when used as a modifier, “disinformation” mostly occurs in combination with “narrative”. In a future article I will explore how “disinformation” is used where it is not coupled with “narrative”, but for now I consider pursuing narratives as the most promising tack to continue the exploration.</p><h3>Narratives</h3><p>In the above exploration we saw that “disinformation” is most often used as a modifier of “narrative”. This is an important finding because it helps us narrow down how “disinformation” is actually used.</p><p>In the EU definition of “disinformation” we don’t find the word “narrative” and neither does “narrative” occur in the leading document <a href="https://ec.europa.eu/info/sites/default/files/eu-communication-disinformation-euco-05122018_en.pdf">“EU Action Plan Against Disinformation”</a>.</p><p>Given the prevalence of the word “narrative” in the actual usage of the term “disinformation” as we found studying our dataset, this is puzzling.</p><p>Let’s look up the Oxford Languages definition of “narrative”:</p><blockquote>narrative ~ a spoken or written account of connected events; a story.</blockquote><p>Compare this with the European Union’s definition of “disinformation” which we saw above:</p><blockquote>disinformation ~ the creation, presentation and dissemination of verifiably false or misleading information for the purposes of economic gain or intentionally deceiving the public.</blockquote><p>Whereas information — and hence disinformation — can be about anything, we find that <em>in practice</em> disinformation is about <em>connected events</em>. As events are typically determined by <strong>people</strong>, <strong>locations</strong>, and <strong>actions, </strong>we have reason to focus on these concepts.</p><p>For our current exploration, this means that we have reason to narrow down our data in a different way than a purely statistical on word occurrences. Specifically, <em>named entities</em> — like people and locations — are taking a central place as they are defining for a “narrative”.</p><p>Let’s continue our exploration of “disinformation” by focusing on “narratives”. For that purpose we change our dataset: instead of taking sentences with the word “disinformation” from the original body of articles and disinformation cases, we extract sentences with the word “narrative”. Let’s compare the number of sentences in the two datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*Tt-Me0jXRT2rsYvX8pl5Zw.png" /><figcaption>Two datasets, partially overlapping: sentences with “disinformation” and those with “narrative”</figcaption></figure><p>We see that the number of sentences containing both “disinformation” and “narrative” is significantly larger than those containing only “narrative”.</p><p>Let’s look at the progress over the period that EUvsDisinfo has been publishing. The numbers for “disinformation”, “narrative” and “pro-Kremlin disinformation narrative” are occurrences in our datasets. For reference a column with the number of publications — news and disinformation cases — is added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quuv1I_0ax6IZu6ujuNrnQ.png" /><figcaption>Occurrences over time during 2016–2021. Also with number of publications.</figcaption></figure><p>With regard to relative occurrences over time, we see:</p><ul><li>the relative use of the term “narrative” has greatly increased since 2019</li><li>the phrase “pro-Kremlin disinformation narrative” has become increasingly prevalent among all uses of “narrative” in the last three years</li><li>we see a peak in the the occurrences of both “disinformation” and “narrative” in 2020, then in 2021 the usage of these words becomes less frequent in the publications of EUvsDisinfo</li></ul><h3>Recurrent narratives</h3><p>We found that “recurrent disinformation narratives” is mentioned thousands of times in our dataset. We will now try to identify such recurrent narratives. The process of the identification of narratives serves to explore the structure of narratives, which might give us clues about the nature of “disinformation”.</p><p>Our steps:</p><ol><li>Extended tokenisation: not just splitting sentences in individual words, but taking compounds into account.</li><li>TF-IDF scores for sentences in the dataset</li><li><em>K-means</em> clustering analysis: <em>“elbow method”</em> to determine optimal amount of clusters.</li><li>Actual <em>K-means</em> clustering for optimal number of clusters</li><li>Analysing resulting clusters</li></ol><h3>Extended tokenisation</h3><p>Standard tokenisation converts a sentence, e.g. “Hello, world!”, into a list of tokens, e.g. [‘Hello’, ‘,’, ‘world’, ‘!’].</p><p>In our exploration above, we saw that we want to recognise certain compounds as a single token.</p><p>We want to:</p><ol><li>Recognise a full name as a single token, rather than as separate tokens for first name and last name.</li><li>Make sure that certain entities are recognised as entities, e.g. “Joint Investigation Team”.</li><li>Recognise a number of domain specific compounds, e.g. “conspiracy theory” and “chemical attack”. Note that these choices are based on an understanding of the domain, not on any generic and explicit criteria.</li><li>Normalise entities to a single formulation, e.g. “European Union” and “EU” both resolve to “EU”. Again, this is based on an understanding of our domain.</li><li>Normalise names to only the last name the compound tokens “George Soros” and “Soros” will refer to the same entity.</li></ol><p>Technically, we do this by a combination of customising the <em>spaCy</em> tokeniser and by post-processing the outcomes of the tokeniser in accordance with the requirements specified above.</p><h3>TF-IDF scores for sentences and k-means clustering</h3><p>Earlier we created a TF-IDF score for the entire dataset, which means that every word in the dataset gets a score. Now, we do the same per sentence. That means that now scores for terms in sentences are partly determined by the frequency of these terms in all documents.</p><p>Sentences are now transformed into a list of all tokens in the dataset with for each token a score specific for that sentence.</p><p>Once the sentences are transformed we can make an optimal division of sentences into groups based on their TF-IDF representation. We do this through the <em>k-means</em> algorithm. This algorithm starts out by setting arbitrary “centres” for clusters, finding the nearest centre for all items (sentences in our case), and then reset the centre to the means of the new found clusters. From that point, with new cluster centre, the steps are repeated.</p><p>With our set of tokens with their scores, we have a complex dataset for which k-means might <em>not</em> give a division into clusters as good as e.g. <a href="https://medium.com/towards-data-science/spectral-clustering-aba2640c0d5b"><em>spectral clustering</em></a>. The reason to opt for k-means is that it gives us not only a notion of cluster membership, but also a notion of <em>cluster centres</em>. In the present case, this comes down to listing the most salient terms of a cluster.</p><p>Before starting to divide our dataset into clusters using k-means it is necessary to define the number of clusters we seek.</p><p><strong>Elbow method</strong></p><p>One way to estimate a good number of clusters is through the <a href="https://en.wikipedia.org/wiki/Elbow_method_(clustering)">“elbow-method”</a>. Here we iterate over values <em>k</em> for the number of clusters and determine for each of them the “sum of the squared distance”, which is a metric for the total distance of items to cluster centres. Obviously, with more clusters, for a larger <em>k</em>, this total distance decreases. (Think of the extreme: if there are as many clusters as there are items, the distance will be zero as each item is a cluster of one element.)</p><p>The idea behind the <em>elbow-method</em> is that an optimum number of clusters is there where an initial steep improvement by adding more clusters, changes into a more gradual improvement.</p><p>When trying this with the “sum of squared distance” measurement for our data and with <em>k=5</em> to <em>k=40</em> clusters, we get the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*6ANHRCIU_Hn3qHekFgPQKQ.png" /><figcaption>Elbow method</figcaption></figure><p>Based on the diagram — using the helplines — we select <em>k=16</em> because this looks best as the inflection point.</p><p>Performing <em>k-means</em> clustering with <em>k=16</em> results in the following distribution of sentences over clusters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApDYYBacojdfmLSQtHJB9w.png" /></figure><p>We see that one cluster consists of almost half the dataset and the other clusters are at most about one tenth of its size. Let’s look closer at the result.</p><h3>Top terms</h3><p>We chose the <em>k-means</em> algorithm because this has a notion of the “centre” of a cluster. As we had transformed our original sentences into a matrix of TF-IDF scores for each term in the dataset, our cluster centres are not sentences, but terms. What this means is that out of the process we get not only a grouping of the sentences of our dataset, but also the terms most characteristic for each cluster.</p><p>As it is tedious to identify clusters by their id, we use the first three “top terms” of each cluster to generate a title for the cluster. You have already seen this in the diagram in the previous section.</p><p>Here are the twenty ranked “top terms” for two clusters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*5fxhY10kaFMgpJN6MnbxwQ.png" /><figcaption>Ranked “top terms” (cluster centres) for two clusters</figcaption></figure><p>Bringing in domain knowledge, both of these lists look quite coherent for each of the named clusters.</p><h3>Summarising narratives</h3><p>The natural way to present a narrative is through stringing together words to form a story.</p><p>The outcome of our clustering process consists of:</p><ul><li>a label for every sentence in the dataset indicating to what cluster it is assigned</li><li>a set of cluster centres for each cluster, the “top terms” that are the most salient terms for that cluster</li></ul><p>We will now use the labelling of the sentences of the dataset to generate a brief description of each cluster.</p><p><strong>Generating text</strong></p><p>We will generate a brief description for each narrative that we have found by generating a summary of the sentences for each cluster.</p><p>We will use <a href="https://huggingface.co/facebook/bart-large-cnn">BART-large-CNN</a>, which is a version of the autoregressive decoder BART fine-tuned for summarisation on the CNN / DailyMail dataset. This is an English-language dataset containing just over 300k unique news articles as written by journalists at CNN and the Daily Mail.</p><p>For a general introduction on generating text see Patrick von Platen’s <a href="https://huggingface.co/blog/how-to-generate">“How to generate text: using different decoding methods for a generation with Transformers”</a></p><p>When generating text with Huggingface transformers there are a couple of parameters relevant to us:</p><ul><li>max_length and min_length: these determine the size of the summary. We create a short summary as experiments showed that longer summaries led to incomprehensible results.</li><li>no_repeat_ngram_size: we saw earlier that phrases in our dataset are very repetitive (remember &quot;recurrent pro-Kremlin disinformation narrative&quot;?) We don&#39;t want our summary to be as repetitive as the dataset. We set this parameter to 2 as we don&#39;t even want bigrams to be repeated in the summary.</li><li>repetition_penalty: as above, we don&#39;t want terms consisting of single words to be repeated in our summary, so we set a high penalty on repetition.</li><li>do_sample and top_p: to be set together to let the algorithm find the next word through sampling from the words with at least a certain probability defined by <em>top_p</em>.</li><li>num_beams: number of paths to consider</li><li>num_return_sequences: number of summaries to be returned. We will use this as we will not leave the generation fully to the language model: we will evaluate the different generated outcomes to pick the best.</li></ul><p><strong>Pruning results</strong></p><p>The generated summaries tend to favour a journalistic story over just presenting the most relevant information in terms of a few sentences. An example of this is that the generated summaries often contain quotes, as in “Mr. X said …”. That might result in lively summaries of journalistic articles, but it is not suitable for our present dataset of context-free sentences.</p><p>To mitigate the bias, we generate several summaries (“return sequences”) and then select the one that has a <a href="https://www.machinelearningplus.com/nlp/cosine-similarity/"><em>cosine similarity</em></a> of its TF-IDF score closest to the sentences of the cluster as a whole.</p><p>Summarisation of <em>“EU / collapse / imminent”:</em></p><blockquote>The narrative of “imminent collapse’ is used to spread demoralisation and self-doubt among target audiences. The claim that external actors, including the EU and the US are stirring up protests in Russia’s neighbourhood is a recurring pro-Kremlin disinformation tale. This story also aims to pit EU member states against each other in an attempt to undermine European solidarity.</blockquote><p>The generated summaries are partly good and partly confusing. The latter shouldn’t surprise us as what we summarise are not stories but sentences taken out of the context of articles on the ground that they contain the word “narrative”.</p><p>We are looking for a representation of narratives. The present result of summarisation to come to such a result is promising as a proof-of-concept, but the current quality is not satisfactory.</p><h3>Word vectors, PCA, and projection onto the 2D plan</h3><p>How do our clusters relate to each other? In a vector representation of terms in a vocabulary, a term doesn’t get a number, but gets represented as a vector, that is, a series of numbers. In such vectors we might find non-referential patterns, e.g. the 21st and 37th numbers of the vector are relatively high if a person or a role is female.</p><p>What we will look for is the following: the “top terms” of a cluster are different terms, but their vector representations may be similar for the terms of that cluster compared to the vector representations of the “top terms” for other clusters.</p><p>To explore this we will do the following:</p><ol><li>Determine the word vectors for the “top terms” of each cluster</li><li>Use <a href="https://en.wikipedia.org/wiki/Principal_component_analysis">Principal Component Analysis</a> to reduce the original 300 dimensions of the vector space to 2 dimensions.</li><li>Display the 2 dimensional representation in a diagram.</li></ol><p>To display the diagram we add some extra steps:</p><ul><li>Give each cluster its own colour</li><li>Set the size of the shape representing each term based on the TF-IDF score for it.</li><li>If a term appears in several clusters, change its shape to indicate an overlap. The legend for “duplicates” shows what shape is used for how many clusters have that term among their “top terms”.</li></ul><p>Ideally, such a 2D-representation would be a diagram with a number of islands of terms. Looking at all clusters we see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Tzvd_YSzeTOkvKz7CCbjw.png" /></figure><p>We see no obvious division of clusters as mutually exclusive clouds of same-coloured dots.</p><p>For a clearer picture, let’s look at only the two clusters <em>“MH17 / downing / flight”</em> and <em>“Crimea / illegal annexation / referendum”.</em> We get the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aiMKGVCaqLzi11lBYFuk8w.png" /></figure><p>We see that entities are displayed mostly on the right in the diagram, meaning that our 2D projection moves entities belonging to a cluster far away from the other elements of a cluster. But we see no clear grouping of items using this method.</p><p>I conclude that the exploration of clusters by mapping them to the 2D plan is not helpful for understanding how clusters are constituted and related.</p><h3>Cosine similarity and cluster distance</h3><p>In the previous section we tried to compare cluster centres, that is, the “top terms” of clusters, by mapping them to a 2D plane. Now we will try to compare clusters as a whole by looking at their “distance”.</p><p>Earlier, we created TF-IDF scores for the entire dataset and later for individual sentences. Now we will do the same for clusters, resulting in a score per cluster.</p><p>On these scores we can apply a <a href="https://en.wikipedia.org/wiki/Cosine_similarity">“cosine similarity”</a>. We compare the scores of all terms in the vocabulary of the different clusters from which we get to a single metric for comparing the “distance” between clusters.</p><p>We can display the result in a heatmap. Note that cosine similarity results in principle in values between -1 and 1, but in practice most values in our matrix are close to 0. To emphasise the differences we take the log of the values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zwpkx2cD5PcZqu0y34-ipw.png" /></figure><p>In the diagram, lighter means closer. We see the lightest colour on the diagonal, meaning that clusters are closest to themselves. Darker means further removed. We see for instance that — as a cluster — <em>“Belarus / colour revolution / attempt”</em> is distant from <em>“Crimea / illegal annexation / referendum” </em>and <em>“protest / Euromaidan / coup”</em> is relatively close to <em>“Ukraine / war / civil”</em>.</p><p>Looking at similarities of one cluster with all other clusters — looking at an entire row or column — we see that the cluster <em>“MH17 / downing / flight” </em>is relatively far removed from other clusters. We also see that the largest cluster <em>“West / Ukraine / Russia”</em> is relatively close to all other clusters.</p><p>We can take the cumulative cosine similarity for any cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDtG-do-sz_4h5RVhtr_iw.png" /></figure><p>Looking just at the first three “top terms” — the ones in the title — we can understand this distribution. “Ukraine” and “Russia” appear in numerous clusters so the “West / Ukraine / Russia” cluster resembles all others. But terms like “Navalny”, “Crimea”, “chemical attack”, and “MH17” are relatively unique. That means that the latter clusters are more distinctive than the former.</p><p>We have gained some insight into the relationship between clusters, so far only identified by their generated names, but we have not gotten much nearer to understanding how “narratives” figure in all this.</p><h3>Structuring top terms</h3><p>Earlier we saw that from clustering follows a ranked list of “top terms”, that is, terms most representing the centre of the cluster. We expect that these are the terms most central to the narratives we try to construct.</p><p>The division of names and non-names we see in the scatterplot suggests using entities to categorise terms as a further step to understanding clusters.</p><p>We will use spaCy&#39;s Name-Entity Recognition (NER) to categorise tokens. There are more types of entities, but the ones we care about are relevant for narratives. Tokens not categorised as entities, we divide into nouns, verbs, and adjectives.</p><p>We will now divide the terms for each cluster in a number of categories. Between parentheses in the first four items you find how spaCy classifies the term if it is an entity. The last three items show how a term is classified according to Part-of-Sentence.</p><ul><li>Geographical (GRP)</li><li>Group (NORP)</li><li>Organisation (ORG)</li><li>Person (PERSON)</li><li>Noun (NOUN, PROPN, NUM, DATE)</li><li>Verb (VERB)</li><li>Adjective (ADJ)</li></ul><p>What we will do now is take the top terms, assign them to a category, and display these categories. Additionally:</p><ul><li>The font size of the term is determined by the TF-IDF score of the term: a term with a high score is represented large</li><li>Terms that occur in other clusters too are presented in the same colour in all clusters.</li></ul><p>A partial result is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgjCHEGv6O1ABjhPs_zr9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFS9Cgd5vjfUyoj9crXRJg.png" /><figcaption>Partial result of structured overview of clusters</figcaption></figure><p>At first sight, the above presentation does help to give a quick indication of what a cluster is about. E.g. in cluster 5 we see “Navalny”, “Skripal”, and “Litvinenko” in the PERSON category and “poisoning” in the VERB category. This gives a clear indication of a claim of a pattern of poisonings.</p><p>We find that none of our categories is the leading aspect of clustering, that is, we see that our top terms can be Geographical, Person, Noun, Verb, and even Adjective categories. This presentation gives us a quick glance at what matters most, but it doesn’t show us a pattern we might use to simplify what really matters about narratives generally.</p><h3>Where from here?</h3><p>We have engaged in an exploration of a specific dataset, consisting of a set of sentences with either the word ‘disinformation’ or ‘narrative’, extracted from a larger body of articles and disinformation cases.</p><p>Before coming to a conclusion, let’s consider what are possible follow-ups to our exploration.</p><ol><li><em>Fine-tune existing exploration</em>. <br>Examples: <br>- For the goal of clustering, get rid of generic sentences in the dataset which definitely don’t add content to any narrative, e.g. the sentence <em>“What seemed to be most effective, however, was to switch narratives according to the trending topics of discussion.”.<br>- </em>Use a better language model for summarisation, e.g. GPT-3.<br>- Clustering treats each token equally. An adjective gets the same treatment as a person. But for narratives, persons are more important than adjectives. Let the tokeniser remove words that are unlikely to be important to narratives before creating TF/IDF scores and clustering.</li><li><em>Extend exploration by enlarging the dataset</em>.<br>Examples:<br>- Our dataset was extracted from a larger body of articles which will contain more information on the narratives we are trying to describe. Mine these texts for additional data to give more content to the narratives.<br>- Go beyond the publications of the European Union and crawl news articles for other mentions of “disinformation”.</li><li><em>Redefine goals</em>.<br>In the present article we were interested only in exploring one dataset. We can redefine goals.<br>Examples:<br>- Create a classification system for — through clustering — defined narratives, e.g. to identify fragments of a text which match one of the defined narratives.<br>- Fine-tune the definition of “disinformation” based on research into the actual use of the term. E.g. an outcome of our current exploration is that “narrative” is a central concept to “disinformation”, but it is not currently part of the official definition of the term.<br>- Identify within the body of text other aspects of the EU’s definition of “disinformation”, e.g. verification, intention, and actual harm done.</li></ol><h3>Conclusion</h3><p>We looked into the usage of “disinformation” in the body of about 14,000 articles from EUvsDisinfo by first reducing these articles to a dataset of all sentences containing the term “disinformation” and then exploring that dataset with a variety of approaches.</p><p>Using Wordcloud and TF-IDF analysis we found that “disinformation” is strongly correlated with the notion of “narrative”. Additionally, we found that such narratives are typically recurrent, that is, they are repeated.</p><p>Based on this finding we created a new dataset consisting of all sentences in our original body of text containing the word “narrative” and used that dataset for further exploration.</p><p>We used <em>k-means</em> clustering to determine which narratives we can identify in our dataset.</p><p>Based on the “elbow method” we distinguished 16 different clusters. The challenge is to transform those clusters into a presentation that gives us a grip on narratives.</p><p>Summarising the sentences of each cluster using a BART-large-CNN model did result in summaries that got some of the point of each narrative, but none of them were sufficiently good to be acceptable. This is understandable given that our set of sentences per cluster are not a developing story, but individual sentences taken out of the original body of text.</p><p>“Top terms” are terms that designate centres of clusters, that is, they are relatively specific for a cluster. Projecting these top terms onto a 2D plan using vector representation of tokens and PCA didn’t lead to visually separate clusters, so for our purpose.</p><p>Using cosine similarity on TF-IDF scores per cluster and presenting the result in a heat-map showed which clusters are relatively alike and which ones are relatively dissimilar. We found that the largest cluster, containing about half the items in the dataset, is similar to all others. We see that it contains many of the terms like “Russia”, “Russian”, “Ukraine”, and “Kremlin” that we find throughout our dataset, but no very specific terms. Also we found that several clusters are defined by very specific entities, e.g. “MH17”, “Crimea”, and “Navalny”.</p><p>Our last approach to displaying clusters is based on using spaCy to assign the top terms for each cluster to named entities or part-of-sentence categories. The result gives a quick insight in what is central to each cluster and we see that the clustering agrees with narratives that a human might distinguish in the texts.</p><p>The main finding of our exploration is that studying “disinformation” through studying narratives gives promising results. Given that the set of narratives encompasses that of “disinformation narratives”, this can be seen as an encouragement to first study relevant narratives and only within that context try to pin-point where disinformation creeps in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cec6c7f05e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Super-Impatient’s Guide to Getting Started with Bort]]></title>
            <link>https://medium.com/riga-data-science-club/the-super-impatients-guide-to-getting-started-with-bort-c1aa4e862785?source=rss-41bb53ef046d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1aa4e862785</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Cees Roele]]></dc:creator>
            <pubDate>Thu, 04 Feb 2021 05:19:59 GMT</pubDate>
            <atom:updated>2021-02-04T05:19:59.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_w0Qg9eThTtBCGuA" /><figcaption>Photo by <a href="https://unsplash.com/@knurpselknie?utm_source=medium&amp;utm_medium=referral">Georg Arthur Pflueger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>“We tested Bort on 23 NLU tasks, and on 20 of them, it improved on BERT’s performance — by 31% in one case — even though it’s 16% the size and about 20 times as fast.” — Adrian de Wynter</em></blockquote><p><strong>The objective of the present article is to show how to overcome the few issues you’ll encounter when you try to get <em>Bort</em> running in the popular and convenient environment of <em>Simple Transformers</em>. This environment is built on top of Hugging Face <em>Transformers.</em></strong></p><h3>Bort</h3><p>First you create something that works well, then you optimise it.</p><p><em>Bort</em> optimises <em>BERT</em>. Note that I use the capitalisation used in the original articles on <em>Bort</em>, rather than “BORT”. For reading more on <em>Bort</em>, I suggest starting with <a href="https://www.amazon.science/blog/a-version-of-the-bert-language-model-thats-20-times-as-fast"><em>“A version of the BERT language model that’s 20 times as fast”</em></a> by Adrian de Wynter.</p><p>My personal interest is this: I want the best language model that can run on my modest 8GB GPU. <em>BERT-large</em> and <em>RoBERTa-large</em> need more memory so they don’t work. <em>Bort</em> is way smaller while promising a similar performance so I was keen on giving it a try.</p><p>The original open source <a href="https://github.com/alexa/bort">code for <em>Bort</em></a> is available on github since October 2020. Instructions on getting started are clear, but, as the author admits: <em>“Bort requires a rather unusual environment to run.”</em></p><h3>Bort in the Simple Transformers environment</h3><p>To use <a href="https://huggingface.co/transformers/master/model_doc/bort.html"><em>Bort</em> as a model</a> with my existing code I wanted to make it work within <a href="https://github.com/ThilinaRajapakse">Thilina Rajapakse’s</a> <a href="https://github.com/ThilinaRajapakse/simpletransformers"><em>Simple Transformers</em></a> environment. The hard work to make this possible has already been done by <a href="https://github.com/stefan-it">Stefan Schweter</a>. His <a href="https://github.com/huggingface/transformers/pull/9813">pull request</a> for <em>Bort</em> was committed to the master branch of Hugging Face <em>Transformers</em> on January 27th. It should be part of <em>Transformers</em> as of version 4.3.0 and available as model type “bert” and model name “amazon/bort”.</p><p>At the time of writing that version of <em>Transformers</em> has not yet been released, so let’s install it from the master branch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1650ef298875c129461176c0a1455357/href">https://medium.com/media/1650ef298875c129461176c0a1455357/href</a></iframe><p>… and install <em>Simple Transformers</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c926d5f477788f221aceb53d6c56957d/href">https://medium.com/media/c926d5f477788f221aceb53d6c56957d/href</a></iframe><p>Easy. But there is one catch. Let’s consider classification. Normally, we would initialise a <em>ClassificationModel</em> in <em>Simple Transformers</em> using <em>Bort</em> like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d09dd4b0e15789b968bb72fc9f1275ef/href">https://medium.com/media/d09dd4b0e15789b968bb72fc9f1275ef/href</a></iframe><p>That gets us the model, but it doesn’t work due to not invoking the right tokenizer.</p><h3>Combining model type and tokenizer</h3><p>The Hugging Face implementation defines <em>Bort</em> as just another instance of <em>BERT</em> and suggests to use the existing <em>RoBERTa</em> tokenizer. This is elegant because no new object types have been created where they are not functionally different from existing ones.</p><p>However, this brings us into slight trouble with <em>Simple Transformers</em>. There, in the different classes defining tasks, like <em>ClassificationModel</em>, the configuration, model class, and tokenizer are defined together and identified through the model type. As the model type for <em>Bort</em> is “bert”, we will get a <em>BertTokenizer</em> for our <em>Bort</em> model, rather than the needed <em>RobertaTokenizer</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fv2AlM9TAlElSee_wo_dTw.png" /></figure><p>Fortunately, <em>Simple Transformers</em> is prepared to resolve this situation! When initialising a <em>ClassificationModel</em> we can pass the following parameters:</p><blockquote><strong>tokenizer_type:</strong> The type of tokenizer (auto, bert, xlnet, xlm, roberta, distilbert, etc.) to use. If a string is passed, Simple Transformers will try to initialize a tokenizer class from the available MODEL_CLASSES. Alternatively, a Tokenizer class (subclassed from PreTrainedTokenizer) can be passed.</blockquote><blockquote><strong>tokenizer_name:</strong> The name/path to the tokenizer. If the tokenizer_type is not specified, the model_type will be used to determine the type of the tokenizer.</blockquote><p>What does that mean for <em>Bort</em>? We can now define usage of the <em>RoBERTa </em>tokenizer with a <em>BERT</em> model type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b91b2ffae1c1abafffacb3531b52d77/href">https://medium.com/media/1b91b2ffae1c1abafffacb3531b52d77/href</a></iframe><p>This works!</p><p>But only for the <em>ClassificationModel</em>. For other models, e.g. <em>MultiLabelClassificationModel,</em> the tokenizer_type and tokenizer_name keywords are not available.</p><p>To get you started if you want to implement this yourself for other model classes - after all, you are super impatient! - below is the relevant code from <em>ClassificationModel.</em> You can port this to other model classes and then install <em>Simple Transformers</em> from your modified source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2f1aba40f298dabbca2503f04bb058c/href">https://medium.com/media/b2f1aba40f298dabbca2503f04bb058c/href</a></iframe><p>With the above I could use <em>Bort</em> with my existing code based on <em>Simple Transformers</em>. Good!</p><h3>However…</h3><blockquote><a href="https://huggingface.co/transformers/master/model_doc/bort.html">Bort</a> requires a specific fine-tuning algorithm, called <a href="https://adewynter.github.io/notes/bort_algorithms_and_applications.html#fine-tuning-with-algebraic-topology">Agora</a> , that is sadly not open-sourced yet. It would be very useful for the community, if someone tries to implement the algorithm to make Bort fine-tuning work.</blockquote><p>What does that mean in practice? It means that fine-tuning of <em>Bort</em> will currently give you results at a slightly <em>worse</em> level than <em>BERT</em>. The performance improvements that are possible with <em>Bort</em> will come only when the fine-tuning algorithm is available. I’m impatiently waiting for that!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1aa4e862785" width="1" height="1" alt=""><hr><p><a href="https://medium.com/riga-data-science-club/the-super-impatients-guide-to-getting-started-with-bort-c1aa4e862785">The Super-Impatient’s Guide to Getting Started with Bort</a> was originally published in <a href="https://medium.com/riga-data-science-club">Riga Data Science Club</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>