<?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 Lucas de Sá on Medium]]></title>
        <description><![CDATA[Stories by Lucas de Sá on Medium]]></description>
        <link>https://medium.com/@lucasdesa?source=rss-346c1948fcab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*FHK2W6Gm8fQYEO5POEwNvA.png</url>
            <title>Stories by Lucas de Sá on Medium</title>
            <link>https://medium.com/@lucasdesa?source=rss-346c1948fcab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:04:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucasdesa/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[Criando um Processo de ETL com GCP Cloud Storage e Cloud Functions]]></title>
            <link>https://medium.com/@lucasdesa/criando-um-processo-de-etl-com-gcp-cloud-storage-e-cloud-functions-dfe0eb7179d8?source=rss-346c1948fcab------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe0eb7179d8</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Lucas de Sá]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 14:03:10 GMT</pubDate>
            <atom:updated>2021-09-13T16:36:40.456Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google Cloud Functions - Um Breve Tutorial</h3><h4>Extraindo dados carregados ao Cloud Storage para o BigQuery utilizando Cloud Functions e Python</h4><blockquote>A versão em inglês deste artigo está disponível <a href="https://medium.com/@lucasdesa/google-cloud-functions-a-brief-tutorial-de07d8945b01#a32b-68828e9ad61e">aqui</a>.</blockquote><p>Há diversos cenarios em que é necessário armazenar dados para serem lidos posteriormente. Na Google Cloud Platform (GCP) pode-se guardar arquivos no <a href="https://cloud.google.com/storage/docs">Google Cloud Storage</a> (GCS), que atua como um data lake, e carregá-los no <a href="https://cloud.google.com/bigquery/docs/introduction">BigQuery</a>, uma poderosa ferramenta para construir um data warehouse, que permite armazenar vastas quantidades de dados e realizar consultas SQL sem precisar gerenciar infraestrutura. Uma maneira de levar dados guardados no GCS ao BigQuery é com o uso das Google Cloud Functions através do processo de Extração, Transformação e Carregamento (<a href="https://en.wikipedia.org/wiki/Extract,_transform,_load">ETL</a>) desrito abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*rio0VXqyfQ962zSq.png" /></figure><p>A ideia deste artigo é dar uma breve introdução as Cloud Functions, criando um Pipeline de dados na GCP em que arquivos são represados em buckets do Cloud Storage, lidos e transformados por uma Cloud Function e carregados nma tabela do BigQuery.</p><h4>Mas afinal o que são as Google Cloud Functions?</h4><p>Para entender o que são Cloud Functons primeiro precisamos ter uma ideia dos diferentes serviços de computação disponíveis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2CS6AjbQXCDXwc0u.png" /></figure><p>A imagem acima mostra um espectro desses serviços disponíveis, sendo eles: Infraestrutura Como Serviço (IaaS), Containers Como Serviço (CaaS), Plataforma Como Serviço (PaaS) e Funções Como Serviço (FaaS). Note que embora os serviços a esquerda dêem mais controle e customização em suas configurações, eles requerem um time de pessoas especializadas para manter a infraestrutura. Já os serviços a direita, embora não ofereçam tanto controle, possuem abstrações de alto nível e a manutenção é gerenciada pelo provedor do serviço.</p><p>As Cloud Functions estão no espectro a direita como FaaS. Tipicamente esses serviços executam um código escrito por um desenvolvedor como resposta a um evento pré definido, com um tempo limite de execução com manutenção e escalabilidade gerenciada pelo provedor. A arquitetura desse tipo de serviço é referida como Arquitetura Serverless, onde a precificação é dada pelo total de invocações da função e a quantidade de memória e CPU utilizadas. Esse tipo de serviço é atraente já que com pouco esforço a função está rodando sem as preocupações gerenciar um servidor.</p><p>O diagrama abaixo mostra os diferentes modelos de serviço de computação oferecidos pela GCP, abrangendo do IaaS ao FaaS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*jrgsmbywJys7mtjF.png" /></figure><p>Em sumário as Cloud Functions são Funções Como Serviço, com um ambiente de execução serverless e código executado num ambiente gerenciado, onde funções de propósito único são escritas e ativadas por eventos pré definidos emitidos por outros serviços da GCP, e o modelo de pagamento é baseado no total de invocações e recursos computacionais utilizados.</p><h4>Configurando uma Cloud Function</h4><p>A ideia desta function é instantaneamente processar um arquivo <em>json</em> no momento que ele é represado em um bucket no Cloud Storage e armazenar seu conteúdo no BigQuery.</p><p>Abaixo definimos o bucket <em>test_function </em>onde<em> </em>os arquivos serão armazenados:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*cumWjKnQUbZD-x1Xmm1lZw.png" /></figure><p>Agora definiremos a tabela no BigQuery onde os dados serão carregados. Ela se chama <em>my_table</em>, está no dataset <em>a_dataset</em> e possui os campos abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*jIgkHdkP4h7aoNv6Gf4eRw.png" /></figure><p>Para criar uma Cloud Function basta ir no dashboard das Cloud Functions no Cloud Console e selecionar <em>Create Function:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*pZkcxoFtpDvcYkeGqYPUrg.png" /></figure><p>Em seguida vamos preencher as configurações desejadas para a Function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*nUO7K7d2RBw4L4XkmVLRJg.png" /><figcaption>Opções de Configuração de uma Cloud Function</figcaption></figure><p>Primeiro é necessário inserir o nome da função e a região na qual ela será criada.</p><p>Na aba de <em>Trigger </em>há uma gama de opções de <em>Trigger Type. N</em>ós selecionaremos a opção de <em>Cloud Storage</em> e o tipo de evento como <em>Finalize/Create</em>. Por fim vamos especificar o <em>bucket</em> desejado do Cloud Storage para que a Cloud Function seja ativada pelos arquivos que são criados neste bucket.</p><p>Em <em>Runtime, Build, Connections and Security Settings</em> é possível configurar outras opções. Em <em>Advanced</em> há duas configurações obrigatórias: a quantidade de memória alocada e o tempo para que a function dê timeout.</p><p>Esses configurações vem por padrão com 256MB de memória e 60 segundos para o tempo de timeout, porém é possível alocar até 8GB de memória e 540 segundos (9 minutos) para timeout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*U8pyWm-OgL7LZccaovRVkA.png" /></figure><p>Agora com as configurações selecionadas, podemos salvá-las e prosseguir para a aba do código. Há diversas opções de linguagem e maneiras para subir o código. Iremos utilizar Python 3.7 e usar o próprio editor do google para escrever o código.</p><p>É necessário específicar qual o <em>entry point</em> da Function, ou seja, definir qual método será lido na execução do código. Também é possível especificar os pacotes Python no arquivo <em>requirements.txt</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCAhUDH-LxbfrQiwDP7dFg.png" /><figcaption>Editor de Código de uma Cloud Function</figcaption></figure><p>Segue abaixo o código escrito na função:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a34658cf49e02bcd9a45eb70ee0f6303/href">https://medium.com/media/a34658cf49e02bcd9a45eb70ee0f6303/href</a></iframe><p>É importante notar que o BigQuery aceita um formato específico de arquivos json, o <em>NDJSON</em>, que nada mais é um arquivo json onde cada linha possui um objeto diferente, como mostra o exemplo abaixo:</p><pre>{&quot;key&quot;: 1, &quot;value&quot;: &quot;my_value&quot;}</pre><pre>{&quot;key&quot;: 2, &quot;value&quot;: &quot;another value&quot;}</pre><pre>{&quot;key&quot;: 3, &quot;value&quot;: &quot;this is NDJSON&quot;}</pre><p>Com o código pronto podemos clicar em <em>Deploy</em> e ver a magia acontecer =)</p><h4>Colocando a Cloud Function em uso</h4><p>Agora podemos finalmente testar a Cloud Function! Todos os logs são referentes a function são registrados no <em>Logging</em> da GCP. Há também a aba <em>Logs </em>na página de cada Cloud Function.</p><p>Para ver a nossa Function em execução basta subir um arquivo <em>NDJSON</em> no bucket <em>test-function</em> na GCS. Os logs ficarão disponíveis logo após a execução da function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBysoElFQ6cfBzNEb9DLkA.png" /><figcaption>Logs da Function após subir o arquivo <em>my_example.json no GCS</em></figcaption></figure><p>Feito isso é possível ver os dados carregados no BigQuery ao fim da execução da Function!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*DQS9H31fBEEOGkXS301KxA.png" /></figure><h4>Considerações Finais</h4><p>As Cloud Functions são uma excelente ferramenta de ETL para jobs simples e pouco custosos devido a sua versatilidade e agilidade para fazer o deploy de um fluxo de propósito único de workloads orientados a eventos (Pub/Sub, Storage, Firestore, etc) e chamadas HTTP.</p><p>Ainda assim é importante levar em conta as limitações das Cloud Functions. O seu limite de execução de 9 minutos a torna inviavel para trabalhos custosos, limitando seus casos de uso para trabalhos mais leves como micro-batching e injestão via streaming.</p><h3>Referências</h3><blockquote><a href="https://cloud.google.com/architecture/streaming-data-from-cloud-storage-into-bigquery-using-cloud-functions"><em>Streaming Data from Cloud Storage into BigQuery using Cloud Functions</em></a><em> <br></em><a href="https://cloud.google.com/functions/docs"><em>Cloud Functions Documentation</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe0eb7179d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Cloud Functions — A Brief Tutorial]]></title>
            <link>https://medium.com/geekculture/google-cloud-functions-a-brief-tutorial-de07d8945b01?source=rss-346c1948fcab------2</link>
            <guid isPermaLink="false">https://medium.com/p/de07d8945b01</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Lucas de Sá]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 12:31:36 GMT</pubDate>
            <atom:updated>2021-09-16T17:13:55.563Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google Cloud Functions — A Brief Tutorial</h3><p>Extracting data loaded from Cloud Storage to BigQuery with Cloud Functions</p><blockquote><em>The portuguese version of this article can be read </em><a href="https://medium.com/@lucasdesa/criando-um-processo-de-etl-com-gcp-cloud-storage-e-cloud-functions-dfe0eb7179d8">here</a><em>.</em></blockquote><p>There are many instances in which we need to store data for future use. With Google Cloud Platform we can use <a href="https://cloud.google.com/storage/docs">Google Cloud Storage</a> (GCS) as a datalake to store and load data to <a href="https://cloud.google.com/bigquery/docs/introduction">BigQuery</a>, a powerful analytics database for building a data warehouse, which allows us to store vasts amounts of data and make fast SQL queries without having to manage it’s infrastructure. One way to automatically import data from GCS to BigQuery is using Cloud Functions as a middleman in the <a href="https://en.wikipedia.org/wiki/Extract,_transform,_load">ETL</a> process described below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*rio0VXqyfQ962zSq.png" /></figure><p>The idea for this article is to introduce Google Cloud Functions by building a data pipeline within GCP in which files are uploaded to a bucket in GCS and then read and processed by a Cloud Function, which will load this data to a BigQuery table.</p><h4>But what exatcly are Google Cloud Functions?</h4><p>To understand Cloud Functions first we need to know what the different computing services are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2CS6AjbQXCDXwc0u.png" /></figure><p>The image above displays the spectrum of the different available services, being: Infrastructure as a Service (IaaS), Containers as a Service (CaaS), Platform as a Service (PaaS) and Functions as a Service (FaaS). Notice that although the services on the left provide a higher level of control to it’s configurations, they require a specialized team to maintain it’s infrastructure. On the right, even though they don’t offer as much control, they have a higher level of abstraction and it’s maintenance is made by the service provider.</p><p>The Cloud Functions are on the right spectrum as a FaaS. Typically those services execute a piece of code written by a developer as a response to a pre-defined event, with a time execution limit and it’s scalability managed by the provider. The architecture of this kind of service is refered as a Serverless Architecture, where pricing is calculated by the number of times the function is called and the quantity of memory and the CPU utilized. This kind of service is atractive as with little effort the function is up and running without worrying about managing a server.</p><p>The diagram below shows the different kinds of computing servies offered by the Google Cloud Platform, encompassing IaaS to FaaS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*jrgsmbywJys7mtjF.png" /></figure><p>In summary the Google Cloud Functions are FaaS, in a serverless execution environment with the code being run in a fully managed environment, where single purpose functions are written and triggered by pre defined events emmited by other services in GCP. It’s payment model is based on total function invocations and computing resources used.</p><h4>Setting up a Cloud Function</h4><p>The idea behind this function is to instantly process a <em>json </em>file at the moment it’s stored in a Cloud Storage bucket and load it’s content to BigQuery.</p><p>Below we define the bucket <em>test_function</em> where the files will be stored</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*cumWjKnQUbZD-x1Xmm1lZw.png" /></figure><p>Now we’ll define a BigQuery table where the data will be loaded. We’ll call it <em>my_table</em> and has the following columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*jIgkHdkP4h7aoNv6Gf4eRw.png" /></figure><p>To setup a Cloud Function we have to go to the Cloud Functions dashboard and click on <em>Creat Function</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*pZkcxoFtpDvcYkeGqYPUrg.png" /></figure><p>Then we’ll fill our function configs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*nUO7K7d2RBw4L4XkmVLRJg.png" /></figure><p>Firstly we’ll need to fill the name and region for the function.</p><p>At the <em>trigger</em> section we’ll select the <em>Cloud Storage</em> option. For the event type we’ll go with <em>Finalize/Create. </em>Finally we’ll specify the <em>bucket</em> in Cloud Storage in which the function will be triggered for each file that’s created on this bucket.</p><p>In <em>Runtime, Build, Connections and Secutiry Settings </em>is possible to configure other settings. In <em>Advanced</em> there are two mandatory configurations: memory quantity and timeout limit.</p><p>The default settings for these configs is 256MB of memory and 60 seconds until timeout, but it’s possible to alocate up to 8GB of memory and 540 seconds (9 minutes) until timeout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*U8pyWm-OgL7LZccaovRVkA.png" /></figure><p>With all set we can procede to the code tab. There’s a handfull of language options and ways to set up our code. We’ll chose Python 3.7 and use Google’s own editor to write our code.</p><p>It is also necessary to specify the function’s <em>entry point</em>, that means we need to define what method will be read at the code’s execution. It is also possible to specify which Python packages will be used at the <em>requirements.txt </em>file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCAhUDH-LxbfrQiwDP7dFg.png" /><figcaption>Cloud Function Editor</figcaption></figure><p>Below is the code written for this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a34658cf49e02bcd9a45eb70ee0f6303/href">https://medium.com/media/a34658cf49e02bcd9a45eb70ee0f6303/href</a></iframe><p>It’s important to notice that BigQuery only accepts a specific json file format called <em>NDJSON</em>, which is a json file were every line has a single json object, like the example below:</p><pre>{&quot;key&quot;: 1, &quot;value&quot;: &quot;my_value&quot;}</pre><pre>{&quot;key&quot;: 2, &quot;value&quot;: &quot;another value&quot;}</pre><pre>{&quot;key&quot;: 3, &quot;value&quot;: &quot;this is NDJSON&quot;}</pre><p>With everything set we can click on <em>Deploy</em> and see the magic happen =)</p><h4>Running the Cloud Function</h4><p>Now we can finally put our function to use! All of the functions logs are registered at GCP’s <em>Logging</em> tool. There’s also a <em>Logs</em> tab for each function.</p><p>To run our function we’ll upload a <em>NDJSON</em> file to the <em>test-function</em> bucket in GCS. The function logs will be available right after it’s execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBysoElFQ6cfBzNEb9DLkA.png" /><figcaption>Function logs after uploading the <em>my_example.json file to GCS</em></figcaption></figure><p>Now we can query the data in BigQuery!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*DQS9H31fBEEOGkXS301KxA.png" /></figure><h4>Final Remarks</h4><p>The Google Cloud Funtions are a great tool for painless ETL jobs due to it’s versatility and agility for deploying single purpose event oriented functions, such as Pub/Sub and Cloud Storage, and HTTP calls.</p><p>Still it’s important to consider it’s limitations. The 9 minute execution time can make more demanding jobs unfeasible, limiting it’s use cases for less demanding workloads such as micro-batching.</p><h3>References</h3><blockquote><a href="https://cloud.google.com/architecture/streaming-data-from-cloud-storage-into-bigquery-using-cloud-functions"><em>Streaming Data from Cloud Storage into BigQuery using Cloud Functions</em></a><em> <br></em><a href="https://cloud.google.com/functions/docs"><em>Cloud Functions Documentation</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de07d8945b01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/google-cloud-functions-a-brief-tutorial-de07d8945b01">Google Cloud Functions — A Brief Tutorial</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clusterização de Textos com K-Means]]></title>
            <link>https://medium.com/bexs-io/clusteriza%C3%A7%C3%A3o-de-textos-com-k-means-46254fe31bf6?source=rss-346c1948fcab------2</link>
            <guid isPermaLink="false">https://medium.com/p/46254fe31bf6</guid>
            <dc:creator><![CDATA[Lucas de Sá]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 23:44:44 GMT</pubDate>
            <atom:updated>2026-01-29T15:53:40.493Z</atom:updated>
            <content:encoded><![CDATA[<h3>Agrupamento de Textos com K-Means</h3><h4>Agrupando hinos nacionais com aprendizado não supervisionado</h4><blockquote>A versão em inglês deste artigo está disponível <a href="https://medium.com/@lucasdesa/text-clustering-with-k-means-a039d84a941b">aqui</a>. O jupyter notebook com toda análise está acessível neste <a href="https://nbviewer.jupyter.org/github/LucasTurtle/national-anthems-clustering/blob/master/Cluster_Anthems.ipynb">link</a> e o mapa final da análise esta <a href="https://nbviewer.jupyter.org/github/LucasTurtle/national-anthems-clustering/blob/master/just_map.ipynb">aqui</a>!</blockquote><p>Uma idéia me ocorreu ouvindo <a href="https://www.nexojornal.com.br/podcast/2019/03/03/Sobre-hinos-nacionais-e-seus-significados-para-um-pa%C3%ADs">um episódio de um podcast do jornal Nexo</a>. Num momento do podcast os participantes comentam que os hinos nacionais podem ser divididos em grupos, sendo alguns hinos de caráter bélico, como o da França, outros saudando a natureza local, como o do Brasil, e assim por diante. Como ninguém hoje em dia tem tempo de classificar um monte de hinos nacionais, vamos ver como podemos fazer isso usando um algoritmo de <em>aprendizado não supervisionado</em>.</p><p>Essa análise será restringida aos continentes da Europa, América Latina e America do Norte, e as letras dos hinos estão em inglês. O código e o <a href="https://www.kaggle.com/lucasturtle/national-anthems-of-the-world">dataset</a>, montado por mim, estao disponíveis no meu <a href="https://github.com/LucasTurtle/national-anthems-clustering">github</a>.</p><h3>Introdução</h3><p>A idéia deste artigo é entender como representar um conjunto de dados textuais (neste caso os hinos nacionais) para que eles sejam usados como entrada para o algoritmo K-Means. Como estamos lidando com países é interessante visualizar seus resultados em um mapa interativo usando Folium.</p><p>O processo foi dividido nas seguintes etapas:</p><ol><li>Pré-processamento do Conjunto de Dados</li><li>Extração de Features com TF-IDF</li><li>Aplicação do K-Means e Análise dos Agrupamentos</li><li>Visualização dos Grupos em um Mapa com Folium</li></ol><h3>Pré-processamento do Conjunto de Dados</h3><p>Antes do pré-processar o conjunto de dados, é importante saber como ele está estruturado. Carregar o <em>dataset </em>e selecionar os continentes que queremos utilizar é bem simples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68a48ce7a95c6a4e8da59bd61fb8e9a6/href">https://medium.com/media/68a48ce7a95c6a4e8da59bd61fb8e9a6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*sLqqejhLz1u8lUvbyDg8nw.png" /></figure><p>É importante notar que além do hino (coluna ‘anthem’) e do país (coluna ‘country’), as colunas ‘alpha-2’ e ‘alpha-3’ representa os ISO-Codes dos diferentes países, que são códigos identificadores de cada país.</p><p>Agora é interessante saber a disposição dos hinos. Ao investigar o hino da Hungria fica claro que seu texto possui ruídos. Hinos nacionais tendem a fazer menção a termos locais que utilizam caracteres não representados em UTF-8, gerando “palavras” estranhas que precisam ser removidas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*HXQTOjKpTOKmnPtPD8vVGg.png" /></figure><p>Agora que sabemos o formato do nosso conjunto de documentos, vamos passar a chamá-lo de <em>corpus</em>. A etapa de pré-processamento se refere a série de tratamentos que devem ser feitos no corpus para que ele possa ser bem representado por um modelo estatístico antes de ser alimentado ao algoritmo de agrupamento K-Means. A rotina de pré-processamento pode ser divida em:</p><ol><li><strong><em>Tokenização</em></strong> do corpus, ou seja, quebrar o conjunto de hinos nacionais em palavras individuais.</li><li>Remoção de <strong><em>stop words</em></strong>, que são palavras comuns (<em>a</em>, <em>the</em>, <em>not</em>, etc) que não contribuem para o significado semântico do texto.</li><li>Remoção de <em>ruído</em> do texto, como palavras com caracteres especiais, palavras com simbolos não ASCII, palavras juntas de números, etc. Ou seja, tudo que não dê para ser reconhecido como uma palavra.</li><li>Aplicação de <a href="https://www.researchgate.net/figure/Stemming-process-Algorithms-of-stemming-methods-are-divided-into-three-parts-mixed_fig2_324685008"><strong><em>stemming</em></strong></a>, que reduz uma palavra para a sua raiz. Ie: [consultant, consulting, consultants] -&gt; consult</li></ol><p>Abaixo estão as funções auxiliares que removem uma lista de palavras (como stop words) do texto, aplicam stemming e removem palavras com 2 ou menos letras e 21 ou mais letras (pois a palavra comum mais longa da língua inglesa é ‘ <em>Incomprehensibilities</em>’, com 21 letras).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56a98859c83af58dacc34734953d2f82/href">https://medium.com/media/56a98859c83af58dacc34734953d2f82/href</a></iframe><p>Agora definimos a função de processamento principal, que usa expressões regulares para remoção de ruído do texto e utiliza as funções definidas acima.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0a4d1d5aac585ccd94e9861834cf973/href">https://medium.com/media/b0a4d1d5aac585ccd94e9861834cf973/href</a></iframe><p>Agora o hino nacional da Hungria fica com essa cara!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*ksUyIoQUhPYlYKSWTnK9Yg.png" /></figure><h3>Extração de Features com TF-IDF</h3><p>A fase de pré-processamento foi realizada para que esta etapa gere os melhores resultados. Aqui busca-se representar o quanto uma palavra é importante num conjunto de documentos para que estes dados estejam prontos para serem usados num algoritmo. Este processo de mapeamento de dados textuais em vetores é chamado de <em>feature extraction</em>.</p><p><em>TF</em>-<em>IDF</em>, abreviação de <em>Term Frequency-Inverse Document Frequency </em>(Frequencia de Termo-Frequencia Inversa de Documento), é uma estatística numérica que busca refletir a importância de uma palavra num corpus, onde um termo com peso alto é considerado relevante num corpus.</p><p>Este método funciona, simplificadamente, através do aumento do peso de importância de uma palavra quando ela aparece muitas vezes em um documento, e diminuindo o peso desta palavra quando ela é comum em muitos documentos.</p><p>Esta estatística é dividida em duas etapas:</p><blockquote><strong><em>.</em></strong><em> Term Frequency — TF</em></blockquote><p>A frequência de termo <em>tf(t, d)</em> mensura o quão frequentemente um termo <em>t</em> ocorre num documento <em>d,</em> dando um peso de maior a termos frequentes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*JJaIvHCv0kz0GQawzYy-SA.png" /></figure><blockquote><strong><em>.</em></strong><em> Inverse Document Frequency — IDF</em></blockquote><p>A frequência inversa de documento <em>idf(t, D)</em> mensura a importância de um termo <em>t</em> num conjunto de documentos <em>D</em>. Essa estatística tende a diminuir o peso de importância de termos frequentes porém com pouca importância e aumentar o peso de termos raros que dão bastante significado a um texto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*zigaNF7zAoODcjoTpUJx_w.png" /></figure><p>A multiplicação de <em>tf(t, d)</em> por <em>idf(t, D)</em> nos gera o score <em>tf-idf</em> de um termo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*3BA6E612ZZG-Ebyod038Ag.png" /></figure><p>Apesar de toda a matemática, é bem fácil aplicar o TF-IDF usando o sklearn!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/553be1c29d04b923ab39e2d20ba63c8f/href">https://medium.com/media/553be1c29d04b923ab39e2d20ba63c8f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*bKasFPtiQQrQAixztYM5nA.png" /><figcaption>As palavras com maior peso por documento</figcaption></figure><h3>Aplicação do K-Means e Análise dos Agrupamentos</h3><p>O K-Means é um dos algoritmos de machine learning mais simples e populares que existe. Ele é considerado de <em>aprendizado não supervisionado</em> pois não precisa que os dados sejam rotulados anteriormente, no nosso caso quer dizer que nenhum texto pertence a nenhuma classe ou grupo. Ele é um algoritmo de <em>clustering </em>(agrupamento ou aglomeração) que separa um conjunto dados em um número <em>K </em>pré definido de <em>clusters </em>(grupos)<em>.</em></p><p>A idéia por trás deste algoritmo é que sua divisão de grupos seja feita por <em>K</em> <em>centróides</em>, onde um centróide é um ponto que representa o centro de um grupo. Este algoritmo funciona de forma iterativa, onde os centróides são inicialmente colocados de forma aleatória no espaço vetorial do conjunto de dados e movem-se para o centro dos pontos mais próximos deles. A cada nova iteração é recalculada a distância entre os centróides e os pontos e eles se movem novamente para o centro dos seus pontos mais próximos. O algoritmo é finalizado quando a posição ou os grupos não são mais alterados ou quando a distância da mudança dos centróides atinge um limiar pré definido.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xb3PiHBi4-O1hmyl9SuHvA.gif" /><figcaption>Visualização do K-Means. Imagem extraída <a href="https://douglasduhaime.com/posts/clustering-semantic-vectors.html">deste artigo</a>.</figcaption></figure><p>Como inicialmente nao sabe-se o número ideal de grupos, rodamos o K-Means com 2 até 7 grupos e selecionaremos o melhor resultado.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ae8f2e89b6c0f589c9aaff5740cf0e4/href">https://medium.com/media/6ae8f2e89b6c0f589c9aaff5740cf0e4/href</a></iframe><p>Com o resultado de diferentes agrupamentos, precisa-se agora escolher o melhor número de clusters, que é uma análise muito subjetiva. Há medidas de desempenho, como o <em>Elbow Method </em>e média <em>Silhouette, </em>que trazem insights para essa escolha. Eu recomendo <a href="https://medium.com/neuronio-br/aprendizado-n%C3%A3o-supervisionado-com-k-means-f4272dee98a0">este artigo escrito por uma coléga</a> para se aprofundar nestes métodos.</p><p>Para a escolha do melhor número de clusters analisou-se os distintos clusters em cada agrupamento através de gráficos de palavras mais dominantes em cada grupo. Concluiu-se que os grupos que mais faziam sentido entre si foi quando eles foram separados em 5 grupos.</p><pre>best_result = 5<br>kmeans = kmeans_results.get(best_result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSB9dgLy-2ROHl1qfkSX6g.png" /><figcaption>Palavras mais dominantes por cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMci11RxzXhvnSVGclprOg.png" /><figcaption>Word Clouds dos agrupamentos</figcaption></figure><p>Ao examinar os clusters, fica claro o tema que as palavras inferem em cada grupo. No Cluster 0, por exemplo, há um carater mais positivo nas palavras “heart”, “beauti” e “mother” (coração, belo e mãe), enquanto no Cluster 3 é mais bélico com os termos “war”, “blood”, “glori” (guerra, sangue e glória).</p><p>Agora vamos atribuir as labels resultantes do K-Means em seu respectivo país.</p><pre>labels = kmeans.labels_ <br>data[&#39;label&#39;] = labels<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*gLBaDluauKcvaQj5Hj1Pyg.png" /></figure><h3>Visualização dos Grupos em um Mapa com Folium</h3><p>A ideia agora é colorir cada país com a cor de seu respectivo grupo em um mapa, também conhecido como mapa coroplético. Isso possível com o uso da biblioteca <a href="https://github.com/python-visualization/folium"><em>Folium</em></a>.</p><p>Primeiro vamos criar uma paleta de 5 cores, uma para cada cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1f623411fb4ae095bbd54a0bd30a46e/href">https://medium.com/media/b1f623411fb4ae095bbd54a0bd30a46e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*L0_fh9ewKlyfyrTGhMvEfw.png" /></figure><p>Agora precisamos delimitar as coordenadas de cada país no mapa. <a href="https://www.kaggle.com/ktochylin/world-countries">Existe um arquivo Json</a> que identifica cada país pelo seu ISO-Code de 3 letras e possui os poligonos que traçam os limites cada país.</p><p>Dessa forma é simples fazer um merge dos labels dos países com os seus poligonos do arquivo Json pelo ISO-Code de cada país!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0375b142a574f869d742b631f0b9eac4/href">https://medium.com/media/0375b142a574f869d742b631f0b9eac4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*XfYE71InuDHbCFtzELJQHQ.png" /></figure><p>Com poligonos e as labels que delimitam os países associados no dataframe acima, o que resta agora é criar uma instância de um mapa com Folium, desenhar os poligonos e pintar países com a sua respectiva cor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c3a3b6965381cbb9c4e73619da08600/href">https://medium.com/media/6c3a3b6965381cbb9c4e73619da08600/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*006Ob43hwHEGnaGPrESNxw.png" /><figcaption>Você pode interagir com o mapa <a href="https://nbviewer.jupyter.org/github/LucasTurtle/national-anthems-clustering/blob/master/just_map.ipynb">aqui</a></figcaption></figure><p>As cores representam os seguintes clusters:</p><ul><li>Cluster 0 — Vermelho, de palavras positivas que saudam a terra natal</li><li>Cluster 1— Amarelo, de palavras que saudam a pátria e a liberdade</li><li>Cluster 2 — Verde, termos de amor a terra natal e de tom religioso</li><li>Cluster 3 — Azul, de termos que remetem a guerra</li><li>Cluster 4 — Magenta, termos que se encaixam nos outros clusters</li></ul><h3>Conclusão</h3><p>Análise de clusters de um conjunto de textos é um processo que envolve <em>Natural Languge Processing </em>(NLP) e o uso de um algoritmo de agrupamento. Este metodo de estruturar textos não estruturados pode ser aplicado em diversos segmentos, como segmentação de pesquisa, análise de feedback, etc.</p><p>Dentro do K-Means há outras variáveis que influenciam no resultado do algoritmo, como diferentes métricas de distância (distância euclidiana, manhattan, similaridade cosseno, etc), a posição inicial dos centróides, além da análise dos agrupamentos ser algo completamente subjetivo.</p><p>É importante lembrar que o K-Means não é a única maneira de agrupar dados, existem outras alternativas como algoritmos de agrupamento hierárquico.</p><h3>Referencias</h3><p>Todo o material deste artigo está disponível neste <a href="https://github.com/LucasTurtle/national-anthems-clustering">repositório do Github</a>.</p><blockquote><a href="https://jmotif.github.io/sax-vsm_site/morea/algorithm/TFIDF.html"><em>Term Frequency — Inverse Document Frequency statistics</em></a><em><br></em><a href="https://www.geeksforgeeks.org/removing-stop-words-nltk-python/"><em>Removing stop words with NLTK in Python</em></a><em><br></em><a href="https://www.geeksforgeeks.org/introduction-to-stemming/"><em>Introduction to Stemming</em></a><em><br></em><a href="https://medium.com/neuronio/unsupervised-learning-with-k-means-3eaa0666eebf"><em>Unsupervised Learning with K-Means</em></a><em><br></em><a href="https://nbviewer.jupyter.org/github/python-visualization/folium/blob/master/examples/GeoJSON_and_choropleth.ipynb"><em>GeoJSON Choropleths</em></a><em><br></em><a href="https://www.kaggle.com/ktochylin/world-countries/data"><em>World Countries Polygons Dataset</em></a><em><br></em><a href="https://www.kaggle.com/lucasturtle/national-anthems-of-the-world"><em>National Anthems of the World</em></a><em><br></em><a href="https://github.com/python-visualization/folium"><em>Folium</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46254fe31bf6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bexs-io/clusteriza%C3%A7%C3%A3o-de-textos-com-k-means-46254fe31bf6">Clusterização de Textos com K-Means</a> was originally published in <a href="https://medium.com/bexs-io">Bexs.IO</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Clustering with K-Means]]></title>
            <link>https://medium.com/@lucasdesa/text-clustering-with-k-means-a039d84a941b?source=rss-346c1948fcab------2</link>
            <guid isPermaLink="false">https://medium.com/p/a039d84a941b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Lucas de Sá]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 23:40:50 GMT</pubDate>
            <atom:updated>2026-01-29T16:00:48.786Z</atom:updated>
            <content:encoded><![CDATA[<h4>Clustering national anthems with unsupervised learning</h4><blockquote>The portuguese version of this article can be read <a href="https://medium.com/@lucasdesa/clusteriza%C3%A7%C3%A3o-de-textos-com-k-means-46254fe31bf6?sk=492881c0d99536e94891736736e4479c">here</a>. The jupyter notebook with all of the code can be found on this <a href="https://nbviewer.jupyter.org/github/LucasTurtle/national-anthems-clustering/blob/master/Cluster_Anthems.ipynb">link</a> and you can check out the final map <a href="https://nbviewer.jupyter.org/github/LucasTurtle/national-anthems-clustering/blob/master/just_map.ipynb">here</a>!</blockquote><p>An idea ocurred to me while listening to a <a href="https://www.nexojornal.com.br/podcast/2019/03/03/Sobre-hinos-nacionais-e-seus-significados-para-um-pa%C3%ADs">podcast</a>. At one moment the participants mentioned that national anthems could be divided into groups, with some having more militaristic lyrics, such a France’s, others being more patriotic complimenting it’s rich nature, such as Brazil’s, and so on and so forth. As no one’s got the time to classify a bunch of national anthems let’s see how this can be done using <em>unsupervised learning</em>.</p><p>This analysis will be restricted to Europe, Latin America and North America. The code and <a href="https://www.kaggle.com/lucasturtle/national-anthems-of-the-world">dataset</a>, which were built by me, is avaiblable on my <a href="https://github.com/LucasTurtle/national-anthems-clustering">github</a>.</p><h3>Introduction</h3><p>The idea behind this article is to understand how to represent text data (in this case national anthems) so that it can be used as input for the K-Means algorithm. Since we are dealing with countries, it will also be nice to visualize it’s results in a interactive map with Folium.</p><p>The whole process can be divided into the following stages:</p><ol><li>Pre-processing of the Dataset</li><li>Feature Extraction with TF-IDF</li><li>Running K-Means and Cluster Analysis</li><li>Clusters Visuzalisation in a Map with Folium</li></ol><h3>Pre-processing of the Dataset</h3><p>Before we pre-process the dataset, it’s important to know how it is structured:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68a48ce7a95c6a4e8da59bd61fb8e9a6/href">https://medium.com/media/68a48ce7a95c6a4e8da59bd61fb8e9a6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*sLqqejhLz1u8lUvbyDg8nw.png" /></figure><p>It’s nice to notice that the columns ‘alpha-2’ and ‘alpha-3’ represent the different countries ISO-Codes. This will be useful later.</p><p>It’s also interesting to know how the anthems look like. Looking at Hungary’s national anthem it’s clear that the dataset contains noise. Anthems generaly contain mentions to different culture’s locations and names, which many times are not represented by UTF-8 characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*HXQTOjKpTOKmnPtPD8vVGg.png" /></figure><p>From now on we’ll be refer to our dataset as a<em> corpus</em>. This pre-processing stage refers to the series of treatments that must be done to the corpus so that it can be well represented by statistic model before it’s fed to the K-Means algorithm. The pre-processing routine is divided as such:</p><ol><li><strong><em>Corpus tokenization</em></strong>, that is, divide the different texts into individual words.</li><li>S<strong><em>top words removal</em></strong>, which are common words (<em>a</em>, <em>the</em>, <em>not</em>, etc) that bring close to no contribution to the semantic meaning of a text</li><li><strong>Noise removal</strong> from the texts, that means basically anything that can’t be recongnized as a english word, such as words with non ASCII symbols, words together with numbers, etc.</li><li><a href="https://www.researchgate.net/figure/Stemming-process-Algorithms-of-stemming-methods-are-divided-into-three-parts-mixed_fig2_324685008"><strong>Stemming</strong></a>, which reduces a word to it’s root. Ie: [consultant, consulting, consultants] -&gt; consult</li></ol><p>Below are a list of auxiliary functions that remove a list of words (such as stop words) from the text, apply stemming and remove words with 2 letters or less and words 21 or more letters (the longues word in the english alphabet is ‘<em>Incomprehensibilities</em>’, with 21 letters)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56a98859c83af58dacc34734953d2f82/href">https://medium.com/media/56a98859c83af58dacc34734953d2f82/href</a></iframe><p>Now we’ll define the main processing function, that uses regular expressions for noise removal and calls the functions defined above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0a4d1d5aac585ccd94e9861834cf973/href">https://medium.com/media/b0a4d1d5aac585ccd94e9861834cf973/href</a></iframe><p>And after processing our corpus, this is what Hungary’s anthem looks like!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*ksUyIoQUhPYlYKSWTnK9Yg.png" /></figure><h3>Feature Extraction with TF-IDF</h3><p>The pre-processing phase was done so that this stage can yield the best possible results. Here we want to represent how important a word is to a set of documents so that the encoded data is ready to be used by an algorithm. This mapping process of text data into real vectors is know as feature extraction.</p><p><em>TF-IDF</em>, short for Term Frequency-Inverse Document Frequency is a numerical statistic that intends to reflect the importance of a word in a corpus, which a term with a high weight is considered relevant.</p><p>This method works by increasing the weight of a word when it appears many times in a document, and lowering it’s weight when it’s common in many documents.</p><p>This method is divided in two steps:</p><blockquote><strong><em>.</em></strong><em> Term Frequency — TF</em></blockquote><p>The term frequency <em>tf(t, d) </em>measures how frequently a term <em>t</em> occurs in a document <em>d,</em> giving a highers weight to more frequent terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*JJaIvHCv0kz0GQawzYy-SA.png" /></figure><blockquote><strong><em>.</em></strong><em> Inverse Document Frequency — IDF</em></blockquote><p>The inverse document frequency <em>idf(t, D)</em> measures the importance of a term <em>t</em> in a set of documents <em>D</em>. This statistic lowers the importance of frequent terms with low importance and increases the weight of rare terms that give more meaning to a text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*zigaNF7zAoODcjoTpUJx_w.png" /></figure><p>The product of <em>tf(t, d)</em> by <em>idf(t, D)</em> yields the <em>tf-idf</em> score for each term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*3BA6E612ZZG-Ebyod038Ag.png" /></figure><p>Even though we went through all the math above, it’s quite easy to apply TF-IDF using the sklearn library!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/553be1c29d04b923ab39e2d20ba63c8f/href">https://medium.com/media/553be1c29d04b923ab39e2d20ba63c8f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*bKasFPtiQQrQAixztYM5nA.png" /><figcaption>The words with highest weights</figcaption></figure><h3>Running K-Means and Cluster Analysis</h3><p>K-Means is one of the simplest and most popular machine learning algorithms out there. It is a <em>unsupervised algorithm</em> as it doesn’t use labelled data, in our case it means that no single text belongs to a class or group. It is algo a clustering algorithm that classifys a dataset into a <em>K</em> number of clusters.</p><p>The idea behind this algorithm is that it’s clusters will be defined by <em>K centroids</em>, where each centroid is a point that represents the center of a cluster. This algorithm works iteractively, where initially each centroid is placed randomly in the vector space of the dataset and move themselves to the center of the points which are closer to them. In each new iteration the distance between each centroid and the points are recalculated and the centroids move again to the center of the closest points. The algorithm is finished when the position or the groups don’t change anymore or when the distance in which the centroids change doesn’t surpass a pre-defined threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xb3PiHBi4-O1hmyl9SuHvA.gif" /><figcaption>Visual representation of K-Means. Image extracted from <a href="https://douglasduhaime.com/posts/clustering-semantic-vectors.html">this article</a>.</figcaption></figure><p>As we initially don’t know the ideal number of clusters, we’ll run the algorithm with 2 to 7 groups and then select the best result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ae8f2e89b6c0f589c9aaff5740cf0e4/href">https://medium.com/media/6ae8f2e89b6c0f589c9aaff5740cf0e4/href</a></iframe><p>With the results of all the different groupings we need to choose which <em>K</em> number is the best, which can be a very subjective analysis. There are some ways to measure the performance of the algorithm, like the <em>Elbow Method</em> or the <em>Silhouette Score</em>, which brings insight on how well defined the groups are. I highly recommned t<a href="https://medium.com/neuronio/unsupervised-learning-with-k-means-3eaa0666eebf?">his article written by a fellow colleague</a> to dig deeper into those methods.</p><p>To select the best number of clusters I went through all the different clusters in each grouping by looking at graphs with the most dominant words in each group. I came to the conclusion that the groups made much more sense when they were divided into 5 different clusters.</p><pre>best_result = 5<br>kmeans = kmeans_results.get(best_result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSB9dgLy-2ROHl1qfkSX6g.png" /><figcaption>Most dominant words by cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMci11RxzXhvnSVGclprOg.png" /><figcaption>Word Clouds</figcaption></figure><p>Looking at the clusters it’s clear that the words in each one of them have a theme. In Cluster 0 for example, there are more positive words like “heart”, “beauti” and “mother, while in Cluster 3 there are more conflitct related words such as “war”, “blood” and “glori”.</p><p>Now let’s group the labels from the K-Means results with each country.</p><pre>labels = kmeans.labels_ <br>data[&#39;label&#39;] = labels<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*gLBaDluauKcvaQj5Hj1Pyg.png" /></figure><h3>Clusters Visuzalisation in a Map with Folium</h3><p>The idea now is to color each country in it’s respective group in a map, also know as choropleth map. This can be done using the <a href="https://github.com/python-visualization/folium"><em>Folium</em></a><em> </em>library.</p><p>First let’s create palette of 5 colours, one for each cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1f623411fb4ae095bbd54a0bd30a46e/href">https://medium.com/media/b1f623411fb4ae095bbd54a0bd30a46e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*L0_fh9ewKlyfyrTGhMvEfw.png" /></figure><p>Now we’ll need to draw the coordinates of each country in a map. <a href="https://www.kaggle.com/ktochylin/world-countries">Here’s a Json file with the polygons of each country</a>, identified by it’s ISO-Code.</p><p>Now it’s simple to merge the labels of each country with it’s respective polygon by it’s ISO-Code!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0375b142a574f869d742b631f0b9eac4/href">https://medium.com/media/0375b142a574f869d742b631f0b9eac4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*XfYE71InuDHbCFtzELJQHQ.png" /></figure><p>With the poligons and labels now associated in the dataframe above now we can create a map instance with Folium, draw the poligons and paint the countries with the color of it’s respective label.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c3a3b6965381cbb9c4e73619da08600/href">https://medium.com/media/6c3a3b6965381cbb9c4e73619da08600/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*006Ob43hwHEGnaGPrESNxw.png" /><figcaption>You can play around with the map <a href="https://nbviewer.jupyter.org/github/LucasTurtle/national-anthems-clustering/blob/master/just_map.ipynb">here</a></figcaption></figure><p>The clusters are:</p><ul><li>Cluster 0 — Red, with words that praise the motherland of each nation</li><li>Cluster 1 — Yellow, with words that praise liberty</li><li>Cluster 2 — Green, with more religious terms</li><li>Cluster 3 — Blue, with terms that are more related to war</li><li>Cluster 4 — Magenta, with generic terms that can be part of any cluster</li></ul><h3>Conclusion</h3><p>Text clustering is a process that involves <em>Natural Language Processing </em>(NLP) and the use of a clustering algorithm. This method of finding groups in unstructured texts can be applied in many different segments, such as feedback analysis, research segmentation, etc.</p><p>In K-Means there are many variables that influence the algorithm’s result, such as different distance metrics (euclidean, manhattan, cosine similarity, etc), the centroids initial positions, and grouping analysis can be very subjective.</p><p>It’s also important to note that K-Means is not the only way of clustering data, there are other different methods, such as hierarchical clustering algorithms.</p><h3>References</h3><p>All material and code can be found in this <a href="https://github.com/LucasTurtle/national-anthems-clustering">Github repo</a>.</p><blockquote><a href="https://jmotif.github.io/sax-vsm_site/morea/algorithm/TFIDF.html"><em>Term Frequency — Inverse Document Frequency statistics</em></a><em><br></em><a href="https://www.geeksforgeeks.org/removing-stop-words-nltk-python/"><em>Removing stop words with NLTK in Python</em></a><em><br></em><a href="https://www.geeksforgeeks.org/introduction-to-stemming/"><em>Introduction to Stemming</em></a><em><br></em><a href="https://medium.com/neuronio/unsupervised-learning-with-k-means-3eaa0666eebf"><em>Unsupervised Learning with K-Means</em></a><em><br></em><a href="https://nbviewer.jupyter.org/github/python-visualization/folium/blob/master/examples/GeoJSON_and_choropleth.ipynb"><em>GeoJSON Choropleths</em></a><em><br></em><a href="https://www.kaggle.com/ktochylin/world-countries/data"><em>World Countries Polygons Dataset</em></a><em><br></em><a href="https://www.kaggle.com/lucasturtle/national-anthems-of-the-world"><em>National Anthems of the World</em></a><em><br></em><a href="https://github.com/python-visualization/folium"><em>Folium</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a039d84a941b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>