<?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 Felipe Bras on Medium]]></title>
        <description><![CDATA[Stories by Felipe Bras on Medium]]></description>
        <link>https://medium.com/@felipebras?source=rss-4bfcf726664d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-FlUU3clJ4O1H4pwnjcZ7g.jpeg</url>
            <title>Stories by Felipe Bras on Medium</title>
            <link>https://medium.com/@felipebras?source=rss-4bfcf726664d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:38:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@felipebras/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[Brazilian 2022 Elections: Networks and Biases]]></title>
            <link>https://medium.com/@felipebras/brazilian-2022-elections-networks-and-biases-c1658adb9765?source=rss-4bfcf726664d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1658adb9765</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Felipe Bras]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 17:00:19 GMT</pubDate>
            <atom:updated>2022-08-31T17:56:41.386Z</atom:updated>
            <content:encoded><![CDATA[<p>On my <a href="https://medium.com/@felipebras/brazilian-2022-elections-analysis-avoiding-controversies-sort-of-15bbe8edabcb">previous publication</a> inspired by the 2022 Brazilian Elections, I analyzed how my Representative spends the office budget quota and how it compares to the average Deputy in the current Legislature. Now I use some basic graph theory and a few network centrality measures to better understand how the Lower House is composed and changed in the last four years.</p><p>Going into graphs is a big step from what I’m most comfortable working with. I’m not a Statistician or Computer Scientist, but I’ve been in close contact with these fields in the last few years. It is clear by now that one of the pitfalls in analyzing data is confirmation bias. But boy, how tempting it is sometimes.</p><p>I shouldn’t start by thinking “I knew it!”. But after a few years of reading the Brazilian news, finding evidences for a solidified opinion is, to say the least, interesting. I’m going to make my case for what I’ve confirmed, I mean, for what I have discovered, applying basic graphs and network theory to the political arrangement of Brazil’s intricate Chamber of Deputies and the 32 parties that make it up.</p><p>Graph and Network theory are immensely hard and I barely scratch the surface of what can be done with it. It is proportionally interesting, though. For example, plotting a simple graph of the relations of all Representatives in the current Legislature is pretty revealing (find the code on my <a href="https://github.com/felipebras/elections">GitHub</a> profile).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*CVi8uSG2jquaBwuRFwvK8A.png" /><figcaption>Graph of political parties and representatives</figcaption></figure><p>The nodes with larger radii represent the political parties and the smaller ones are the Deputies. I list my first impressions:</p><ol><li>There are 6 large parties (out of 32)</li><li>One party have very loyal members, having only one Deputy who changed parties mid-term</li><li>A handful of parties of varying sizes have had intense movement during the current Legislature (the 56th, ending this year)</li><li>Isolated political parties detain a small fraction of the 513 Seats</li><li>The network of Deputies that changed parties is scattered; there is no obvious clustering considering political spectra.</li></ol><p>The next step is improving the graph, defining labels for the parties and classifying them as left- or right-wing. Well, here I should tread lightly.</p><p>As a friend who read my previous text reminded me, I’m not a political scientist. Hence I should not meddle with the decisions of how the representatives spend their office budgets without a basic understanding of how the system actually works. On the other hand, I am citizen who is able to make some educated guesses, some quick research on each of the parties websites and, most importantly, figuring out who are the main actors of each party. It wasn’t hard to classify them from left to right afterwards. To be honest, I estimate that I’m not too far from the “reality”.</p><p>I used a five degree scale from left- to right-wing with three intermediaries to come up with the network below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*j--xk_nidPohCL6GsOJpog.png" /></figure><p>What can I confirm about my first impressions? The six major parties are the ones I suspected, so no big surprises. The labor party PT has many seats in the House, and also show the loyal affiliates that I identified. The complex network of changes involve mostly center to right-wing parties, though some Representatives are very agnostic when it comes to political spectrum. Finally, most of the isolated parties are leftists.</p><p>Quick note: some political parties shown in the graph have merged with or joined others during the current Legislature. This has two consequences: increased number of interactions (edges) and acronyms that should disappear in the next election.</p><p><em>Centrality </em>— in network theory — is a fundamental concept to understand the importance of a node. For us, nodes are Deputies and political parties. The edges represent how they are connected. There are many centrality measures and they explore the importance of a node in different perspectives. I just want to make clear that centrality here is not “how to the center” of the political spectrum a party is, but a concept that measures the relation of the nodes. I’ll be using as a reference the textbook <a href="https://www.cambridge.org/us/academic/subjects/physics/statistical-physics/first-course-network-science">A First Course in Network Science</a>.</p><p><em>Degree centrality</em> is the simplest. It counts the number of neighbors (edges) and can be measured in relative terms. In the table below we see which parties are more connected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*TMJcbSuUv3dX9M5Gm_4Z5Q.png" /><figcaption>Degree centrality: top 10 political parties with more Seats</figcaption></figure><p>Although I don’t intend to identify individual Representatives, while exploring <em>betweenness centrality, </em>I’ll have to mention three of them. <em>Betweenness </em>measures the number of times a node is part of the shortest path between other nodes. Broadly speaking It can be an estimate of <em>flow of information</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Ee6cbd105e9De5xrH_Vc5Q.png" /></figure><p>In relative terms, the parties with more betweenness are slightly different from the top contenders in degree centrality. So for the flow of information, some parties are more dependent on the individual relations of its members than others. There are also some Deputies that stand out in terms of betweeness. Look where they are in the the network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*bnjDXhmJ_APhtiAWq_mvsw.png" /></figure><p>The last measure I want to mention is <em>closeness. </em>Unsurprisingly, it hints on how “close” a node is to other nodes. It took me a while to interpret this one, but I’d translate it as how “mingled” a party or individual is to the rest of the network. I’ll show the top 5 in terms of shortest distance to other nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*Te28hOKO7d7saINqY__QVw.png" /><figcaption>How far is one node to another?</figcaption></figure><p>I want to finish this analysis with two confessions. First, I admit it was longer than what I wanted. It’s a new topic for me and opened a lot of doors. Second, some conclusions can be a bit of a stretch, they should be taken with several grains of salt. Yet, as I mentioned, it feels really comfortable to sometimes fall into the confirmation bias trap. Nevertheless, this does not precludes the power of graphs as tools to be applied more broadly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1658adb9765" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brazilian 2022 Elections: Analysis Avoiding Controversies (sort of)]]></title>
            <link>https://medium.com/@felipebras/brazilian-2022-elections-analysis-avoiding-controversies-sort-of-15bbe8edabcb?source=rss-4bfcf726664d------2</link>
            <guid isPermaLink="false">https://medium.com/p/15bbe8edabcb</guid>
            <category><![CDATA[elections]]></category>
            <category><![CDATA[brazil]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Felipe Bras]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 16:37:26 GMT</pubDate>
            <atom:updated>2022-08-24T16:37:26.229Z</atom:updated>
            <content:encoded><![CDATA[<p>The World Cup this year will be held in December, which is weird. For those who were born in Brazil like me, the World Cup comes hand in hand with a much more significant event: elections for President, State Governors, Senators, and House of Representatives. As much as I’d love to use data analysis to check the performance of our elected presidents, I want to avoid controversies (note: the first presidential election after the Military Dictatorship was held in 1989 after 21 years since the 1964 Coup d’État and an indirect election of a Civil President in 1985).</p><p>I’ve been voting since I was 16 (the vote is mandatory in Brazil at age 18, but you can vote from age 16 if you feel like it) and choosing the Executive Branch has always been fairly straightforward for me. Choosing Congress Representatives is a different story. I usually chose Senators from the Party that I supported most of my life, but the options for the Chamber of Deputies (what people in the US would call House of Representatives) always made me scratch my head. Few were the times where the candidates’ proposals were clear cut or even existed at all. Most of the time they represented, you know, something…</p><p>So every time I voted for Congress I promised that I’d do my homework for the next election, research the candidates, where they came from, what they promised to do and so on. Back in 2018 I did it! I was finally able to choose a candidate that felt right and that person was elected. Great success!</p><p>Now that is time to choose again, let’s see how my Representative performed over the last four years. Notice that I don’t intend to discuss my opinion of this Deputy’s Legislature, yet I’ll try to explore more objective information: money. Thanks to the <a href="https://www.camara.leg.br/transparencia/">Transparency Portal</a> of the Brazilian Chamber of Deputies (our Lower House of Congress) which has an <a href="https://dadosabertos.camara.leg.br/swagger/api.html">API and Bulk Files</a> available, it is possible to access details on how any given Deputy uses their Office budget. There are also <a href="https://www.camara.leg.br/cota-parlamentar/">dashboards</a> provided, but they didn’t display the info the way I wanted. Also, we’re not talking here about large projects and propositions. I’m talking about office expenses. Each Deputy has a monthly budget and how they are used, IMHO, tells a lot about the Representative.</p><p>Quick detour: one of my motivations for this project was to practice Matplotlib and Pandas. Seaborn is cool, but limited in terms of customization: I’d have to use Matplotlib anyway. All files and the Notebook are available in my <a href="https://github.com/felipebras/elections">GitHub</a> page for those who want to take a look. Sorry for the mix of Portuguese and English when naming variables. Now let’s begin!</p><p>Filtering for the Representative I chose, and after doing some preliminary EDA, the first thing I did was condense a few expense categories that <a href="https://www2.camara.leg.br/comunicacao/assessoria-de-imprensa/guia-para-jornalistas/cota-parlamentar">overlapped</a>. Originally the expenses were classified in 19 categories, but I reduced it to 13. After some grouping and handling aesthetics we got the following plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0V-8LdkXM1fYunzAPyqYng.png" /></figure><p>I expected that Air Travel would consume a fair bit of the monthly quota (R$ 37,043.53 for Deputies elected by São Paulo — more on that later). Plane tickets are very expensive in Brazil, especially beginning at the 2nd semester of 2021. All the up to 25 people in each Deputy staff use this budget to travel back and forth. What surprised me was the Consulting account. I dug a little deeper to try to discover what counts as Consulting. After checking the suppliers (you can find each invoice presented to the House accounting office) I discovered that most of the amount goes to press office and “communication and political strategy”. To keep my Representative undisclosed I won’t share the links here.</p><p>Even though I’m still baffled that political strategy is decided by third parties, I realized that it was not so bad when comparing to the average Representative as will be discussed shortly. What makes things bad is that you can find very little information about the owners of the agencies and companies on the web. Also, their social media and advertising websites look somewhat subpar.</p><p>It’s interesting to notice that over the full term (Legislature 56, from 2019 to 2022), six suppliers consumed almost 90% of all expenses with Consulting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*Pql-ZCa4gWpjxGPe7CZJMw.png" /></figure><p>To get a reference, how does the average House Deputy spend their budget? To calculate that Average Joe Representative, it’s important to highlight that the budget depends on his or her State. The reason provided is that <a href="https://www2.camara.leg.br/comunicacao/assessoria-de-imprensa/guia-para-jornalistas/cota-parlamentar">air travel costs vary depending on the State</a>. To work this out, I normalized the category Air Travel to the ratio of each Brazilian State to São Paulo’s budget so that I can compare my Representative to the House average. The plot looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtNq6cNZcpjthqXiXbNs9Q.png" /></figure><p>A few remarks:</p><ol><li>The files have been downloaded on Aug 16, 2022. The data for July and August this year is still incomplete.</li><li>It is legal for the Deputy to transfer a balance from one month to the other but there is no carry from a calendar year to the next. That means that some months can have expenses above the monthly budget.</li><li>There’s no apparent outlier in terms of expenses of the selected Representative to the average Deputy.</li><li>The House’s leaderships accumulate budgets from across functions. The budgets for the Leaderships have been removed and only the basis amount is considered.</li></ol><p>Last but not least, considering the expense categories, how does the average Representative behave?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_s74gYkiFtl2W6BwXf-tQ.png" /></figure><p>Don’t let the dark orange bar full you: it now represents <strong>Chartered Flights</strong>. The light orange is Consulting, which is reasonably significant in terms of average expense. But I’m still letting that sink in: we have 513 Deputies, so do the math when it comes to the total amount of money spent on Chartered Flights. I’m trying to be optimistic and remember that Brazil is a huge country, Deputies have to be present at the depths of their States to hear the pleas of its representatives. Still, I wonder if there were no alternatives.</p><p>I began saying that 2022 was a weird year because of the World Cup paired with Santa Claus. But I must confess it’s weirder for me that I will be voting just for President at the Embassy since I’m living abroad now. This election will be especially decisive for my country’s future and I hope everyone makes sound and informed decisions next October.</p><p>There’s a lot of material I want to explore that would make this text longer than it already is. I’ll make a short series in the next few weeks, following on with this analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15bbe8edabcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sampling, Twitter, and Dozens of Billions of  Dollars]]></title>
            <link>https://medium.com/@felipebras/sampling-twitter-and-dozens-of-billions-of-dollars-eaf89d149b26?source=rss-4bfcf726664d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaf89d149b26</guid>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[inferential-statistics]]></category>
            <dc:creator><![CDATA[Felipe Bras]]></dc:creator>
            <pubDate>Tue, 16 Aug 2022 15:18:21 GMT</pubDate>
            <atom:updated>2022-08-16T15:18:21.827Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sampling, Twitter, and Dozens of Billions of Dollars</h3><p>If I had <a href="https://www.cnn.com/2022/06/17/tech/elon-musk-twitter-bots/index.html">US$44bn to spare</a> I think I would not spend it buying Twitter. Maybe it’s just me — and who am I to criticize a billionaire’s business acumen — but I don’t have that sort of lust for power and influence.</p><p>Nevertheless, what I could do in the rare event of facing the chance of acquiring one of the most important social networks on the planet, is bring someone who took Statistics-101 to assess the company’s methodology. The question is: a <em>random sample </em>of 100 accounts<strong> </strong>drawn from the pool of users each day is enough to estimate the <em>proportion</em> of bots or fake accounts in Twitter’s database? Well, there are a few caveats, but the answer is yes.</p><p>In its simplest form, the problem is controlling the difference between an estimate and the real value so that we know it with a level of certainty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/0*BmFrelWmXIVVcwSI" /></figure><p>where: ε is the <em>sampling error,</em> γ=1−α (α is the <em>significance level</em>), and μ is the <em>population mean </em>(or <em>expected value</em>). We know from the Central Limit Theorem that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/0*Y63PVxmymMwfFYtd" /></figure><p>Also, using the transformation <em>Z=(X−μ) / σ,</em> we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*dDeOnFsMqryEvxCV" /></figure><p>Finally, given a <em>confidence level</em> (γ) we can calculate the <em>critical value</em> for the random variable Z:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/72/0*-Z3DdfHX_VidJVLO" /></figure><p>which can be rearranged to calculate the <em>sample size</em> required to control the <em>sample error</em> at that <em>confidence level:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/66/0*sYx0k-vETlqLC3CB" /></figure><p>The most cunning of readers know that in order to obtain the sample size we still have to know the population <em>standard deviation </em>(σ). The fact that we are dealing with a <em>proportion</em> comes in handy.</p><p>When checking the proportion of bots and fakes, each draw from the pool of Twitter accounts is described by a Bernoulli trial with <em>mean </em>and <em>variance</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/0*28ufTy068Q72cEBm" /></figure><p>A sample is a sequence of these trials with size <em>n</em>, the same proportion <em>p</em>, given by a Binomial Distribution. Let’s remember that the Binomial can be approximated by a Normal Distribution with a large enough sample. Finally, because of the Central Limit Theorem, the <em>estimator </em>for the proportion can be approximately described by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/0*a-KBU9oPTMEvbhTs" /></figure><p>Let’s say we don’t want to estimate the value of the <em>variance </em>(ultimately, the<em> </em>proportion<em> p</em>) using a sample. We still don’t know the required size of the sample, right? Currently, the problem seems recursive: estimate the proportion to get the sample size to get the proportion…</p><p>Allow me to digress a little.</p><p>High-school often students ask themselves “What is a parabola good for?”. Even more often, college students ask themselves “What is calculus good for?”. Well Bhaskara and Newton-Leibniz, it’s time to settle this conundrum! The variance of the distribution is a parabola with negative concavity and a global maximum at 0.5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*FvZ0VYprcfsF9DuW" /></figure><p>Back to Earth.</p><p>By setting <em>p=1/2 </em>we’re maximizing (and probably overshooting) the sample size. But that’s OK for now.</p><p>Let’s plug in some numbers in the sample size equation we have found previously. Choosing the <em>confidence level</em> at 99% and that we don’t want to miss the actual proportion by a difference greater than 3%:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/0*EIKQFSOmc558zVs9" /></figure><p>The required sample to obtain our estimation is way over 100 data points. However, that does not mean that Twitter’s approach is incorrect, because this large sample must be taken only <strong>once</strong>. After this first estimation, the one that is guaranteed to be at most 3% from the actual value with 99% confidence, the manual daily tests with 100 accounts will check if the proportion is off from this one. Considering that the main concern is to check if the relative number of bots or fakes is increasing over time, the hypothesis test we should consider is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/90/0*UjDV1oyK1wLxqaR2" /></figure><p>Now, I assume Twitter has already done that. Several times. With more advanced techniques, TBH. The micro-blogging pioneer already <a href="https://www.cnn.com/2022/08/05/tech/elon-musk-twitter-suit-answer/index.html">provided their estimator</a> for <em>p: </em>it is at most 5%. Plugging that value in the same equation, we arrive at a sample size for the daily tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/0*OkoxsmMBACo6NfGy" /></figure><p>Which is more than 100, but in the same order of magnitude. Rearranging the equation and setting n=100, the <em>sampling error </em>is about 5.01%, meaning that we’re 99% sure that the proportion of bots or fakes is below 10% of the total. Which is a suitable amount for any business decision.</p><p>In my view, Twitter’s approach is to be taken seriously because it is simple and verifiable. Fine-tuning of the tolerances can always be discussed, but there’s nothing much that machine learning can do for this particular estimation. These techniques should be applied to identify individual bots or fakes, of course, but let the estimations in the hands of good old statistical inference.</p><p>Two important notes:</p><ol><li>The 100 accounts daily sample is analyzed by humans and classified as real or bot. As mentioned in the end, this should (and probably is) assisted by machine learning. It’s reasonable to think that the results are at least fed into some supervised classification algorithm.</li><li>In samples with draws without replacement, the distribution of the sample mean is actually a Hypergeometric. Using the Binomial Distribution is completely acceptable when the population size is much bigger than the sample size.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaf89d149b26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>