<?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 Matheus Rivaldo on Medium]]></title>
        <description><![CDATA[Stories by Matheus Rivaldo on Medium]]></description>
        <link>https://medium.com/@matheusrivaldo?source=rss-4aaf5cf7db0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NAoD1QYyq7qikm480U3S2A.jpeg</url>
            <title>Stories by Matheus Rivaldo on Medium</title>
            <link>https://medium.com/@matheusrivaldo?source=rss-4aaf5cf7db0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:45:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matheusrivaldo/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[Introduction to the Command Line and Data Science]]></title>
            <link>https://medium.com/@matheusrivaldo/introduction-to-the-command-line-and-data-science-4ce44858acfc?source=rss-4aaf5cf7db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce44858acfc</guid>
            <dc:creator><![CDATA[Matheus Rivaldo]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 01:43:46 GMT</pubDate>
            <atom:updated>2022-04-29T00:15:40.924Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Author: Matheus Rivaldo da Silva</blockquote><blockquote>Information technology student at <a href="https://ufrn.br/">Universidade Federal do Rio Grande do Norte</a>, 2022.</blockquote><p>Data science combines multiple fields including statistics, scientific methods, artificial intelligence and data analysis to extract value from data. Those who practice data science are called data scientists, and they combine a variety of skills to analyze data.</p><figure><img alt="Picture of a laptop using the application Speedcurve Performance Analytics" src="https://cdn-images-1.medium.com/max/1024/1*gtJeCka-IbI3z1HfoX8scg.jpeg" /></figure><p>Data scientists use many types of tools, but one of the most common are open source notebooks, which are web applications for writing and executing code, visualizing data, and seeing results, all in the same environment. Some of the most popular notebooks are Jupyter, RStudio and Zeppelin.</p><p>A Jupyter Notebook document is structured in JSON format, containing an ordered list of input/output cells that can contain code, text (using Markdown), math, graphics, and enriched text, usually with the “.ipynb” extension. Learn more about jupyter notebooks:</p><p><a href="https://medium.com/velotio-perspectives/the-ultimate-beginners-guide-to-jupyter-notebooks-6b00846ed2af">The Ultimate Beginner’s Guide to Jupyter Notebooks</a></p><p>Notebooks are very useful for conducting analyses, but they have their limitations when data scientists need to work as a team.</p><h4>The Command Line Interface</h4><p>Most computer users use the GUI (Graphical User Interface), a type of user interface that allows interaction with digital devices through graphical elements such as icons and other visual indicators, in contrast to the command line interface.</p><figure><img alt="Graphical User Interface of a computer running Windows." src="https://cdn-images-1.medium.com/max/1024/1*p6vXcoUy9zHtgN6xV2OVKQ.png" /><figcaption>Graphical User Interface of a computer running Windows.</figcaption></figure><p>Command lines are no stranger to programming professionals. Using the appropriate languages ​​for each application, or in the maintenance of hosting services, they help to create functionality and behavior in systems and software.</p><p>The visual representation of CLIs are usually those black screens full of white text that we usually see in movies when hackers are working. This text can also be presented in green, as it was immortalized by the movie The Matrix.</p><figure><img alt="Gif of a scene from the movie The Matrix where command lines are shown vertically in green color." src="https://cdn-images-1.medium.com/max/1000/1*j35XuE-6pU-IHaJePoe0Pw.gif" /><figcaption>“Remember, all I’m offering is the truth. Nothing more.”</figcaption></figure><p>Jeroen Janssens in his book Data Science at the Command Line states that:</p><blockquote>“The command line has many great advantages that can really make you a more efficient and productive data scientist. Roughly grouping the advantages, the command line is agile, augmenting, scalable, extensible, and ubiquitous.”</blockquote><p>Here are a few more reasons why learning the CLI is important:</p><ul><li>As already mentioned, it is a very common tool in data science.</li><li>It is a very popular technology that has a lot of support.</li><li>Allows you to automate repetitive tasks.</li><li>It is valued by companies.</li><li>It has extremely powerful utilities for data processing/data-oriented programming such as AWK and sed.</li><li>It is one of the best ways to use cloud services, which will come in handy when you need more computing power than you can access locally.</li></ul><figure><img alt="A screenshot of a windows operating system command prompt." src="https://cdn-images-1.medium.com/max/980/1*z3O6kXcdl0LCbHJmPdNNig.png" /><figcaption>Command Prompt (cmd) is the default command line interpreter for the Microsoft Windows.</figcaption></figure><p>The appearance of a command line may not be very friendly at first glance but fear not young padawan.</p><p>In this environment, users can type command lines for applications to perform a specific task. This is an old format, seen in the first computer systems, even before the mouseexisted. Some of the most popular shells are Bash, Z shell, KornShell, Command Prompt, and Windows PowerShell.</p><p>Since it is more common to use <a href="https://en.wikipedia.org/wiki/Unix">Unix</a>-like operating systems in data science, I will examples in a Unix shell, namely Bash. It is also possible to run Unix shells on Windows using a compatibility layer like Windows Subsystem for Linux</p><h4>Introduction to the command line</h4><figure><img alt="A screenshot from a Windows Subsystem for Linux" src="https://cdn-images-1.medium.com/max/978/1*kyFOkT_ukFGfrkfQIW6M-Q.png" /><figcaption>Windows Subsystem for Linux.</figcaption></figure><p>If you are a Windows user learn more about wsl:</p><p><a href="https://medium.com/maestral-solutions/windows-subsystem-for-linux-wsl-b2fd7eedce6d">Introducing Windows Subsystem For Linux (WSL)</a></p><p>The piece of text <strong>[text]$</strong> is called command prompt, or just prompt, and typically it will end with one of the characters $, %, # or &gt; and often includes information such as the the name of the computer, and the current working directory (or folder).</p><p>If we try to execute a invalid command we will get an error message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*aA89j4YnsUE17uO8W7UymA.png" /></figure><p>We tried to run the “command” notcommand and a message was printed to the screen saying that the command wasn’t found.</p><p>The anatomy of commands:</p><ul><li><em>command parameter1 parameter2 … parameterN</em></li><li><em>command -options arguments</em></li></ul><p>Let’s use as example the <a href="https://www.ibm.com/docs/en/aix/7.1?topic=d-diff-command"><strong>diff </strong>command</a>. This command compares the contents of files and reports the difference between them.</p><p>For the examples I created two txt files with names of some Brazilian states and I show their content below with the <a href="https://en.wikipedia.org/wiki/Cat_(Unix)">cat command</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*fqVLQAsSVETETY-rhBvasQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*pv6o2ODU4WGuftFv7d98_g.png" /></figure><p>The <strong>-y</strong> option is responsible for showing the files in two columns, indicating the differences.</p><p>Another option of this command is <strong>-q</strong> which only shows if the contents of the files are different or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*HltLEJXpRgWgDLEBu8BJ3A.png" /></figure><h4>The filesystem</h4><p>In computing, directory or folder is a structure used to organize files on a computer or a file that contains references to other files. A directory can contain references to files and other directories, which can also contain other references to files and directories.</p><p>The <a href="https://www.ibm.com/docs/en/aix/7.1?topic=p-pwd-command"><strong>pwd</strong></a><strong> </strong>(print working directory) is a command that prints the name of the local directory in a command line interface. The DOS system equivalent is the command “cd” (no arguments). pwd shows us the full path of the directory we are in at a given moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*OEFYxkYmVBHXynZke9SU9A.png" /></figure><p>An important concept to learn is the absolute or relative path. An absolute path points to the same location on a file system, regardless of the current working directory. To do this, you need to include the root directory. In contrast, a relative path tell us how to go from the current directory to the location of the the file specified by the path, avoiding the need to supply the full absolute path.</p><p>Still in doubt? Let’s see an example.</p><p>If there is a folder called “Family” inside “c/Users/Me/Photos”, if your current working directory is “Photos”and you want to change it to the “Family” folder, just put the command cd Family in the command line. Using an absolute path the command would be cd c/Users/Me/Family.</p><p>Absolute and relative path knowledge can be used in commands that use the option to navigate between directories like ls or cd.</p><p><a href="https://www.ibm.com/docs/en/ssw_aix_71/com.ibm.aix.cmds1/cd.htm"><strong>cd </strong>(change directory)</a> is a command implemented in command line interfaces of several operating systems (Unix or any Unix-like, DOS, Windows, OS/2 and AmigaOS). Its purpose is, as its name suggests, to change the current working directory to a specified one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*wDNRvZLhQEOSr0dvFqwcAg.png" /></figure><p>Examples:</p><ul><li>Change to directory /mnt/c/Users/Matheus/Documents: <strong>cd /mnt/c/Users/Matheus/Documents</strong></li><li>Change to the parent directory of the current directory: <strong>cd ..</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*RR_LvM7jPvWv_EUYXMWEdg.png" /></figure><ul><li>Change to the parent directory of the parent directory of the current directory: <strong>cd ../..</strong></li><li>Change to your home directory: <strong>cd</strong></li><li>Change your home directory: <strong>cd ~</strong></li><li>Change to the previous directory: <strong>cd -</strong></li></ul><p>The <a href="https://www.ibm.com/docs/en/aix/7.2?topic=l-ls-command"><strong>ls </strong>command</a> will list files and directories in a simple way, if no directory is specified, then ls performs its action on the current directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*SJN7Wu2bZUhmjHG0cR0nCw.png" /></figure><p>The <strong>-l</strong> ( lowercase L) option tells ls to print the non-hidden contents of the current directory in long format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*K7LDUJYfAno2ydpwQ9gw2g.png" /></figure><p>When the long listing format is used, you can see the following file information:</p><ul><li>The file type.</li><li>The file permissions.</li><li>Number of hard links to the file.</li><li>File owner.</li><li>File group.</li><li>File size.</li><li>Date and Time.</li><li>File name.</li></ul><p>The first character of the first column of the output shows the file type. Values for file types:</p><ul><li>- : Regular file.</li><li>b : Block special file.</li><li>c : Character special file.</li><li>d : Directory.</li><li>l : Symbolic link.</li><li>n : Network file.</li><li>p : FIFO.</li><li>s : Socket.</li></ul><p>The next nine characters are showing the file permissions. Learn more about file permison in linux:</p><p><a href="https://www.tutorialspoint.com/unix/unix-file-permission.htm">Unix / Linux - File Permission / Access Modes</a></p><p><strong>ls ~ </strong>command lists the contents in the users&#39;s home directory</p><p><strong>ls -a</strong> command lists all contents of the current directory, including hidden files or directories. In Linux, anything that begins with a . is considered a hidden file.</p><p><strong>ls -al</strong> command lists all contents of the current directory in long format, including hidden files or directories.</p><p><strong>ls -A</strong> command lists all contents of the current directory except for the directories .and .. .</p><p><strong>ls -Al</strong> command lists all contents of the directory in long format, except for the directories .and .. .</p><p><strong>ls ~ </strong>command lists the contents in the users’s home directory</p><p><strong>ls [directory path]</strong> command lists the contents of another directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*HVsP7T4b8DV6wle1nPEc0A.png" /></figure><h4>Modifying the Filesystem</h4><p>The<a href="https://www.ibm.com/docs/en/aix/7.2?topic=m-mkdir-command"> <strong>mkdir </strong>(make directory)</a> command is used on the Unix operating system to create new directories. It is generally used this way:</p><pre><strong>mkdir directory_name</strong></pre><p>Where directory_name is the name of the directory you want to create.</p><p>Directories are created within the current directory unless a path is specified before the name of the directory to be created.</p><p>The <a href="https://www.ibm.com/docs/en/aix/7.2?topic=r-rmdir-command"><strong>rmdir </strong>(remove directory)</a> command is used in Unix and DOS operating system to remove empty directories. The directory must be empty before it can be deleted. It is generally used this way:</p><pre><strong>rmdir directory_name</strong></pre><p>Where directory_name is the name of the directory to be removed. There are more arguments that specify other functionality, like the -p argument that removes the parent directory if it also becomes empty.</p><p>The <a href="https://www.ibm.com/docs/bg/aix/7.1?topic=files-copying-cp-command">cp command</a> is used to copy files or group of files or directory.</p><pre><strong>cp original_file copied_file</strong></pre><p>If the command contains two file names, then it copy the contents of first file to the second file. By default, cp will replace files without asking. If the destination file name already exists, its <strong>data will be destroyed</strong>. If you want to be prompted for confirmation before files are overwritten, use the -i (interactive) option.</p><pre><strong>cp original_file1 original_file2 destination_directory</strong></pre><p>If the command has one or more file names and an argument specifying directory name then this command copies each source file to the destination directory with the same name.</p><pre><strong>cp -R my_dir1 my_dir2</strong></pre><p>To copy a directory, we need to use the -R option with cp. The R stands for recursive, as it will get into the directory’s subdirectories, and into these subdirectories’ subdirectories, and so on, copying everything.</p><p>The <a href="https://www.computerhope.com/unix/urm.htm">rm command</a> is used to remove files or directories. To use it, you need to detail the folder or file that will be removed, for example:</p><pre><strong>rm file.txt</strong></pre><p>If the -R recursive option is specified and an argument is a directory, rm removes the directory and all its contents.</p><p>The <a href="https://www.ibm.com/docs/en/aix/7.2?topic=m-mv-command">mv command</a> in Linux moves or renames files and directories.</p><p>The most frequent options are:</p><ul><li>-f: Force moving files suppressing confirmation messages to overwrite.</li><li>-i: Prompt the user before moving each file.</li></ul><p>Examples:</p><p>Rename file1 to file2:</p><pre><strong>mv file1.txt file2.txt</strong></pre><p>Move file1 to the document directory:</p><pre><strong>mv file1.txt document</strong></pre><p>Moves all files and directories under document to the directory named docs, if docs exists. Otherwise, the directory document is renamed docs:</p><pre><strong>mv document docs</strong></pre><p>It is important to remember that <strong>we need to be very careful </strong>when using rm, cp, and mv as they <strong>might cause us to lose important files</strong>.</p><h4>Glob Patterns and Wildcards</h4><p>We can use wildcards to create patterns to match groups of filenames. These patterns, called glob patterns, work in a similar way to regular expressions, albeit with different rules, we can use glob patterns with most commands, making them an extremely powerful tool. Because they’re very powerful, we need to be careful with them, especially when it comes tocommands that modify the filesystem (like rm).</p><p>Wildcards:</p><ul><li>* matches any string of characters.</li></ul><p>Passing * as an argument to ls will cause it to list all non-hidden files and directories in the working directory, plus all files at the root of the listed directories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*qWh0Q2hMjC7kRYfoNc0lsQ.png" /></figure><p>For each file/directory, the shell checks to see if * matches its name. It will match every name except for the names of any hidden files.</p><p>Wildcards can also be used in conjunction with other characters to form more complex patterns. Let’s see an example. Say we want to list all the files (or directory content) with names ending in .html. This can be done by running ls *.html.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*EmaXaJb7ONO3A9ILphSJig.png" /></figure><p>Let’s see another example. Say we want to list all the files (or directory content) with names starting with b. This can be done by running ls b*.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*mmFbz0P3mNt2n6Rtgju9Nw.png" /></figure><ul><li>? matches any single character.</li></ul><p>The wildcard ? matches any character exactly one time. For example, if we use the pattern ????t, it will match any filename that is five characters long and ends with t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*ngYoW8yAckoBcEHUZqyOJg.png" /></figure><p>We have the possibility of using a character’s literal meaning (as opposed to its special meaning) by “escaping” it with a backslash (\). The command ls photo?, for example, will search for file or directories that start with photo and has one more character. The command ls photo\?will search for file or directories that match photo?. We can also use single quotes for that same purpose, what we did above could also be achieved withls&#39;photo?&#39;.</p><ul><li>[list_of_characters] matches any characters in list_of_characters.</li></ul><p>If we want to remove all files or directory content with names that start with either <em>a, i</em>, or <em>u</em>. We can do so by running rm [aiu]*. If you did ls b[a,o,u]* it will list files with the name bab, bub or bob. If we use the exclamation point with square brackets it works as a logical NOT. For example the pattern ls pho[!Tt]os will match any variation of the pattern pho!os, in which the fourth character is not t and is not T.</p><p>We can also use character classes in glob patterns:</p><p>[:alpha:]] matches any letter.</p><p>[[:digit:]] matches any number.</p><p>[[:alnum:]] matches any letter or number.</p><p>[[:lower:]] matches any lowercase letter.</p><p>[[:upper:]] matches any uppercase letter.</p><p>For example, to list all files (and the content of directories) in the working directory with names that start with three number, we can run:</p><pre><strong>ls [[:lower:]][[:lower:]][[:lower:]]*</strong></pre><p>We can use glob patterns with most commands, making them an extremely powerful tool but<strong> we need to be careful</strong> with them, especially when it comes tocommands that modify the filesystem (like <em>rm</em>).</p><h4>File Inspection</h4><p>The <a href="https://linuxize.com/post/linux-head-command/">head command</a> is used to display the initial lines of a file. Suppose you want to read only the first few lines of a file. The command displays the first 10 lines of the beginning of a file by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*nyuEAqqlqjREzRGF0WEbng.png" /></figure><p>The frequently used option is:</p><p><strong>-n</strong> : Set the number of lines head will display.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*rJ_db-zGsS79QoWcobwRbg.png" /></figure><p>Display the first 20 lines of a file named ‘List of exoplanets discovered in 2021.csv’ in the working directory.</p><p>The <a href="https://www.ibm.com/docs/en/aix/7.2?topic=t-tail-command">tail command</a> is used to print the last N numbers or tails of an input. It displays the last 10 file numbers by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*iaXQczj-rlHEkwHG6bCCeg.png" /></figure><p>The frequently used option is:</p><p><strong>-n</strong> Set the number of lines head will display.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*9ccknm-I9bf4Yn_yEHw-tg.png" /></figure><p>Display the last 20 lines of a file named ‘List of exoplanets discovered in 2021.csv’ in the working directory.</p><p>The <a href="https://www.ibm.com/docs/en/aix/7.2?topic=w-wc-command">wc command</a> displays the lines, words, and number of characters in a file, in that order. The wc command can be used to count the lines, words and characters of one or more files. If more than one file is passed as an argument, it will show the statistics for each file and the total.</p><p>The most frequent options are:</p><ul><li><strong>-c</strong>: Counts the number of characters in one or more files;</li><li><strong>-l</strong>: Count the number of lines in one or more files;</li><li><strong>-L</strong>: Counts the number of characters in the longest line in the file;</li><li><strong>-w</strong>: Counts the words of one or more files.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*CsDmwS32vfJYkdzI2Qc0_w.png" /></figure><p>The output tells us that a.txt has 4 lines, 12 words and 67 bytes.</p><h4>Using some commands to explore a csv file</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Bdu_iXLGaw3vxTK5CxH3yw.gif" /><figcaption>“The Truth Is Out There, But So Are Lies.”</figcaption></figure><p>First let’s download a csv file with some informations, the file used is <strong>brasil-municipios.csv</strong>, available in this <a href="https://raw.githubusercontent.com/programacaodinamica/analise-dados/master/dados/brasil-municipios.csv">link</a>.</p><p>First let’s navigate to the folder where the file was downloaded and check if the .csv is in the directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*vY7J2JmStDhAdLT3yYPa8w.png" /></figure><p>As we can see the file is in the folder. Let’s see some basic information of the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*tUw7IDNp-v0fkTp07q-4lg.png" /></figure><p>The output tells us that <strong>brasil-municipios.csv</strong> has 5571 lines, 10289 words and 244570 bytes.</p><p>Creating a copy of the file, see that first we check that there is only one csv file in the directory and after the copy there are two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*z1HYnPGsfCpLjnv0pImYnA.png" /></figure><p>Then, deleting the copy, see that first we check that there are two csv files in the directory and after deletion there is only the original.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*g3N0nj8u4FpzrJiNRgPrOA.png" /></figure><p>Using the head command to see the first five lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*TvAmZgqnhMx1TvCuXrY35A.png" /></figure><p>As we can see the file has six columns, respectively called ‘codigo _ibge’, ‘nome’, ‘latitude’, ‘longitude’, ‘capital’, ‘codigo_uf’.</p><p>Using the tail command to see the last five lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*3-luZ5Y-Un9Q_Ajtr0X5pQ.png" /></figure><p>A useful command is <a href="https://linuxhint.com/use-linux-column-command/">column</a>, it prints the contents by columns instead of having it be one long list. If you have content in a file where a particular delimiter separates entries, use the “<strong>-s</strong>” option with “<strong>-t</strong>.” The -t option determine the number of columns the input contains and create a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*2Hz2PPQmZKCTOIBqiMkVLg.png" /></figure><p>The values in brasil-municipios.csv are separated by commas, we used the option -s with the argument “,”.</p><p>When the file is large, it can be useful to be able to extract random lines. The <a href="https://linuxhint.com/bash_shuf_command/">shuf command</a> shows a random permutation of input lines to standard output.</p><p>Extracting five random lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*lEfhUbpyTZA_6vGg1pRftQ.png" /></figure><p>Another useful option is the <a href="https://www.ibm.com/docs/en/aix/7.2?topic=s-sort-command">sort command</a>. Used to organize the data within a file, according to the user’s need, and display this sorted data on standard output, or redirect this output to another file. It allows sorting the lines of a text file in various ways, such as alphabetically or numerically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*LaGqpMhndVvIIUa_p9wEFw.png" /></figure><p>We are sorting the sixth column numerically. <strong>-t”,”</strong> tells the shell that the fields are separated by commas. Not including this option causes the shell to use the default parameters (spaces and tabs). To sort by the sixth column, we pass in the <strong>-k</strong> (for key) option followed by 6,6. To sort the numbers numerically, we can pass in the <strong>-g</strong> option together with the <strong>-k</strong>.</p><p>One last command is grep. Grep is a command with a simple function: it looks for snippets of text (strings) inside files or directories and returns you in which files the string was found.</p><p>In the terminal you can type, for example: grep &quot;snippet to search&quot; file.txt .</p><p>That is, first the <a href="https://www.geeksforgeeks.org/grep-command-in-unixlinux/">grep command</a>, then the snippet you want to find, and finally the file where you will search. But… What if I want to search across multiple files, not just ONE specific file? Fear not, keep it simple: grep &quot;snippet to search&quot; *.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*FalE6bz76CYT_Wuktc3eAg.png" /></figure><p>So by running <strong>grep -n 2111 brasil-municipios.csv</strong>, we expect to get all the lines that do match the pattern “2111”. The option <strong>-n</strong> display the matched lines and their line numbers.</p><p>Using the <a href="https://en.wikipedia.org/wiki/Regular_expression">regex pattern</a> to see lines that end with 52:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*btdXjp_fJGIIqRCfK5f6XA.png" /></figure><p>Another options:</p><ul><li>-c : prints only a count of the lines that match a pattern</li><li>-h : display the matched lines, but do not display the filenames.</li><li>-i : ignores, case for matching</li><li>-v : prints out all the lines that do not matches the pattern</li></ul><h4>Leaving</h4><p>Exercise the content! Use the commands to practice the command line and learn others, there is no shortage of subjects to learn.</p><p>If you want to clear the command line just type<strong>clear </strong>.</p><p>That’s it for now! Now you close the command line safely. Let’s do it the hacker way!</p><pre><strong>exit</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce44858acfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construindo uma rede de menções com dados do Twitter]]></title>
            <link>https://medium.com/@matheusrivaldo/construindo-uma-rede-de-men%C3%A7%C3%B5es-com-dados-do-twitter-8c91730b8de7?source=rss-4aaf5cf7db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c91730b8de7</guid>
            <dc:creator><![CDATA[Matheus Rivaldo]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 04:47:19 GMT</pubDate>
            <atom:updated>2022-02-17T02:56:04.239Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Matheus Rivaldo da Silva</em></blockquote><p>️<a href="https://ufrn.br/">Universidade Federal do Rio Grande do Norte</a>, 2022.</p><h4>1. Introdução</h4><p>O Twitter é um serviço de microblog e rede social no qual os usuários postam e interagem com mensagens conhecidas como “tweets”. Usuários registrados podem postar, curtir e retuitar tweets, mas usuários não registrados só podem ler aqueles que estão disponíveis publicamente. O serviço é fornecido pela Twitter, Inc., uma corporação com sede em San Francisco, Califórnia. Os tweets foram originalmente restritos a 140 caracteres, mas o limite foi dobrado para 280 em novembro de 2017.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jTqKvkM1Scth0mH6egh-Q.jpeg" /></figure><p>No final de 2020, o Twitter introduziu uma nova API. A API do Twitter v2 vem com mais recursos e dados que você pode extrair e analisar, novos endpoints e muitas funcionalidades.</p><p>A API do Twitter pode ser usada para recuperar e analisar dados do Twitter de forma programática. Ao longo dos anos, a API do Twitter cresceu adicionando níveis adicionais de acesso para desenvolvedores e pesquisadores acadêmicos, para que pudessem dimensionar seu acesso para aprimorar e pesquisar a conversa pública.</p><p>Os dados do Twitter se tornam ainda mais interessantes a partir do ponto de vista de uma análise de rede. O nosso desafio é fazer uma rede de menções utilizando os nomes dos usuários e os nomes dos usuários mencionados num tweet, foi analisado tweets na língua portuguesa que usaram a hashtag <strong>#covid19</strong>. Para isso foi usado a linguagem de programação Python e pacotes para manusear os dados e gerar gráficos.</p><p>Após a criação da rede foi feito análises de métricas. E por último foi feito o deploy da rede utilizando o software Gephi.</p><p>Todo o código e dados desse trabalho podem ser encontrados neste repositório do github: <a href="https://github.com/matheusriv/network_twitter_mentions">https://github.com/matheusriv/network_twitter_mentions</a></p><h4>2. Pré-Requisitos</h4><p>Para poder enviar sua primeira solicitação à API do Twitter, você precisa ter uma conta de desenvolvedor. Se ainda não tem, pode candidatar-se <a href="https://developer.twitter.com/en/apply-for-access">aqui</a>! <em>(Não se preocupe, é gratuito e você só precisa fornecer algumas informações sobre a pesquisa que planeja realizar)</em></p><p>Tem uma conta de desenvolvedor aprovada? Fantástico!</p><p>Tudo o que você precisa fazer é criar um projeto e conectar um aplicativo através do portal do desenvolvedor e estamos prontos para começar!</p><ol><li>Acesse o painel do <a href="https://developer.twitter.com/en/portal/dashboard">portal do desenvolvedor</a></li><li>Faça login com sua conta de desenvolvedor</li><li>Crie um novo projeto, dê um nome, um caso de uso com base no objetivo que você deseja alcançar e uma descrição.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmEHu_0_cDHr9ViYHId_Xw.png" /><figcaption>Captura de tela da página do novo projeto.</figcaption></figure><p>4. Supondo que esta seja sua primeira vez, escolha ‘criar um novo app’ e dê um nome ao seu aplicativo.</p><p>Se tudo der certo, você poderá ver esta página contendo suas chaves e tokens, que usaremos para acessar a API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*nccDpluTDcaOLlpZ.png" /></figure><p>A API do Twitter v2 inclui alguns níveis de acesso para ajudá-lo a dimensionar seu uso na plataforma. O acesso essencial estará disponível imediatamente após a inscrição, e o acesso elevado pode ser solicitado com um aplicativo de caso de uso mais detalhado.</p><blockquote>Essencial: Acesso gratuito e instantâneo à API do Twitter. Inclui 500 mil Tweets/mês e um único ambiente de aplicativo. 1 aplicativo, 1 projeto.</blockquote><blockquote>Elevado: Acesso gratuito até 2 milhões de Tweets/mês e 3 ambientes de aplicativos. 3 Aplicativos, 1 Projeto. Requer um aplicativo de conta de desenvolvedor aprovado.</blockquote><p>Para evoluir para o acesso Elevated Acess é necessário preencher alguns formulários com informações do seu projeto. <a href="https://developer.twitter.com/en/portal/products/elevated">Solicite o acesso elevado</a>.</p><h4>3. O que é um grafo?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*0MC-rm9gfdzHYgbg.png" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:6n-graf.svg">Representação de um grafo.</a></figcaption></figure><p>A teoria dos grafos é o estudo dos grafos, que são estruturas matemáticas usadas para modelar relações pareadas entre objetos. Um grafo neste contexto é composto de vértices, podendo também ser chamados de nós, que são conectados por arestas, também chamadas de links. Uma distinção é feita entre grafos não direcionados, onde as arestas ligam dois vértices simetricamente, e grafos direcionados, onde as arestas ligam dois vértices assimetricamente. Se as arestas em seu grafo têm pesos, então seu grafo é considerado um grafo ponderado, se as arestas não têm pesos, o grafo é dito não ponderado. Um peso é um valor numérico anexado a cada aresta individual.</p><p>Os grafos podem ser usados ​​para modelar muitos tipos de relações e processos em sistemas físicos, biológicos, sociais e de informação. Muitos problemas práticos podem ser representados por grafos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*PwkCMN9_eOCAjK0m" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:4-tournament.svg">Grafo direcionado.</a></figcaption></figure><p>Um grafo direcionado, é um grafo em que as arestas têm uma direção. Isso geralmente é indicado com uma seta na borda; mais formalmente, se v e w são vértices, uma aresta é um par não ordenado {v,w}, enquanto uma aresta direcionada, é um par ordenado (v,w) ou (w,v).</p><h4>4. Construindo a rede</h4><p>Usando a linguagem de programação Python e pacotes necessários.</p><blockquote>Documentações: <a href="https://twython.readthedocs.io/en/latest/index.html">twython</a>, <a href="https://networkx.org/">networkx</a>, <a href="https://matplotlib.org/">matplotlib</a>, <a href="https://pandas.pydata.org/">pandas</a>.</blockquote><p>O Twitter usa OAuth para permitir que aplicativos de terceiros acessem dados em seu nome sem exigir suas credenciais de login do Twitter. Usaremos o pacote Twython para nos ajudar na autenticação e na consulta das APIs do Twitter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*KHKDdyXOlB94yjvB1-3Ovg.png" /></figure><blockquote>Partes do conteúdo deste tutorial de introdução no Twitter API e Twython, são Copyright 2020 Filippo Menczer, Santo Fortunato e Clayton A. Davis, <a href="https://github.com/CambridgeUniversityPress/FirstCourseNetworkScience">A First Course in Network Science.</a></blockquote><blockquote>Referências: introdução à API do Twitter v2 para pesquisa acadêmica <a href="https://github.com/twitterdev/getting-started-with-the-twitter-api-v2-for-academic-research">aqui</a>.</blockquote><p>Para autenticar com o Twitter, forneceremos os detalhes do aplicativo e solicitaremos um URL de autorização única para autenticar seu usuário com este aplicativo.</p><p>Copie e cole a chave e o segredo da API do seu aplicativo do Twitter em um arquivo chamado keys.txt que vai ser lido pelo código. A primeira linha é a API_KEY e a segunda linha do arquivo é a API_SECRET_KEY.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*7eqX-gsa7onEudZoQU7Csg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*QQWHIwGgh4hUCaqXQ4JACw.png" /></figure><p>A execução deve imprimir um URL clicável. Este link é único e funcionará exatamente uma vez. Visite este URL, faça login no Twitter e copie o PIN do verificador fornecido a você para colá-lo na próxima etapa.</p><p>Esse PIN verificador vai ser utilizado a seguir no código. O PIN será diferente toda vez que você executar a etapa de mostrar o URL. Os authentication_tokens incluem tokens temporários que acompanham esse PIN verificador; ao enviá-los juntos, mostramos ao Twitter que somos quem dizemos ser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*qP5corLQL4s9oFEDesfKJw.png" /></figure><p>Agora temos um par de tokens permanente que podemos usar para fazer chamadas autenticadas para a API do Twitter. Criaremos um novo objeto Twython usando essas chaves autenticadas e verificaremos as credenciais do usuário conectado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*IxukFrUu0spRt9Bi7SLBuQ.png" /></figure><p>Se a etapa anterior foi executada sem erros e imprimiu um dict correspondente a um usuário do Twitter, você está bem! O par de token autorizado é como um nome de usuário/senha e deve ser protegido como tal.</p><h4>4.1 Menções no twitter</h4><p>Uma menção entre usuários ocorre quando um usuário menciona outro em um tweet por seu @nome_de_usuario. Como exemplo, considere o seguinte <a href="http://twitter.com/PhilSzostak/status/1489424893951180800">tweet do usuário @PhilSzostak</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*wbjLXiRhf1G8PQAX0QJvsQ.png" /></figure><p>A partir deste tweet, criaríamos duas arestas:</p><p>(‘PhilSzostak’, ‘skywalkersound’)<br>(‘PhilSzostak’, ‘ILMVFX’)</p><p>Depende de nós em que direção desenhamos essas arestas, mas devemos ser consistentes. Neste exemplo, vamos desenhar arestas na direção do fluxo de atenção: <a href="http://twitter.com/PhilSzostak">@PhilSzostak</a> está dando atenção a <a href="http://twitter.com/skywalkersound">@skywalkersound</a> e <a href="http://twitter.com/ILMVFX">@ILMVFX</a>.</p><blockquote>PhilSzostak → skywalkersound</blockquote><blockquote>PhilSzostak → ILMVFX</blockquote><p><a href="https://developer.twitter.com/en/docs/twitter-api/v1/tweets/search/api-reference/get-search-tweets">A API de pesquisa do Twitter</a> permite buscar tweets recentes de acordo com uma consulta de palavras-chave, URLs, hashtags, menções de usuários etc.</p><p>Usaremos a capacidade de pesquisar por hashtags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*WaNY4Z7i2kg1Dd1udt5OYQ.png" /><figcaption>Exemplo de busca de tweets</figcaption></figure><h4>4.2 Rede com tweets que possuem uma hashtag</h4><p>A rede foi construída usando tweets em português que contêm a hashtag <strong><em>#covid19.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhQSi3V3aFlz0IAAEsxCQQ.jpeg" /></figure><p>Só podemos buscar até 100 tweets por vez de uma única chamada de API de pesquisa. E temos 180 chamadas de API a cada 15 minutos. Com isso, você pode obter até 18.000 tweets a cada 15 minutos.</p><p>Para obter mais de 100 tweets de uma única chamada de API de pesquisa, podemos usar um cursor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*XnMcSbd_O3b__v7Yqf_x9w.png" /><figcaption><a href="https://docs.python.org/3/library/itertools.html">Python itertools</a></figcaption></figure><p>Não é necessário filtrar primeiro os tweets que contenham menções de usuários devido a um <a href="https://developer.twitter.com/en/docs/twitter-api/v1/data-dictionary/object-model/tweet">recurso dos Objetos de Tweet</a>: todo tweet tem <a href="https://developer.twitter.com/en/docs/twitter-api/v1/data-dictionary/object-model/entities#entitiesobject">Entidades </a>que sempre contém uma lista de ‘menções de usuário’, mesmo que essa lista esteja vazia. Como um tweet pode mencionar mais de um usuário, precisamos de um loop for aninhado.</p><p>Usando o <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html">dataframe do pandas</a> para armazenar dados:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*Eb_dWscGNe87CsKOeDcDnQ.png" /></figure><p>Salvando dataframe num arquivo csv.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*gDnudGi9cq2mFRdvN-AXSA.png" /><figcaption><a href="https://docs.python.org/3/library/datetime.html">Python datetime</a></figcaption></figure><h4>4.3 Coletando dados por uma semana</h4><p>Com ajuda da aplicação explicada acima, foi feito coleta de dados durante uma semana.</p><p>A pasta ‘data’ possui arquivos csv com menções de usuários no twitter na hashtag <strong>#covid19</strong> nos tweets em português durante o período de uma semana. Lendo todos os arquivos csv da pasta e transformando todos em um único dataframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*GUTQDBmR2jF5YFGa6esfUg.png" /></figure><p>Criando grafo dirigido e salvando como arquivo graphml para ser usado para o deploy da rede no software Gephi. GraphML é um formato de arquivo baseado em XML para grafos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*q4LmcTH7mgWpx6wcfQuvAA.png" /></figure><h4>4.4 Explorando o grafo</h4><p><em>4.4.1 Usuários mais populares</em></p><p>Como essas arestas estão na direção do fluxo de atenção, in-degree nos dá o número de outros usuários que mencionam um determinado usuário. Podemos obter o usuário com maior grau usando a função max integrada:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*nmzWmTUGsB8ruKfj4PYT6Q.png" /></figure><p>Podemos obter mais contexto e informações dos 5 principais usuários:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*xmCUXal6Oiq58-s7XMigqw.png" /><figcaption><a href="https://docs.python.org/3/library/operator.html">Python operator</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*coy9Fr5IYVh92QElDQCj1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNd1dm-pZRV4k7o1sZZhvg.png" /><figcaption>Informações dos 5 primeiros usuários</figcaption></figure><p>Ao especificar o peso, weight=’weight’, podemos obter os 5 principais usuários por força em vez de grau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*EkHmip0NXm_qF1eWve5YHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*nzm4vS4gfsebYIXDua2_cQ.png" /><figcaption>Informações dos 5 primeiros usuários por força</figcaption></figure><p><em>4.4.2 Direcionadores de conversa</em></p><p>Um usuário que menciona muitos outros em uma conversa pode estar “conduzindo” a conversa e tentando incluir outras pessoas no diálogo. Também pode ser spam. Vamos ver quem está fazendo mais menções aqui:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*TO-CTHWhqzLF3Qx5t33BwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*jEGXHnHUU9Tbg1WcWcNHlw.png" /><figcaption>Informações dos 5 primeiros usuários que mais fazem menções</figcaption></figure><p><em>4.4.3 Conectividade</em></p><p>Podemos perguntar se os tweets obtidos pela busca representam uma grande conversa ou muitas pequenas conversas; de um modo geral, cada componente fracamente conectado representa uma conversa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*9hiEoqCmlW0UPeqFfUkF5A.png" /></figure><h4>5. Utilizando o Gephi</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z5hdw4AyGk2RtfJs.png" /></figure><p>Tela inicial do Gephi.</p><p>Gephi é um pacote de software de código aberto para visualização e análise de redes e grafos escrito em Java na plataforma NetBeans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8X4Q51v7YyEDk5ZyARYYfg.png" /></figure><p>Ao abrir o arquivo graphml ele se apresenta da forma acima, o objetivo é dar uma aparência melhor a nossa rede.</p><p>Isso é feito aplicando alguns layouts de grafos no Gephi. O primeiro utilizado foi o OpenOrd seguido do layout principal ForceAtlas 2.</p><p>Com isso, arede naturalmente se molda em alguns ‘grupos’. O Gephi implementa a classe de Modularidade no menu Estatísticas e é possível colorir os diferentes grupos com cores diferentes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*xo1RXOyDpU3rKMDExonMJw.png" /><figcaption>Menu de aparência do Gephi.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*N3QWH9rdb2jDumJd69qxNQ.png" /><figcaption>Layout ForceAtlas 2 utilizado no grafo.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_SjTMwdD8uhAhuaFyLsLA.png" /><figcaption>Rede após configurações iniciais.</figcaption></figure><p>Após isso, os nós são redimensionados com base em seu grau e um filtro é colocado para visualizar somente os rótulos dos nós que possuem graus de entrada de maior valor na rede.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*UJc52GBN_iE6WUxjWUWL_g.png" /><figcaption>Menu de aparência para tamanho dos nós proporcional ao grau de entrada.</figcaption></figure><p>Após isso exportamos o grafo em png.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oq84yTI_QElrLYsUkxqSxQ.png" /></figure><p>Os usuários em destaque são nós que possuem maior grau de entrada e representam seu destaque pois possuem mais menções nessa hashtag.</p><p>Com o Gephi também é possível visualizar e calcular algumas métricas da rede como excentricidade, grau, peso das arestas, medidas de centralidade, modularidade entre outros.Com o Gephi também é possível visualizar e calcular algumas métricas da rede como excentricidade, grau, peso das arestas, medidas de centralidade, modularidade entre outros.</p><p><a href="https://github.com/matheusriv/network_twitter_mentions/tree/main/reports%20graph">Para ver as análises do grafo entre neste link</a>.</p><h4>6. Explorando a rede</h4><p>Para explorar a rede sozinho, você pode encontrar os arquivos no <a href="https://github.com/matheusriv/network_twitter_mentions">repositório do GitHub do trabalho</a> ou <a href="https://matheusriv.github.io/network_twitter_mentions/network/">visitar este link</a>, onde está hospedado uma visualização da rede criada usando o plug-in de exportação Sigma do Gephi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c91730b8de7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construindo uma rede de coocorrência com dados do Spotify]]></title>
            <link>https://medium.com/@matheusrivaldo/construindo-uma-rede-de-coocorr%C3%AAncia-com-dados-do-spotify-101909b0fcbe?source=rss-4aaf5cf7db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/101909b0fcbe</guid>
            <dc:creator><![CDATA[Matheus Rivaldo]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 19:08:09 GMT</pubDate>
            <atom:updated>2022-01-14T19:08:09.407Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Matheus Rivaldo da Silva</blockquote><p>️<a href="https://ufrn.br/">Universidade Federal do Rio Grande do Norte</a>, 2022.</p><h4>Introdução</h4><p>Spotify é um serviço de streaming de áudio e serviços de mídia fundado em 23 de abril de 2006 por Daniel Ek e Martin Lorentzon. É o maior provedor de serviços de streaming de música do mundo, com mais de 381 milhões de usuários ativos mensais, incluindo 172 milhões de assinantes pagantes, em setembro de 2021. Está atualmente disponível em mais de 180 países.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QkB1pYpoOH1_6_W8cBNEw.jpeg" /></figure><p>O Spotify oferece podcasts e músicas gravadas com direitos autorais restritos, incluindo mais de 70 milhões de músicas, de gravadoras e empresas de mídia. Os usuários podem pesquisar músicas com base no artista, álbum ou gênero e podem criar, editar e compartilhar listas de reprodução.</p><p>Os dados do Spotify se tornam ainda mais interessantes a partir do ponto de vista de uma análise de rede. O nosso desafio é fazer uma rede de concorrência utilizando os nomes dos artistas das músicas de playlists encontradas num dataset. Para isso foi usado a linguagem de programação Python e pacotes para manusear os dados e gerar gráficos.</p><p>Após a criação da rede foi feito análises de métricas como excentricidade, Diâmetro, Periferia, Raio e Centro. E por último foi feito o deploy da rede utilizando o software Gephi.</p><p>Todo o código e dados desse trabalho podem ser encontrados neste repositório do github: <a href="https://github.com/matheusriv/network_spotify_artists">https://github.com/matheusriv/network_spotify_artists</a>.</p><h4>Estudo de caso: construindo uma rede com dados do Spotify</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekbwn2Eirwzyv6nuUB-KWA.png" /><figcaption>Source: <a href="https://www.aicrowd.com/organizers/spotify">https://www.aicrowd.com/organizers/spotify</a></figcaption></figure><p>Para a construção da rede foi utilizado o Spotify Million Playlist Dataset, que contém 1.000.000 playlists criadas por usuários na plataforma Spotify. Ele pode ser usado por pesquisadores interessados em explorar como melhorar a experiência de escuta musical. Essas listas de reprodução foram criadas durante o período de janeiro de 2010 a outubro de 2017. Cada lista de reprodução no MPD contém um título de lista de reprodução, a lista de faixas (incluindo os metadados da faixa), informações de edição (hora da última edição, número de edições da lista de reprodução) e outras informações diversas sobre a lista de reprodução.</p><p>O dataset está disponível em: <a href="https://www.aicrowd.com/challenges/spotify-million-playlist-dataset-challenge">https://www.aicrowd.com/challenges/spotify-million-playlist-dataset-challenge</a></p><h4>O que é um grafo?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*rHtOFoEhVFQrB6hvZjON_w.png" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:6n-graf.svg">Representação de um grafo</a>.</figcaption></figure><p>A teoria dos grafos é o estudo dos grafos, que são estruturas matemáticas usadas para modelar relações pareadas entre objetos. Um grafo neste contexto é composto de vértices, podendo também ser chamados de nós, que são conectados por arestas, também chamadas de links. Uma distinção é feita entre grafos não direcionados, onde as arestas ligam dois vértices simetricamente, e grafos direcionados, onde as arestas ligam dois vértices assimétricamente. Se as arestas em seu grafo têm pesos, então seu grafo é considerado um grafo ponderado, se as arestas não têm pesos, o grafo é dito não ponderado. Um peso é um valor numérico anexado a cada aresta individual.</p><p>Os grafos podem ser usados ​​para modelar muitos tipos de relações e processos em sistemas físicos, biológicos, sociais e de informação. Muitos problemas práticos podem ser representados por grafos.</p><h4>Construindo a rede</h4><p>Usando a linguagem de programação Python e pacotes necessários.</p><blockquote>Documentações: <a href="https://networkx.org/">networkx</a>, <a href="https://matplotlib.org/">matplotlib</a>, <a href="https://numpy.org/">numpy</a>, <a href="https://pandas.pydata.org/">pandas</a>, <a href="https://seaborn.pydata.org/">seaborn</a> , <a href="https://www.json.org/json-en.html">json</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*iZlGA4jEow_BNSZz39xDjg.png" /></figure><p>Para a construção da rede foi utilizado o Spotify Million Playlist Dataset. O dataset possui mais de 5gb com dados, composto de 1000 arquivos json, cada um possuindo 1000 playlists.</p><p>Uma pequena amostra do dataset foi usado para a construção da rede. O arquivo json ‘mpd.slice.0–999’ possui informações de 1000 playlists numeradas de 0 a 999.</p><p>O código para leitura do arquivo json e transformar num dataframe vem do repositório: <a href="https://github.com/vaslnk/Spotify-Song-Recommendation-ML/blob/master/EDA.ipynb">github.com/vaslnk/Spotify-Song-Recommendation-ML/blob/master/EDA.ipynb</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*vMCSZwUFkBVs0RdyOFxpDA.png" /></figure><p>Com isso é feito um dataframe ‘song_playlist’ com todas as músicas das playlists do arquivo, cada playlist possui uma numeração chamada de “pid”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*U1QjOcCo7lwfzwlkBCshKg.png" /></figure><p>A rede de coocorrência é construida com os vértices representando os artistas e uma aresta é adicionada entre dois artistas quando eles se encontram na mesma lista de reprodução. No arquivo json de 1000 playlists só as 100 primeiras estão sendo processadas já que a análise das métricas feitas a seguir com o networkx estavam consumindo muito tempo computacional numa rede com tamanho grande.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*_LBCvdFWzCk-8I19uYESJQ.png" /></figure><p>Em seguida é feita uma análise dos componentes do grafo. Na teoria dos grafos, um componente de um grafo não direcionado é um subgrafo conectado que não faz parte de nenhum subgrafo conectado maior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*FCEFyOxvfBz2EpkkaprGGw.png" /></figure><p>O grafo possui quatro componentes e foi utilizado o maior subgrafo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*jYt3VZUrYtDeKj-b1Mm33Q.png" /></figure><h4>Explorando o grafo</h4><p>Algumas métricas podem ser analisadas num grafo.</p><p>Excentricidade do grafo é definida como a distância máxima de um vértice a outro vértice. A distância máxima de um vértice a todos os outros vértices é considerada como a excentricidade do vértice.</p><p>O diâmetro do grafo é a excentricidade máxima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*lPBXcKy_K2UfjZye6021hQ.png" /></figure><p>Um raio do grafo só existe se tiver o diâmetro. É o mínimo entre todas as distâncias máximas entre um vértice e todos os outros vértices é considerado como o raio do Grafo G.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*WvfS9SBRZWof0AwrGobHkw.png" /></figure><p>Centro do grafo: é composto por todos os vértices cuja excentricidade é mínima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*RK73TrBXaPkdbLa8E30GeA.png" /></figure><h4>Medidas de Centralidade</h4><p>Na teoria dos grafos e na análise de redes, os indicadores de centralidade atribuem números ou classificações aos nós dentro de um grafo correspondente à sua posição na rede.</p><p>A centralidade de grau é definida como o número de ligações (arestas) que um nó possui. Abaixo estão os 10 nós com maior centralidade de grau, sendo artistas populares mundialmente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*Z_weFINzDt-nwHWv71zGdA.png" /></figure><p>Em um grafo conectado, a centralidade de proximidade de um nó é calculada como a recíproca da soma do comprimento dos caminhos mais curtos entre o nó e todos os outros nós do grafo. Assim, quanto mais central for um nó, mais próximo ele estará de todos os outros nós.</p><p>Abaixo estão os 10 artistas com maior centralidade de proximidade no grafo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*RlNTQ0YMceciAHeWncvFtw.png" /></figure><p>A centralidade de intermediação é uma maneira de detectar a quantidade de influência que um nó tem sobre o fluxo de informações em um grafo. É frequentemente usado para encontrar nós que servem como uma ponte de uma parte de um grafo para outra.</p><p>O algoritmo calcula os caminhos mais curtos não ponderados entre todos os pares de nós em um grafo. Cada nó recebe uma pontuação, com base no número de caminhos mais curtos que passam pelo nó. Os nós que se encontram com mais frequência nos caminhos mais curtos entre outros nós terão pontuações de centralidade de intermediação mais altas.</p><p>Abaixo podemos ver os 10 artistas com maior centralidade de intermediação no grafo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*PQ98bt9TWDEMEZOcSgxBkA.png" /></figure><p>Centralidade do autovetor é uma medida da influência de um nó em uma rede. Relacionamentos originados de nós de alta pontuação contribuem mais para a pontuação de um nó do que conexões de nós de baixa pontuação. Uma pontuação de autovetor alta significa que um nó está conectado a muitos nós que possuem pontuações altas.</p><p>Abaixo podemos ver os 10 artistas com maior centralidade do autovetor no grafo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*Olcy2fwkdsJlczJkN1yZNw.png" /></figure><p>Abaixo está os grafos das quatro medidas de centralidade analisadas comparadas, é possível ver uma maior mudança de valores na centralidade de proximidade e uma maior homogeneidade na centralidade de intermediação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmtcM18YMxNswX10aKj-MA.png" /></figure><h4>Análise Bivariada</h4><blockquote>Códigos de análise bivariada retirados do <a href="https://github.com/ivanovitchm/network_analysis_2021/tree/main/week_06">repositório da disciplina de Análise de Redes do professor Ivanovitch Silva</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*LLGO-5BcZ66KDi_z49Pq2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uy6OGNms-PzzEg4zf-6AA.png" /></figure><p>Uma forma interessante de identifcar propriedades de centralidade de uma rede mais complexa é através da PDF (Probability Density Function).<br>No eixo de x do gráfico tem o valor do grau dos nós, no eixo y tem a quantidade de ocorrências daquele grau. É possível observar que existe mais ou menos mais de 500 nós com grau 100. A maioria dos nós da rede possui grau 200 ou menos.<br>Nessa implementação o PDF pode ser chamado também de KDE (kernel density estimation). O eixo y do lado direito e esquerdo estão sendo usados, no direito sendo a probabilidade que é a curva em vermelho no gráfico.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*NNGB_xtKpbK_UmCXhFGKDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8t-wi0V-4CQJgWl-QJ2gw.png" /></figure><p>Neste outro gráfico é possível observar que aproximadamente 90% dos nós da rede tem 200 de valor de grau ou menos.</p><h4>Análise de Decomposição da Rede</h4><p>O método core_number do networkx retorna o número do núcleo para cada vértice. Um k-core é um subgrafo máximo que contém nós de grau k ou mais. O número do núcleo de um nó é o maior valor k de um k-core que contém esse nó.</p><p>O k-core 2, por exemplo, é um subgrafo da rede onde cada nó tem pelo menos 10 vizinhos. O k-core máximo dessa rede foi 105, onde cada nó nesse subgrafo tem pelo menos 105 vizinhos, esses nós são o núcleo da rede pois é o último k-core.</p><p>Alguns nós do núcleo da rede:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*opkAWrTlO_UJRwfw1XkOcQ.png" /></figure><blockquote>Código para visualização de núcleo da rede retirado do <a href="https://github.com/ivanovitchm/network_analysis_2021/tree/main/week_06">repositório da disciplina de Análise de Redes do professor Ivanovitch Silva</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Ho8foScF7m-B9z0mzdDHGw.png" /></figure><p>Colorindo o núcleo da rede de vermelho (105-core) e a “casca” do núcleo de azul (97-shell), k-core anterior ao núcleo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjXa9scartRQaE96gL6CVg.png" /></figure><p>E, por fim geramos um arquivo graphml para ser usado para o deploy da rede no software Gephi. GraphML é um formato de arquivo baseado em XML para grafos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*ltnCWh0H0Xg-foCaGD2mTQ.png" /></figure><h4>Utilizando o Gephi</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFCnBPcXniFX68Tdu6hilQ.png" /><figcaption>Tela inicial do Gephi.</figcaption></figure><p>Gephi é um pacote de software de código aberto para visualização e análise de redes e grafos escrito em Java na plataforma NetBeans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5Vxsj3Kj2dnPJgh1Ja8Wg.png" /></figure><p>Ao abrir o arquivo graphml ele se apresenta da forma acima, o objetivo é dar uma aparência melhor a nossa rede.</p><p>Isso é feito aplicando alguns layouts de grafos no Gephi. O primeiro utilizado foi o OpenOrd seguido do layout principal ForceAtlas 2.</p><p>Com isso, arede naturalmente se molda em alguns ‘grupos’. O Gephi implementa a classe de Modularidade no menu Estatísticas e é possível colorir os diferentes grupos com cores diferentes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*N1S4xtslw5J8ZCyrVFKaQQ.png" /><figcaption>Menu de aparência do Gephi.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*uifS9L89jIdcPCDrNkqv8Q.png" /><figcaption>Layout ForceAtlas 2 utilizado no grafo.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*JNmLEPE0saj3OC3JFhTC9A.png" /><figcaption>Rede após configurações iniciais.</figcaption></figure><p>Após isso, os nós são redimensionados com base em seu grau e um filtro é colocado para visualizar somente os rótulos dos nós que possuem graus de maior valor na rede.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*PWsrUc6X10-3YvL-VlwUDg.png" /><figcaption>Menu de aparência para tamanho dos nós proporcional ao grau.</figcaption></figure><p>Após isso exportamos o grafo em png.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54TMkmdWyv2x7yV28JwXTw.png" /></figure><p>Pode-se notar que alguns grupos de nós se conectam densamente. Os artistas em destaque são nós que possuem mais conexão e representam seu destaque e sucesso no mercado musical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtoIg8pwPm4itQJudzOp3A.png" /><figcaption>Estatíticas dos nós da rede.</figcaption></figure><p>Com o Gephi também é possível visualizar e calcular algumas métricas da rede como excentricidade, grau, peso das arestas, medidas de centralidade, modularidade entre outros.</p><h4>Explorando a rede</h4><p>Para explorar a rede sozinho, você pode encontrar os arquivos no <a href="https://github.com/matheusriv/network_spotify_artists">repositório do GitHub</a> do trabalho ou visitar este <a href="https://matheusriv.github.io/network_spotify_artists/network/">link</a>, onde está hospedado uma visualização da rede criada usando o plug-in de exportação Sigma do Gephi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=101909b0fcbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>