<?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 Vincenzo Lavorini on Medium]]></title>
        <description><![CDATA[Stories by Vincenzo Lavorini on Medium]]></description>
        <link>https://medium.com/@vincenzo.lavorini?source=rss-f0c2f36e0bc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1VbkGQhfCsBwTYYoK27F7g.jpeg</url>
            <title>Stories by Vincenzo Lavorini on Medium</title>
            <link>https://medium.com/@vincenzo.lavorini?source=rss-f0c2f36e0bc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:20:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vincenzo.lavorini/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[KneeFinder: simple tool to find the Knee / Elbow point.]]></title>
            <link>https://medium.com/@vincenzo.lavorini/kneefinder-simple-tool-to-find-the-knee-elbow-point-b72cd806b864?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b72cd806b864</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Tue, 01 Nov 2022 16:01:15 GMT</pubDate>
            <atom:updated>2023-05-31T09:54:41.506Z</atom:updated>
            <content:encoded><![CDATA[<p>This post describe <a href="https://github.com/vlavorini/kneefinder">KneeFinder</a>, a tool that you can use to find the knee / elbow point.</p><p><strong>Update, 31 Mai 2023</strong>: a 2-dimensional version of this tool exist: <a href="https://github.com/vlavorini/hyperknee_finder">HyperKnee finder</a>. The new tool optimize two parameters at the same time.</p><p>If you landed here, probably you are trying to tune some parameter of an algorithm.</p><p>You also read somewhere that, in order to tune that parameter(s), the best way is through the “knee” or “elbow” method: run your algorithm with different values of the parameter you want to tune, take the outcomes, plot them and find the point where “the slope changes the most”.</p><p>A better definition (from Satopää, Albrecht, Irwin, and Raghavan, 2011, p.1) states the knee point as the point where the</p><blockquote>“relative costs to increase [or decrease, NdC] some tunable parameter is no longer worth the corresponding performance benefit”</blockquote><p>While the reason for which using the knee/elbow method is clear, the methodologies used to deploy it change between scopes and algorithms. What they have in common is the final part: having the plot outcome VS parameter, find the optimal value for that parameter.</p><p>This post explain how to find it in a straightforward way, with a simple and robust tool.</p><h3>The example</h3><p>Say we have the following data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*glt7IVf3FzHmHMOfUzi4uw.png" /><figcaption>Figure 1: cost as function of the parameter value.</figcaption></figure><p>What one usually do in such situation is to take as optimal parameter p= 2 or p=3, just following their sense. The problem is that the sense of one can be different from the sense of another, and both of them can’t be automatized.</p><h4>KneeFinder</h4><p>Here we propose an empirical definition of the knee point:</p><blockquote>The knee point is the point farther from the line passing by the first and the last point of the data</blockquote><p>While this definition is theoretically weak, empirically is very strong: if your parameter can be tuned by the knee method, the data will be such that this definition coincide with the point you want to find.</p><p>Note that other and more sophisticated methods exists (like <a href="https://github.com/arvkevi/kneed">Kneed</a>), this one is easier to use (no hyper-parameters to define) and so it is more robust and easy to insert in an automated pipeline.</p><p>Let’s develop our definition in a graphical way:</p><ul><li>draw a segment passing between the first and the last point of the data</li><li>draw the distances between the data points and the segment</li><li>take the biggest of those distances</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*fTcdraR1K78zp2jH6b88yQ.png" /><figcaption>Figure 2: graphical explanation of the proposed algorithm.</figcaption></figure><p>Here it is: the optimal value for your parameter is two.</p><p>You can find the <a href="https://github.com/vlavorini/kneefinder">KneeFinder at this link</a>. Note that it’s still in testing phase, so please fill a issue on GitHub if you find any.</p><h4>Inside the algorithm</h4><p>Here some technicality inside the code, for your pleasure.</p><p>In order to be efficient, instead of looping between all the data points and calculate the distances you see in Figure 2, the algorithm we wrote calculates the cross product between the vector given by the difference between the first and the last point (the orange segment of Figure 2, if you want), and the vectors which define the data points between which we have to choose. All of them at once, thanks to Numpy vectorization capabilities.</p><p>The result is an array of non-normalized lengths, and the biggest of them define our knee point.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b72cd806b864" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change management for rookies]]></title>
            <link>https://medium.com/@vincenzo.lavorini/change-management-for-rookies-837608564b20?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/837608564b20</guid>
            <category><![CDATA[engineering-management]]></category>
            <category><![CDATA[change]]></category>
            <category><![CDATA[change-management]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 17:01:40 GMT</pubDate>
            <atom:updated>2022-01-04T17:01:40.497Z</atom:updated>
            <content:encoded><![CDATA[<p>Dear reader,</p><p>you too, like me, found yourself having to manage a business transformation. You too, like me, did not have any training when you did it. You didn’t even know that the concept of ‘<a href="https://en.wikipedia.org/wiki/Change_management">Change Management</a>’ actually existed.</p><p>You then managed:</p><ul><li>technical transformations, such as the migration of software procedures</li><li>procedural transformations, such as the introduction of new project management and monitoring flows</li><li>social transformations, such as having to change team structures</li></ul><p>all by simply avoiding making the mistakes of the previous times.</p><p>Personally, after several iterations, I feel confident in synthesizing the cornerstones that constitute a good basis for managing transformations:</p><ul><li>do not underestimate</li><li>consider the interested parties (also in the planning phase)</li><li>create familiarity with the new solution</li><li>focus on the goals of transformation</li><li>start small</li></ul><p>Below is a short story that perfectly sums up the need to use these tricks.</p><h4>Let’s talk about Jira</h4><p>It is a Kanban-style task management and monitoring system. A relatively easy and intuitive system to use, at least in the first instance.</p><p>When I had to implement it into a company, I limited myself to the classic presentation on slides, followed by proof of use. Looking at the faces of those present I felt confident that within a few weeks all interested parties would use this product correctly.</p><p>Instead, for several months Jira was used little and badly. Some members shown passive resistance by merely marking the tasks as completed. Others made it an ‘official’ duplicate of their old tracking method. Many just saw it as a waste of time, useful only for management to track the work of individuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2znji0LjsZfObEKy3Pkqg.png" /><figcaption>Example of using Jira.</figcaption></figure><p>This situation highlights a number of mistakes that have been made.</p><h4>Underestimation</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F10LW7WuoxTm4hO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ffandom-reaction-gif-10LW7WuoxTm4hO&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2F10LW7WuoxTm4hO%2F200.gif%3Fcid%3D790b7611c695f109566d209ba34291459b2c398b421a4505%26rid%3D200.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="317" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc23c474c497a7055881ff507bceeb72/href">https://medium.com/media/dc23c474c497a7055881ff507bceeb72/href</a></iframe><p>Transformations require resources: time, energy, empathy, willpower of the entire affected community. This is why business transformation processes are often underestimated. In fact, it seems easier to deceive (oneself, the superiors and the team) that one finds oneself in front of a “little thing” to be included in ordinary work. Except then, regularly, find themselves using more resources than expected to finalize this “little thing”.</p><p>A good rule of thumb is therefore to consider <strong>every introduction of a novelty in the life of workers as a real corporate transformation</strong>. This state of mind will allow us to face it with the right tools</p><h4>Presumption</h4><p>We are too often convinced that we have the necessary knowledge to carry out the tasks assigned to us. It therefore happens that we are confident that both innovation and its implementation are considered and designed in the best possible way. Except then receiving feedback from interested parties on parts that could have (should have?) been done differently.</p><p>Therefore, it’s better to stay humble and <strong>include interested parties </strong>already in the design phase, in order to tune the solution with the people who will use it.</p><p>As a bonus it is obtained that the workers included, happy to have been considered, will become ambassadors of the project, thus contributing to <strong>increasing the familiarity </strong>of all the others towards it.</p><h4>Strange loves</h4><p>It still happens that we are so in love with the hypothesized solution that we forget that its only purpose should be solving a problem. That is, it happens that we look for a series of problems to be solved with the solution we already have in mind.</p><p>Therefore it includes excessively complex features, or whose usefulness is projected into a too distant and/or smoky future, or simply useless features.</p><p>So let’s not forget to<strong> focus on the objectives of the transformation</strong>, rather than on the benefits it could bring. In general, it is <a href="https://en.wikipedia.org/wiki/Occam&#39;s_razor">better to prefer simple solutions to complex solutions</a>.</p><h4>Repetita juvant</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FqgSV3R0z9C1Da%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fnewer-qgSV3R0z9C1Da&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2FqgSV3R0z9C1Da%2Fgiphy.gif%3Fcid%3D790b761115294434dc32c7d3bf34995649af979456c1b81e%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="233" frameborder="0" scrolling="no"><a href="https://medium.com/media/7db6a32508566654dca0345d6d0e54cb/href">https://medium.com/media/7db6a32508566654dca0345d6d0e54cb/href</a></iframe><p>The hardest part in changes is often overcoming the resistance of the workers. Inertia in these cases tends to win easily: if so far everything has gone on without major problems, why change?</p><p>Explaining the reasons why the change must take place is not enough to convince people. The most reticent ones agree with you halfway: according to them your solution does not worthily solve the problems for which it would arise, or it solves only secondary problems; in any case, it certainly introduces new ones. In sum, it is one more fish to fry.</p><p>This line of thinking is like Cassandra’s syndrome, and tends to come true if we do not act promptly: the worker who considers the solution useless, at the limit harmful, will act (perhaps involuntarily) in such a way as to make it really useless, and at the limit harmful.</p><p><strong>Create familiarity </strong>with the new solution mitigates this problem. Some examples:</p><ul><li>discuss the key concepts and their importance, for example through meetings on the state of migration;</li><li>highlight the successes achieved</li><li>adopt old terms in the new solution (that’s why they called the PC screen ‘desktop’)</li><li>granting time and space to workers to experiment with the new solution.</li><li>create internal games / competitions around the new solution.</li></ul><h4>Blinders</h4><p>The “<a href="https://en.wikipedia.org/wiki/Agile_software_development">Agile</a>” methodology is not just prerogative of software developers. The implementation of the change should therefore consider the unforeseen, positive and negative, that occur along the way, always with a view to <strong>focus on the objectives of the change</strong>, rather than on the change itself, and to <strong>include stakeholders </strong>while redesigning the solution.</p><h4>Too big to fail</h4><p>If innovation involves many teams and / or people, it may become difficult to optimize it while it is being installed. Not only for technical issues, but also for political ones: it would be difficult to explain that, given the effects, we need to make changes to the change, that will (again) affect the way people work, so that the global change works at its best.</p><p>It would be natural to prefer to patch up here and there, so to solve the found issues. The risk is not to have an optimal solution anyway.</p><p>It is therefore preferable to start with a small group of users: not only will you avoid embarrassment, but you can also act more aggressively, as errors and failures are more tolerated in this configuration. This practice is also known as<em> </em><a href="https://ideas.darden.virginia.edu/the-learning-launch-how-to-grow-your-business-with-the-scientific-method"><em>Learning Launch</em></a>.</p><p>It is important to consider that the workers who participate in the experiment could see their work (totally or partially) as useless, in case the change experiment does not bear good results. It is therefore appropriate to consider rewarding techniques.</p><h4>Conclusions</h4><p>Making changes in the company is a difficult operation, for several reasons. It is therefore useful to give oneself the right tools to limit the problems, which are always around the corner anyway.</p><p>This article does not pretend to be a recipe to follow, but I hope it can give you a good part of the tools necessary to bring about a change in the company in the best possible way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=837608564b20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trasformazioni aziendali (Change Management) per non esperti.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@vincenzo.lavorini/trasformazioni-aziendali-change-management-per-non-esperti-7b0f50c165c9?source=rss-f0c2f36e0bc7------2"><img src="https://cdn-images-1.medium.com/max/1708/1*1slm5Hfy7SFpuATYSZk20A.png" width="1708"></a></p><p class="medium-feed-snippet">English translation at this link</p><p class="medium-feed-link"><a href="https://medium.com/@vincenzo.lavorini/trasformazioni-aziendali-change-management-per-non-esperti-7b0f50c165c9?source=rss-f0c2f36e0bc7------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@vincenzo.lavorini/trasformazioni-aziendali-change-management-per-non-esperti-7b0f50c165c9?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b0f50c165c9</guid>
            <category><![CDATA[change]]></category>
            <category><![CDATA[engineering-mangement]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <category><![CDATA[change-management]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 14:30:27 GMT</pubDate>
            <atom:updated>2022-01-04T17:02:22.467Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
        </item>
        <item>
            <title><![CDATA[Hybrid work: the issues of free choice]]></title>
            <link>https://medium.com/@vincenzo.lavorini/hybrid-work-the-issues-of-free-choice-60bf63baa8ef?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/60bf63baa8ef</guid>
            <category><![CDATA[diversity]]></category>
            <category><![CDATA[hybrid-work]]></category>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[hr]]></category>
            <category><![CDATA[remote-working]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Tue, 10 Aug 2021 13:19:14 GMT</pubDate>
            <atom:updated>2021-08-13T10:04:17.578Z</atom:updated>
            <content:encoded><![CDATA[<p>At the time of writing this article many companies have become convinced of how much efficiency can be gained with remote work, and they are therefore reflecting on how to regulate these policies for the post COVID-19.</p><p>(Italian translation of this article is <a href="https://medium.com/@vincenzo.lavorini/telelavoro-smart-working-parziale-i-problemi-della-libera-scelta-29cf79a386e3">at this link</a>)</p><p>Having used to work from home both as a team manager and as a worker, I have noticed some differences from office work which, if maintained for a long time, can cause issues among colleagues and to the whole company.</p><h4>The alternatives</h4><p>Even if it exist there is the possibility of working 100% both remotely and in the office, this article focuses on the hybrid solution, i.e. partial remote work: a few days a week working remotely (which for the mass practically means from home), and a few days in the office. This solution lends itself to large customization: how many days a week? Which ones? Establish a common policy for the entire company, or let each department / team / worker decide independently?</p><p>At first glance, the choice could be dismissed as simple: we set loose guidelines and let teams / departments / workers decide.</p><p>But this elasticity opens up non-trivial scenarios, if we think in the medium-long term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YuyRR-6DmhOV7PX-SVaR3g.jpeg" /><figcaption>Home installation. [<a href="https://search.creativecommons.org/photos/40afbbc8-2e33-4702-87b7-a85fa35b558e">CC 2.0</a>]</figcaption></figure><h4>The advantages of being in the office</h4><p>The benefits of working from home are glaring nowadays, both for the workers and the companies. Maybe a little too much, and in their dazzle they distract our view from the benefits of working in the office.</p><p>First of all: <strong>sociability</strong>. Much of the communication between human beings occurs through gestures, tones, glances, and other non-verbal means. Furthermore, our sympathy towards a person also depends on her behavior with others, and also on her behavior outside of communications. It’s then clear how much easier is to deeply know our colleagues and consequently seal a friendship with them while we are physically near to them.</p><p>Better socialization with colleagues helps efficiency: we have more pleasure, so we act more diligently, in giving help to a friend rather than from a semi-unknown colleague.</p><p>Again, in the most extreme utilitarian case, if one of these fellow-friends will find himself in some way able to benefit us, he will.</p><p><strong>Professional growth</strong> is another advantage. The chats we have in the various breaks do not necessarily focus on the matters of the moment; maybe we speak with the existence of an instrument, or a technique, or an interesting event which, although perfectly useless at the moment, could be useful in unpredictable ways in the future. As example, a chat about how a stormy situation was handled, or how the relationship with a supplier, or with a customer was managed. Note that although these topics can be addressed in remote chats, hardly we talk in such channels about topics which usefulness is in doubt, especially when we don’t know not very well our colleagues, or when we know that our manager is reading. But in front of a coffee our attitude is much more informal, and we are willing to indulge, tolerate and interact more.</p><p>The same reasoning applies to the <strong>insights</strong> about the company and its internal dynamics: those who go often to the office, stroll through the corridors, stop at the coffee machines, end up interacting with colleagues and bosses (including those with whom they usually have no relationships) in the most different ways, and they manage to perceive humors, worries, rumors about the ongoing decision-making processes in quantities and in qualities far more significant than the remote chats, or in the more or less formal remote meetings.</p><p>Again, there is <strong>visibility</strong>, particularly towards senior executives. We can divide managers into two macro categories: the ‘neutral’ ones, who tend to be unconcerned about the place where workers perform their duties, and those who prefer to see the workers in the office; to my knowledge, executives who prefer their subordinates stay at home do not exist.</p><p>While neutral managers will be just neutral towards both categories of workers, the latter will have an amplified attitude towards those workers who work in the office. So, if we imagine that in a company there are elements of both kinds, we understand that on average the workers which stay more in the office will acquire more visibility.</p><p>These are just some of the privileges that come from being in the office, enough to give an idea. For each of them mitigation policies that make their impact less felt can be studied, but they will always remain present in hybrid work situations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2rTL5ZC1YLI00X_Ux67Ueg.jpeg" /><figcaption>Pauses promote diversity [<a href="https://search.creativecommons.org/photos/37ec3cb7-f929-47e8-b540-c265fa3f6dde">CC 2.0</a>]</figcaption></figure><h4>The difficulty of choosing</h4><p>Although at first glance one could think of an awareness campaign on workers to help them to choose with more conscience, it cannot be ignored that we are dealing with human beings. In essence, a young, single and childless worker would still tend to go to the office more often than an older one with family and dependent children.</p><p>The former, therefore, would enjoy the benefits listed above to a greater extent than the latter; as a result, his daily work and career would take more advantage.</p><p>If we want to expand the two categories above, we could consider that would tend to stay more at home people:</p><ul><li>disabled, or with disabled children</li><li>introverted, or more generally with sensitive psychological distress</li><li>that feels overweight, underweight, and in general those who do not believe to correspond to the usual standards of beauty</li><li>who belong to ethnic minorities</li><li>who live far from the office</li><li>who carry out secondary activities (voluntary work, associations, but also parallel projects)</li><li>…</li></ul><p>Leaving free choice therefore brings with it an enormous problem of diversity: it will lead to the formation of categories of workers advantaged, and therefore preferable, both in terms of career and entry into the company.</p><h4>The deterioration of relationships at work</h4><p>At the atomic level, if some workers find themselves professionally advantaged and socially more cohesive than others, the business environment will necessarily worsen. I am not a psychologist, but I believe there is a high probability that some of the following situations may occur:</p><ul><li>relations between workers will be more tense; there will be misunderstandings, differences of opinion will increase, collaboration and solidarity will be undermined;</li><li>workers who will find themselves advantaged as they frequent the office more may feel they do not deserve the advantage obtained (<a href="https://en.wikipedia.org/wiki/Impostor_syndrome">impostor syndrome</a>), tending to amplify stress, anxiety, mental rumination.</li><li>the managers who, inevitably and understandably, will favor these workers will develop a feeling of guilt towards the other workers, and therefore would not be cloudless in their choices, both daily and strategic ones; moreover, they will find themselves being flattered in an abnormal way by the former, to the detriment of the diversity of thought, and challenged in an abnormal way by the others, to the detriment (again) of their own serenity and perception of the quality of their work (again, syndrome of ‘impostor).</li><li>workers who will find themselves disadvantaged because of the choose to stay more at home will feel that their efforts and professionalism are not sufficiently valued, which is the exact opposite of the impostor syndrome (some call it the <a href="https://medium.com/swlh/the-opposite-of-imposter-syndrome-4b4ec7487b6d">authority syndrome</a>); they will feel anger, frustration, desire for revenge.</li></ul><p>By extrapolation, similar problems will arise leaving the teams and the departments free to decide on the subject, as the departments that choose to frequent the site more will have an advantage over the others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HC7OaLBDKuV2Nc8ermxv-g.jpeg" /><figcaption>Free choice can lead to issues [<a href="https://search.creativecommons.org/photos/2e990ca4-1b8f-483d-b06c-714738fda105">cc 2.0</a>]</figcaption></figure><h4>Solutions?</h4><p>Free choice is beautiful, but it is an illusion. Each choice we make is influenced by a thousand small laces that limit its freedom. And the factors that influence a worker on a daily basis in his choices about how much and where to work, as we have seen, could lead him to damage his relationship with colleagues, his career, and potentially even his mental health. Also, and consequently, the company would be damaged.</p><p>If we exclude a priori the possibility of total remote work (or total presence in the office), the simplest solution is a strict regulation of hybrid work. More clearly, companies should decide <strong>how many</strong> and <strong>which days</strong> the workers should be present in the office, and when instead they should stay at home, or in any case elsewhere than in the office.</p><p>Such a policy will inevitably be hated by many, especially those who are convinced that they are fully capable of choosing the best for themselves, both tactically and strategically.</p><p>But giving every worker equal opportunities is useful to safeguard a good business environment, therefore this solution remains, in my opinion, the best on the market.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60bf63baa8ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telelavoro (Smart Working) parziale: i problemi della libera scelta.]]></title>
            <link>https://medium.com/@vincenzo.lavorini/telelavoro-smart-working-parziale-i-problemi-della-libera-scelta-29cf79a386e3?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/29cf79a386e3</guid>
            <category><![CDATA[risorse-umane]]></category>
            <category><![CDATA[telelavoro]]></category>
            <category><![CDATA[diversità]]></category>
            <category><![CDATA[salute-mentale]]></category>
            <category><![CDATA[smart-working]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Sat, 07 Aug 2021 17:09:35 GMT</pubDate>
            <atom:updated>2021-08-13T10:03:37.214Z</atom:updated>
            <content:encoded><![CDATA[<p>Nel momento in cui scrivo questo articolo molte imprese si sono convinte di quanto si guadagni in termini di efficienza con il <a href="https://it.wikipedia.org/wiki/Telelavoro">telelavoro</a> (o “Smart Working”, come stranamente definito da molti), e stanno dunque riflettendo su come regolamentare tali politiche per il post COVID-19.</p><p>(English translation is <a href="https://medium.com/@vincenzo.lavorini/hybrid-work-the-issues-of-free-choice-60bf63baa8ef">at this link</a>)</p><p>Avendo utilizzato il telelavoro sia come dirigente di una squadra, sia come lavoratore, ho notato alcune differenze rispetto al lavoro in ufficio che, se mantenute a lungo, possono causare squilibri tra colleghi.</p><h4>Le alternative</h4><p>Sebbene esista la possibilità di lavorare al 100% sia da remoto che in ufficio, questo articolo si focalizza sulla soluzione ibrida, ossia il telelavoro parziale: qualche giorno a settimana da remoto (sostanzialmente, da casa), e qualche giorno in ufficio.</p><p>Tale soluzione si presta a grandi personalizzazioni: quanti giorni a settimana? Quali? Stabilire una politica comune per l’intera azienda, o lasciare che ogni dipartimento/squadra/lavoratore decida in autonomia?</p><p>Ad un primo impatto si potrebbe tacciare la scelta come semplice: stabiliamo delle direttive lasche e lasciamo decidere squadre/dipartimenti/lavoratori.</p><p>Ma tale elasticità apre scenari non banali, se ragioniamo nel medio-lungo termine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YuyRR-6DmhOV7PX-SVaR3g.jpeg" /><figcaption>Installazione domestica. [<a href="https://search.creativecommons.org/photos/40afbbc8-2e33-4702-87b7-a85fa35b558e">CC 2.0</a>]</figcaption></figure><h4>I vantaggi della presenza in ufficio</h4><p>I vantaggi del lavoro da casa sono ormai lampanti. Forse un po’ troppo, e nel loro abbagliarci distraggono la nostra vista dai benefici del lavorare in ufficio.</p><p>Primo tra tutti:<strong> la socialità</strong>. Gran parte della comunicazione tra esseri umani avviene tramite gesti, toni, sguardi, ed altri mezzi non verbali. Inoltre, la nostra simpatia verso una persona dipende anche dal suo comportamento con gli altri, ed anche dai suoi comportamenti al di fuori delle comunicazioni. Si capisce quindi quanto sia più facile conoscere i colleghi e conseguentemente stringere con loro amicizia standogli fisicamente vicino piuttosto che a casa.</p><p>Socializzare meglio con i colleghi aiuta l’efficienza: abbiamo più piacere, quindi agiamo con più solerzia, nel soddisfare richieste o offrire aiuto ad un collega amico, che ad un collega semi sconosciuto.</p><p>Ancora, nel caso utilitaristico più estremo, se uno di questi colleghi-amici si troverà in futuro nella possibilità di avvantaggiarci in qualche modo, lo farà.</p><p><strong>La crescita professionale</strong> è un altro vantaggio. Le chiacchierate che facciamo nelle varie pause non necessariamente vertono sulle faccende del momento; magari parliamo col collega dell’esistenza di strumento, o di una tecnica o di un avvenimento interessante, che sebbene siano perfettamente inutili sul momento, potrebbero giovare in modi imprevedibili in futuro. Ad esempio, su come è stata gestita una situazione burrascosa, o su come è stato gestito il rapporto con un fornitore, o con un cliente. Notare che sebbene tali argomenti possano esser sicuramente affrontati in teleconferenza o in chat, difficilmente parliamo con i colleghi di argomenti dalla dubbia utilità, specialmente quando non conosciamo bene i colleghi che leggeranno, o quando sappiamo che il nostro manager è li che legge/ascolta. Ma davanti ad un caffè il nostro atteggiamento è molto più informale, e siamo disposti a concederci, tollerare ed interagire maggiormente.</p><p>Stesso ragionamento vale per le <strong>intuizioni sull’azienda </strong>e sulle dinamiche interne ad essa: chi frequenta l’ufficio, passeggia tra i corridoi, si ferma alle macchinette del caffè, finisce per interagire con colleghi e superiori ( compresi quelli con cui abitualmente non ha relazioni lavorative) nei modi più diversi, e riesce a percepire umori, preoccupazioni, ma anche voci di corridoio su processi decisionali in corso e futuri, e lo fa in quantità e qualità ben superiori rispetto a quanto si legge sulle chat aziendali, o nelle riunioni più o meno formali.</p><p>Ancora, vi è la <strong>visibilità</strong>, in particolare verso i quadri dirigenziali. Possiamo dividere i dirigenti in due macro categorie: quelli ‘neutrali’, che tendono all’indifferenza sul luogo ove i lavoratori svolgono i loro compiti, e quelli che quelli che preferiscono vedere i lavoratori in ufficio; a mia conoscenza, dirigenti che preferiscono che i propri sottoposti stiano a casa non esistono.</p><p>Mentre i dirigenti neutrali saranno, appunto, neutri nei confronti di entrambe le categorie di lavoratori, i secondi avranno una chiara preferenza: amplificata per chi lavora in ufficio, smorzata per chi lavora da casa. Quindi, se immaginiamo che in un’azienda esistano elementi di entrambe le specie, si capisce che mediamente chi sta in ufficio acquisirà più visibilità.</p><p>Questi sono solo alcuni dei di privilegi che scaturiscono dallo stare in ufficio, e credo siano sufficienti a rendere l’idea. Sebbene per ciascuno di essi si possano studiare politiche di mitigazione che ne facciano sentire meno l’impatto, essi rimarranno sempre presenti in situazioni di lavoro ibrido.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2rTL5ZC1YLI00X_Ux67Ueg.jpeg" /><figcaption>Pause come promozione della diversità [<a href="https://search.creativecommons.org/photos/37ec3cb7-f929-47e8-b540-c265fa3f6dde">CC 2.0</a>]</figcaption></figure><h4>La difficoltà dello scegliere</h4><p>Sebbene a primo impatto si potrebbe pensare ad una campagna di sensibilizzazione sui lavoratori per portarli a scegliere con più coscienza, non si può ignorare che abbiamo a che fare con esseri umani, in sostanza, lavoratori scapoli, giovani e senza prole tenderebbero comunque ad andare in ufficio più spesso rispetto a lavoratrici più anziane, con famiglia e figli a carico.</p><p>I primi, dunque, godrebbero dei benefici sopra elencati in modo maggiore rispetto alle seconde; di conseguenza, il loro lavoro quotidiano e la loro carriera ne sarebbero avvantaggiati.</p><p>Volendo espandere le due categorie di sopra, possiamo considerare che tenderebbero a stare maggiormente a casa le persone:</p><ul><li>disabili, o con figli disabili</li><li>introverse, o più in generale con sensibili disagi psicologici</li><li>in sovrappeso, in sottopeso, ed in generale coloro che non corrispondono ad i canoni abituali di bellezza</li><li>che appartengono a minoranze etniche</li><li>che abitano lontano dall’ufficio</li><li>che svolgono attività secondarie (volontariato, associazionismo, ma anche progetti paralleli)</li><li>…</li></ul><p>Lasciare libera scelta porta con se dunque innanzitutto un enorme problema di diversità: si formerebbero categorie di lavoratori avvantaggiati, dunque preferibili, sia in prospettiva di carriera sia in ingresso in azienda.</p><h4>Il deterioramento dei rapporti aziendali</h4><p>Inoltre, a livello atomico, se alcuni lavoratori si troveranno professionalmente avvantaggiati e socialmente più coesi rispetto ad altri, l’ambiente aziendale andrà necessariamente peggiorando. Non sono uno psicologo, ma ritengo alta la probabilità che si possano verificare alcune tra le seguenti situazioni:</p><ul><li>i rapporti tra lavoratori si tenderanno; ci saranno incomprensioni, aumenteranno le divergenze di opinioni, collaborazione e solidarietà verrebbero minate;</li><li>i lavoratori che si troveranno avvantaggiati in quanto maggiormente frequentano l’ufficio potrebbero sentire di non meritare il vantaggio ottenuto (<a href="https://it.wikipedia.org/wiki/Sindrome_dell%27impostore">sindrome dell’impostore</a>), tendendo ad amplificare stress, ansia, ruminazione mentale.</li><li>i dirigenti che, inevitabilmente e comprensibilmente, favoriranno questi lavoratori svilupperanno un sentimento di colpa verso gli altri lavoratori, e quindi non sarebbero sereni nelle loro scelte, sia quotidiane che strategiche; inoltre, si troveranno ad essere adulati in maniera abnorme dagli uni, a discapito quindi della diversità di pensiero, e contestati in maniera abnorme dagli altri, a discapito (nuovamente) della propria serenità e della percezione della qualità del proprio lavoro (ancora, sindrome dell’impostore).</li><li>i lavoratori che si troveranno svantaggiati per la scelta di restare maggiormente a casa sentiranno che i propri sforzi e la propria professionalità non sono sufficientemente valorizzati, che è l’esatto opposto della sindrome dell’impostore (qualcuno la chiama <a href="https://medium.com/swlh/the-opposite-of-imposter-syndrome-4b4ec7487b6d">sindrome dell’autorità</a>); sentiranno rabbia, frustrazione, voglia di rivalsa.</li></ul><p>Estrapolando, problemi simili si presenteranno lasciando libertà di decisione a squadre e dipartimenti, in quanto i dipartimenti che scelgono di frequentare maggiormente la sede saranno avvantaggiati rispetto agli altri.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HC7OaLBDKuV2Nc8ermxv-g.jpeg" /><figcaption>[<a href="https://search.creativecommons.org/photos/2e990ca4-1b8f-483d-b06c-714738fda105">cc 2.0</a>]</figcaption></figure><h4>Soluzioni?</h4><p>La libera scelta è bellissima, ma è un’illusione. Ogni scelta viene influenzata da mille piccole lacci che ne limitano, appunto, la libertà. Ed i fattori che influenzano quotidianamente un lavoratore nelle sue scelte su quanto e dove lavorare, come abbiamo visto, potrebbero portarlo al danneggiamento del suo rapporto con i colleghi, della sua carriera, e potenzialmente anche della sua salute mentale. Anche, e di conseguenza, l’azienda ne verrebbe danneggiata.</p><p>Se escludiamo a priori la possibilità di lavoro remoto totale (o presenza in ufficio totale), la soluzione più semplice rimane regolamentare in modo stretto il telelavoro parziale. Più chiaramente, le aziende dovrebbero decidere quanti e quali giorni si <strong>deve</strong> presenziare in ufficio, e quando invece si <strong>deve</strong> stare a casa, o comunque altrove che in ufficio.</p><p>Tale politica sarà inevitabilmente detestata da molti, in particolare da coloro che sono convinti di essere pienamente capaci di scegliere il meglio per se stessi, sia tatticamente che strategicamente.</p><p>Ma dare ad ogni lavoratore pari opportunità è utile a salvaguardare un buon ambiente aziendale, pertanto tale soluzione rimane, a mio parere, la migliore sulla piazza.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29cf79a386e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Features correlations: data leakage, confounded features and other things that can make your Deep…]]></title>
            <link>https://medium.com/data-science/features-correlations-data-leakage-confounded-features-and-other-things-that-can-make-your-deep-771bcaf84f9f?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/771bcaf84f9f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Wed, 04 Dec 2019 15:43:53 GMT</pubDate>
            <atom:updated>2019-12-04T17:09:23.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>Features correlations: data leakage, confounded features and other things that can make your Deep Learning model fail</h3><p>One of the most overlooked concepts in phenomenological sciences, and especially in Deep Learning, is on correlation between input features.</p><p>What is correlation? Check this cartoon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ayDAjhkP2ZaafX4MnvbSg.jpeg" /></figure><p>As it seems from the plot that boss is showing, the more employees have shaved heads, the more the company sales increase. If you where that boss, would you consider the same action on your employees? Probably not.</p><p>In fact, you recognize that there is no <a href="https://en.wikipedia.org/wiki/Correlation_does_not_imply_causation"><em>causality</em></a> between the two sets of events, and their behaviour is similar just by chance. More clearly: the shaved heads do not cause the sales.</p><p>So, we just spotted the existence of at least two possible categories of correlations: without and with causality. We also agreed that only the second one is interesting, while the other is useless, when not misleading. But let’s dive deeper.</p><h3>Correlations in Deep Learning</h3><p>Let me introduce an example in the Deep Learning world, and in particular in the computer vision realm, where a non-causal correlation between features actually makes a model fail.</p><h4>What are the “features” in a picture?</h4><p>In general, a feature is whatever the model uses to build it’s predictions. But maybe it’s better to specify what is a feature in this context:</p><p>Consider a picture of a face. Features can be:</p><ol><li>a bulk of green pixels</li><li>a circle filled of green pixels</li><li>a set of white pixels containing the circle filled of green pixels</li><li>… all the previous and more to compose an eye</li><li>… all the previous and more to compose the face.</li></ol><p>All of them are features. And just to stay tuned, the feature “iris” is correlated with the feature “eye”.</p><h4>Classifying tigers</h4><p>Now, suppose you train a model to recognize tigers, and suppose the training set is composed by a thousands of pictures similar to the ones below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1Kbhic3JKYps_-Mbxpbn7g.png" /><figcaption>Tiger examples in the Training set.</figcaption></figure><p>Of course, the training set includes other pictures describing what is not a tiger; maybe other animals, cars, helicopters, etc.</p><p>Let’s say the model you trained on such dataset performs with a very high score on the Test set. Happy with your model, you go to a zoo in order to try it with a picture of a tiger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTQed5Xy-___BRyKNkmu2Q.jpeg" /><figcaption>The picture you took in the zoo.</figcaption></figure><p>You expect the model to raise the green flag, recognizing the picture as containing a tiger. But the model actually completely fails, saying it’s not. What did go wrong?</p><h4>The guilty: correlated, non-causal features</h4><p>Maybe you already spotted the issue: while the pictures in the training set show tigers in the forest, the picture at the zoo show a tiger in a cage. In technical terms, the picture you took belong to a different distribution than the Training set one.</p><p>What’s happening is: the model believes that a tiger is the animal you know surrounded by “forest”, because in our Training set it’s always like this. Since in the picture at the zoo there is no forest, the model do not recognize the picture as containing a tiger.</p><p>Now we can better discriminate the correlations, introducing a third category, i.e. correlations caused by a <a href="https://en.wikipedia.org/wiki/Confounding">confounding</a> factor. It’s effect can in fact confuse the model, letting it believe that there is a causal correlation between the animal and the forest which actually do not exist.</p><p>In our example, the confounding factor, a.k.a <em>hidden feature</em> (H) causes both features ‘tigers’ and ‘forest’ to be present in the same picture. H is a set of events like: biology, opportunity of finding a tiger, but also mood of the photographers, media interest, and in general whatever can make exist a picture of a tiger in a forest.</p><p>So when this set of events H occurs, a picture with a tiger in a forest is generated. But H is not generalizable: not every time a tiger is manifest also a forest is, like in the example of the picture at the zoo or a picture of a tiger in the snow.</p><p>In other words, our model do believes the tiger <em>is the hidden feature H</em>, and not simply the tigers as the animals we know.</p><h4>Schematic view</h4><p>We just introduced three types of correlations you should discern when building a data model. Let’s see them in a schema</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*zx-A3TyY1Mw_jGURV4rPGw.png" /></figure><ol><li>The first case is the easiest to recognize, like the cartoon at the begin of the article. A manifestation of this case in the Machine Learning world is known as <a href="https://machinelearningmastery.com/data-leakage-machine-learning/">data leakage</a>. <br>As example, consider the Tiger classifier, and suppose that every picture containing a tiger is annotated with some mark, say a green cross on the top left of the picture. Since minimization methods like gradient descent are lazy, it’s easier for the model to recognize the mark then to recognize the tiger. And so, the model will only check the existence of the mark to recognize tiger pictures. The obvious corollary is that such a model is practically useless, because in production you will not find the marks you have in the training set.</li><li>The second case is the only one we can safely accept. An example can be the stripes in the tigers: since there are no tigers without stripes, it’s safe for the model to classify a tiger if and only if there are stripes on the animal.</li><li>The third case is more subtle to spot in and hard to teach to a model. But often it can be simply tolerated.<br> — Subtle because it can be easily overlooked in training phase and discovered only in production, like the tiger example.<br> — Hard to teach because of statistic: assume you just spotted the issue in the model we described in the previous paragraph, and in order to solve it you add the picture you took to the Training set. With such base it’s still very difficult for the model to ignore the feature ‘forest’, while it’s much more likely that the training process will accept a bigger error when facing the tiger in the cage. Technically, the picture you added do not alter the minimum in the weights hyperspace by a sensible value, since is just a sample over 1001. This means that your model is likely to fail in production when facing a tiger in any environment different than a forest.<br>But maybe your model is expected to be used in forest, and so you can accept that your model includes this confounding factor.</li></ol><h3>Conclusions and further readings</h3><p>The control of features correlations can be critical, especially if you train a model on data which is not tuned to your application.</p><p>In principle, non-causal correlation issues can be solved by selecting a dataset <a href="https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables">I.I.D. compliant</a> to train the model, but as you can understand this is impossible for most of the use cases.</p><p>There are very smart people which are specifically studying such underestimated issues. As reference, check the works of <a href="http://pengcui.thumedialab.com/">prof. Peng Cui</a>.</p><p>What a data scientist practically (should) do is to build a fairly good training dataset, also using data augmentation, in order to obtain a sufficient variance in the data, and finally mitigate such issues. And, very important, to monitor the predictions made by the model after the deployment in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=771bcaf84f9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/features-correlations-data-leakage-confounded-features-and-other-things-that-can-make-your-deep-771bcaf84f9f">Features correlations: data leakage, confounded features and other things that can make your Deep…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evasione fiscale: come limarla a costo (forse) zero]]></title>
            <link>https://medium.com/@vincenzo.lavorini/evasione-fiscale-come-limarla-a-costo-forse-zero-26375eed2879?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/26375eed2879</guid>
            <category><![CDATA[taxes]]></category>
            <category><![CDATA[fiscal-policy]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Thu, 08 Aug 2019 13:12:16 GMT</pubDate>
            <atom:updated>2021-09-15T14:14:25.362Z</atom:updated>
            <content:encoded><![CDATA[<h3>Evasione IRPEF: come limarla a costo (forse) zero</h3><p>In questo post descriverò un breve studio che ho fatto sull’Imposta sui Redditi delle Persone Fisiche (IRPEF), sulla base del quale costruirò una mia ipotesi per limitare l’evasione fiscale.</p><p>Specifico subito che non sono un tributarista ne un commercialista: il mio lavoro quotidiano consiste nel creare modelli di dati (<em>Data Scientist</em>), pertanto sia analisi che ipotesi saranno basate esclusivamente sullo studio diretto dei dati. Parimenti, verranno ignorati studi secondari e/o complementari sull’ipotesi che formulerò nella seconda parte del presente articolo.</p><p>Per chi vuole un’anteprima: il sistema di calcolo <a href="https://it.wikipedia.org/wiki/Imposta_sul_reddito_delle_persone_fisiche#Presupposto_e_caratteristiche_dell&#39;imposta">‘a scaglioni’</a> incita all’evasione, dunque basterebbe sostituirlo con una progressione continua.</p><h3>Lo studio</h3><p>Il codice utilizzato per svolgere il presente studio è liberamente scaricabile <a href="https://github.com/vlavorini/studio_irpef">a questo link</a>.</p><p>Cominciamo dunque dal presentare i dati: baserò il presente studio sulle dichiarazioni dei redditi del 2018, relative quindi ai redditi 2017. Tale dataset è scaricabile dal <a href="https://www1.finanze.gov.it/finanze3/analisi_stat/index.php?tree=2018AAPFTOT020602&amp;export=0&amp;media=media&amp;page=1&amp;personalizza=no">sito del Ministero delle Finanze</a>; nella seguente tabella un estratto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwBLI_eeHxPmUs6SfiqSRw.png" /><figcaption>Tabella 1: estratto dei dati forniti dal Ministero delle Finanze.</figcaption></figure><p>In Figura 1 abbiamo il totale dei redditi dichiarati per classe di aggregazione. Ad esempio: il punto più in alto, indicato con una freccia, ci dice che la somma totale dei redditi di coloro che hanno dichiarato tra 20 e 26 mila Euro, è di circa 145 miliardi di Euro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*OuQn7j0iH_eqFUPrIELVJA.png" /><figcaption>Figura 1: distribuzione dei redditi complessivi dichiarati per classi di reddito.</figcaption></figure><p>Come ci si potrebbe aspettare, sia le classi a reddito più elevato che le classi a reddito più basso totalizzano meno delle cosiddette classi medie. Ma quel che salta agli occhi in questa figura è la forte discontinuità dei punti rispetto ad una ipotetica distribuzione ‘liscia’: la Statistica prevede infatti che in presenza di <a href="https://it.wikipedia.org/wiki/Legge_dei_grandi_numeri">grandi numeri</a> (stiamo analizzando circa 40 milioni di contribuenti) le distribuzioni debbano risultare, appunto, lisce.</p><p>Per chiarirci meglio guardiamo la Figura 2, dove abbiamo ipotizzato una curva liscia che generi esattamente lo stesso gettito totale, e dove per chiarezza di visualizzazione trascuriamo i redditi più elevati:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*1gPliHAq2JFruHwd517XIg.png" /><figcaption>Figura 2: Redditi reali e redditi attesi nell’ipotesi di curva liscia a confronto. Gli scaglioni IRPEF sono riportati sull’asse delle ascisse.</figcaption></figure><p>In questa figura appaiono più evidenti le discontinuità tra i redditi dichiarati (punti rossi) ed una ipotetica curva liscia (punti blu). Per completezza di informazione, la curva liscia è definita da quattro parametri, ed è presente nel codice precedentemente fornito.</p><p>Guardando attentamente la figura, notiamo che i punti che stanno al di sotto della curva adattata sono ad immediato ridosso degli scaglioni IRPEF (15, 28, 55, 75 mila Euro). Detto diversamente: in prossimità degli scaglioni i redditi dichiarati sono inferiori alle attese, mentre sono superiori altrove.</p><p>L’unico fenomeno che ci viene in mente per spiegare queste discontinuità è, appunto, l’evasione fiscale: coloro i quali dichiarando tutti i propri redditi rischierebbero di oltrepassare uno scaglione, omettono qualcosa, ricadendo dunque sotto l’aliquota precedente.</p><p>A quanto ne sappia chi scrive, tali soglie sono perlopiù psicologiche: l’aliquota maggiore si applica infatti solo alla parte di reddito eccedente la soglia. In pratica, dichiarando 55001 Euro, quindi appena al di sopra della soglia dei 55000, si pagherebbe praticamente la stessa cosa che dichiarandone 54999, in quanto l’aliquota maggiore verrebbe applicata solo a quell’Euro eccedente. Ma forse mi manca qualche informazione, e se il lettore ha da suggerirmi qualcosa sono tutt’orecchie.</p><h4>La mia ipotesi: progressione continua</h4><p>Il sistema di scaglioni porta dunque con se una sorta di incentivo all’evasione: diviene terribilmente seducente evadere qualcosa per rientrare nello scaglione precedente, a prescindere dal reale risparmio in termini di tasse.</p><p>E se passassimo ad un numero infinito di scaglioni, o in altre parole ad una progressione continua? Sparirebbe l’effetto, più o meno psicologico, del passaggio di scaglioni.</p><p>Di seguito, costruiremo tale ipotesi partendo dagli effetti delle aliquote attuali, in modo da non allontanarci troppo dallo status quo. Faremo quindi un’operazione simile a quella di prima, e cioè adatteremo una curva liscia ai dati.</p><p>Nella Figura 4 abbiamo calcolato l’IRPEF per una serie di redditi imponibili. Vediamo due grafici:</p><ul><li>a sinistra abbiamo i risultati del calcolo dell’IRPEF che attualmente viene effettuato, ed in particolare abbiamo indicato con diversi colori i redditi ricadenti nei diversi scaglioni. Sebbene non sia immediatamente visibile, i diversi scaglioni presentano pendenze diverse: è questo l’effetto delle differenti e progressive aliquote a cui sono sottoposti gli scaglioni.</li><li>A destra abbiamo sovrapposto allo stesso grafico una funzione analitica. Notare che viene rispettata la zona detassata per i redditi sotto le 8.174 Euro.</li></ul><p>Per la cronaca, la funzione analitica utilizzata è una tangente iperbolica modulata da una gaussiana reperibile nel notebook presente <a href="https://github.com/vlavorini/studio_irpef">qui</a>. La funzione è definita da sette parametri, che possono essere modificati per ottimizzare il gettito fiscale per i diversi redditi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*083VFO28XsMksmVsmyNtSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*z-lmpewELmVH04CXmgrD2w.png" /><figcaption>Figura 4: calcolo dell’IRPEF con il sistema attuale; con i diversi colori sono indicate le diverse aliquote. A destra è sovrapposta la curva analitica ipotizzata.</figcaption></figure><p>Il sistema a progressione continua non sembra dunque distaccarsi molto da quello attualmente in vigore. Vediamo più nel dettaglio cosa accade ai montanti totali che lo stato dovrebbe incassare, in Figura 5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*uRNJzJYWSPjrbsHpmsU_tg.png" /><figcaption>Figura 5: confronto tra gettiti IRPEF.</figcaption></figure><p>La nostra ipotesi segue da molto vicino l’andamento del gettito IRPEF. Inoltre, il gettito totale (espresso nella legenda) è esattamente lo stesso.</p><p>Per amor di precisione quantifichiamo le differenze tra questo ipotetico nuovo calcolo dell’IRPEF. In Figura 6 è presentata la differenza percentuale tra i due calcoli.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*uSl0cN5KdIIxnDXuCoxl3A.png" /><figcaption>Figura 6.</figcaption></figure><p>In essa appare evidente che le differenze col modello a scaglioni sono sensibili: al massimo un contribuente potrebbe pagare il 4% in più di IRPEF, nel caso dichiari 28.000 Euro; viceversa, il massimo che si potrebbe risparmiare sarebbe poco meno del 6%, per i redditi estremamente bassi. I redditi alti non noterebbero alcuna differenza.</p><p>Evidentemente, questa curva potrebbe essere ulteriormente perfezionata in modo da minimizzare le differenze rispetto al modello a scaglioni, ma tale compito esula dallo scopo del presente studio.</p><h4>Conclusioni</h4><p>Nel presente breve studio si è tentato di dimostrare come il sistema di calcolo dell’IRPEF a scaglioni porta con se un incentivo all’evasione. Si è pertanto proposto il superamento degli scaglioni, passando dunque ad una progressione continua.</p><p>Si è dimostrato che il gettito fiscale della proposta progressione continua potrebbe essere esattamente lo stesso del modello precedente, sebbene possano esistere differenze localizzate in particolare presso i valori di soglia degli scaglioni.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26375eed2879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bayesian A/B Testing with Python: the easy guide]]></title>
            <link>https://medium.com/data-science/bayesian-a-b-testing-with-python-the-easy-guide-d638f89e0b8a?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d638f89e0b8a</guid>
            <category><![CDATA[business-development]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 14:40:27 GMT</pubDate>
            <atom:updated>2019-05-13T07:51:14.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*M5BjyNgAvjBhd_UgTfBMDA.jpeg" /></figure><p>If you landed on this page, you already know what an <a href="https://en.wikipedia.org/wiki/A/B_testing">A/B test</a> is, but maybe you have some doubt on how to analyse the results within a bayesian framework.</p><p>To start the post, then, let me point you the practical difference of the bayesian approach from the classical, ‘frequentist’ one: the difference is in the form in which the metric you want to study actually is. For the frequentists, it’s a simple number, while for bayesians it’s a <a href="https://en.wikipedia.org/wiki/Probability_distribution">distribution</a>.</p><p>While having a distribution instead of a number appears as just a complication, it turns out to be extremely useful in so many cases, and in A/B tests too. And with this post, you will see that in practice is not so difficult to deal with it. In fact, just few lines of code.</p><p><strong>Edit 18/01/2018: the code on this page has become the baseline of an </strong><a href="https://github.com/NaturalCycles/MixBABA"><strong>A/B testing tool</strong></a><strong> which work with </strong><a href="http://www.mixpanel.com/"><strong>Mixpanel</strong></a><strong>.</strong></p><h3>Straight to the code</h3><p>I promised an easy guide. So in this part I will just show you the code, and in the next one, if you are interested, you will see some of the details hidden behind it.</p><p>Note that no approximation method have been used: no Markov Chain Monte Carlo (MCMC), or any other stochastic (and slow) process. And so, no proabilistic programming framework is needed.</p><p>Let’s introduce the sample data: we already run an A/B test for checking the Conversion Rate (CR, since now on) of a web page, and the results are in the Table 1, below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*zwlO_-OlPjcvPPCh5xp_Lw.png" /><figcaption>Table 1: The data</figcaption></figure><p>Here the code. You just have to install Scipy and Numba, insert your numbers, and you will get your result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21ecb92effceb5a981f405da7f7fdb76/href">https://medium.com/media/21ecb92effceb5a981f405da7f7fdb76/href</a></iframe><p>And the content of the module imported, calc_prob.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca92fe73a678172bc8e6689927ee0739/href">https://medium.com/media/ca92fe73a678172bc8e6689927ee0739/href</a></iframe><p>Based on the numbers in Table 1, the Test option performs much better than the Control one: almost 60% uplift, with more than 98% probability of being better.</p><p>As you can see, these are bare, agnostic, results. Wether they are good or not depends on your situation. A deeper consideration on the thresholds will be treated in another article, but speacking in terms of probability, anything above 95% should be good enough.</p><p>Easy, right? Now let’s dig a bit in the details.</p><h3>The details</h3><p>In the code I initialized two <a href="https://en.wikipedia.org/wiki/Beta_distribution">“Beta” functions</a>, one for each option, feeding them with the numbers we had in the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*HjtYZngt7sh3Ujcq7xBsow.png" /></figure><p>Those are in fact the functions which models the data for an A/B test. To better introduce their behavior, check the animation below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*8CxN7lOhf3ChFg3Mur-6kw.gif" /><figcaption>Figure 1: animation of the Beta distribution for a fixed CR. The ‘X’ axis has been zoomed.</figcaption></figure><p>Each fucntion is built on top of a flat, uninformative one, defined by β(1,1). The more informations (data) we add to this base, the more the function becomes narrower.</p><p>Now you are probably thinking: is it really so simple? Why does exist a function that appear to be built exactly for model A/B tests?</p><p>The answer lies in a nicety of the Bayes theorem. Without going too much into the details, usually solutions to the Bayes theorem are hard (if not impossible) to be solved exactly, and that’s why few approximation methods have been developed, like Markov Chain Monte Carlo (MCMC). You can find a lot of articlesaround the web which uses such procedures.</p><p>But A/B tests are a lucky case, and we actually can have an exact solution based on the concept of “<a href="https://en.wikipedia.org/wiki/Conjugate_prior">Conjugate priors</a>”. When this concept is applicable, the posterior function of the Bayes theorem lies in the same family of the prior one, and so we can build the final function with an iterative process.</p><p>A/B tests are random experiments with exactly two possible outcomes, “convert” or “don’t”, and as such is described as a <a href="https://en.wikipedia.org/wiki/Bernoulli_trial">Bernoulli trial</a>, and the Beta distribution is the conjugate prior for such a process. That’s why we can dare to use it in the simple way I did. But if you still have doubts and/or you want to dig more deep, you can check the mathematical details in <a href="https://en.wikipedia.org/wiki/Conjugate_prior#Example">here</a>: the example in that Wikipedia page is exactely our case.</p><p>Coming back to our case, let me show you the two distributions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02dcb5ea16369a3fb282cf6b1cc82b0d/href">https://medium.com/media/02dcb5ea16369a3fb282cf6b1cc82b0d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*7Aaj97rSPVFse48w9g6yHg.png" /><figcaption>Figure 2: distributions for the two CR.</figcaption></figure><p>You can notice that the peaks of the two distributions coincide with the values you calculate in the classical way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*Uv2RwdVzAmsNphRSmfLETw.png" /></figure><p>The difference, as stated before, is that you have a whole Probability Density Function (<em>PDF</em>) for the CR, instead of a simple number. And thanks to this, you can calculate, as example, the variance (popularly said ‘the error’) on the CRs, which is also shown on the label within the plot.</p><p>Now you can calculate what is called the ‘uplift’, i.e. how much Test option increase the CR with respect to the Control one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*1aA3Dj4gQwlbFeo7x0ZNFw.png" /></figure><p>But, at this point, you need to asses how trustful is this result. How? Well, you can estimate the probability for one option to be better than the other!</p><p>Note that, in the classical, “frequentist”, paradigm you have no way of calculate such probability. In that approach, you usually calculate the ‘<a href="https://en.wikipedia.org/wiki/P-value">p-value</a>’, and then check whether or not it falls under an arbitrarily chosen threshold (‘α value’, typically 5%), and eventually you can declare something almost impossible to explain to any manager/client/board: “with 95% confidence level, we can reject the null hypothesis”. And then, you have to explain that this declaration is very different from “this hypothesis is better then the other with 95% probability”, which is the very sentence they really want to hear from you.</p><p>But here we are in the bayesian world, and here we can actually say that. In fact, we have PDFs which define our CR, and the probability is given by the area under the curve. This is, practically, the definition of PDF.</p><p>A simple example: do you want the probability for the Test option’s CR to be greater than, say, 0.003? Well, it’s just the area under the Test curve between 0.003 and 1.0, which is shaded in the Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*RC23dWNTSPCN_hBQTF9y7Q.png" /><figcaption>Figure 3: The probability for the Test option CR to be greater than 3E-03.</figcaption></figure><p>In Math language, you calculate the area by integrate over the curve between the two limits: 0.003 (the limit that we choose) and 1 (the hard limit).</p><p>With Python, we can calculate this integral exactely (still: no Monte Carlo needed), courtesy of the <a href="http://mpmath.org/">Mpmath</a> library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3db7df8773c590051c140eb614d694a6/href">https://medium.com/media/3db7df8773c590051c140eb614d694a6/href</a></iframe><p>In this example we considered only one distribution (the Test one), but to measure the trustefulness of our uplift we have to consider both the distributions (Control and Test), and so in order to visualize the situation we have to add a dimension. By consequence, the probability we are going to measure is is defined not by an area anymore, but by a volume instead. In particular, the volume under the <a href="https://en.wikipedia.org/wiki/Joint_probability_distribution">joint probability distribution</a> of Test and Control where the Test is greater than the Control. Let’s see what it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*TfHWi1hSP7sEUhrYW1-RhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*8lS1RGfxd6C5UEYdL-vElg.png" /><figcaption>Figure 4: the Joint PDF of the two options. Left: 3-d visualization. Right: view from the top (zoomed). The gray plane (or line, in the 2-d) separate the zone where the Test dominate the Control.</figcaption></figure><p>Imagine the plot of Figure 4 in the left as the picture of a mountain, and its view from a satellite is in the right plot. Focusing on the plot on the right, you can see the grey line as the border between the land belonging to the Test option (upper triangle) and the land of the Control option. In this scenario, the question become: how much amout of mountain do Test have more than Control?</p><p><strong>UPDATE (13/05/2019)</strong>: Since I had several requests about this, below you can find the code for recreate the plot of Figure4, right. This uses Monte Carlo sampling, and a lot of points are needed to have a figure nice to see:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2902b36c2a96ef64c6b75f8d029d151/href">https://medium.com/media/f2902b36c2a96ef64c6b75f8d029d151/href</a></iframe><p>To calculate this volume (in the upper triangle of Figure 4), I saw a lot of posts around the web which, again, use approximated methods (like Monte Carlo). Well, the people who wrote them are not aware that an exact method has already been deployed by John Cook in 2005 (chapter 2, <a href="https://www.johndcook.com/UTMDABTR-005-05.pdf">here</a>). The code within the module calc_prob.py reproduces that formulation, and comes almost in full from a <a href="https://gist.github.com/arsatiki/1395348/f0275f529d322d3c23e18201f26890f5a09dcb51">version</a> originally wrote by <a href="http://ars.iki.fi/">Antti Rasinen</a>.</p><p>In our case the area is 0.98, which means that the ‘Test’ option performs better than the ‘Control’ one with 98% probability.</p><p>Let me highlight that if the result was, hypotetically, 50%, than the mountain was perfectly shared, and this means no options is better than the other, while smaller value means than Test option is actually worse than the control one.</p><p>That’s all.</p><p>As you see, the details behind the few lines of code at the start of this posts are deep, and not so straightforward. But I hope I’ve been clear and simple in the description of the concepts, as I stated in the title.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d638f89e0b8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/bayesian-a-b-testing-with-python-the-easy-guide-d638f89e0b8a">Bayesian A/B Testing with Python: the easy guide</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gaussian Mixture Model clusterization: how to select the number of components (clusters)]]></title>
            <link>https://medium.com/data-science/gaussian-mixture-model-clusterization-how-to-select-the-number-of-components-clusters-553bef45f6e4?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/553bef45f6e4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 18:17:44 GMT</pubDate>
            <atom:updated>2018-11-21T18:17:44.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Gaussian Mixture Model clustering: how to select the number of components (clusters)</h3><p>If you landed on this post, you probably already know what a Gaussian Mixture Model is, so I will avoid the general description of the this technique.</p><p>But if you are not aware of the details, you can just see the GMM as a k-means which is able to form stretched clusters, like the ones you can see in <strong>Figure 2</strong>.</p><p>All the code used for this post is <a href="https://github.com/vlavorini/ClusterCardinality/blob/master/Cluster%20Cardinality.ipynb">in this notebook</a>. In the same <a href="https://github.com/vlavorini/ClusterCardinality">repository</a> you can find the data to fully replicate the results you see plotted.</p><p>Now: suppose you are in the situation depicted in <strong>Figure 1</strong>, you want to discern how many clusters we have (or, if you prefer, how many gaussians components generated the data), and you don’t have information about the “ground truth”. A real case, where data do not have the nicety of behaving good as the simulated ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*ow6_Gqqf9-6JIfmn43nv1A.png" /><figcaption><strong>Figure 1:</strong> The vecotrs we are going to cluster. The transparency on the points reflects the density.</figcaption></figure><p>At a first look, one could scream “Three main cluster plus two minor!”. And maybe it’s just correct, but here we want to check for an automated method for finding the “right” number of clusters.</p><p>It’s to be noted that this “right” number is something fluffy anyway, since the specificity of each problem can lead one to decide to overcome the decision of the automated algorithm.</p><p>But let me introduce the GMM results for the configuration we just announced (five clusters). In the plot below (<strong>Figure 2</strong>) we fitted a GMM with five components to our data. And we have our first issue: same data, same model, but different results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*UZRRyYnZ2naAg_2MdwdGkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*7EElitYX6YvJnc1cqQcWIA.png" /><figcaption><strong>Figure 2: </strong>Clusters shapes: since the algorithm we rely on is not deterministic, we can have very different results!</figcaption></figure><p>The guilty for this behavior is the fitting procedure: the <a href="https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm">Expectation-Maximization (EM) algorithm</a>. This algorithm only guarantee that we land to a local optimal point, but it do not guarantee that this local optima is also the global one. And so, if the algorithm starts from different initialization points, in general it lands into different configurations.</p><p>While there are other procedures to fit the GMM, we want to stick on this one: the other methods are more complex and require more hyperparameters to be set; and this exceed the goals for this post.</p><p>We, then, have to take in account of the non-deterministic nature of our guy.</p><p>The easiest way of dealing with it is to run the fitting procedure several times, and consider the mean value and the standard deviation for each configuration. Put simple: we account for an error on each fit.</p><h3>Cluster performance evaluation(s)</h3><p>Since we don’t know the ground truth of our cluster generators, i.e. we are not aware of the original distribution which generated the data, our choices about the performance evaluation of the clustering process are limited and quite noisy.</p><p>Nonetheless, we will explore three different techniques.</p><h4>Silhouette score</h4><p>This score, as clearly stated by the <a href="https://scikit-learn.org/stable/modules/clustering.html#silhouette-coefficient">SKLearn</a> developers, consider two measures:</p><ul><li>The mean distance between a sample and all other points in the same cluster.</li><li>The mean distance between a sample and all other points in the <em>next nearest cluster</em>.</li></ul><p>i.e. it checks how much the clusters are compact and well separated. The more the score is near to one, the better the clustering is.</p><p>Since we already know that the fitting procedure is not deterministic, we run twenty fits for each number of clusters, then we consider the mean value and the standard deviation of the best five runs. The results are in <strong>Figure 3</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*6Q5kcr8XQJLir6DUG282ww.png" /><figcaption><strong>Figure 3: </strong>Silhouette scores for our dataset</figcaption></figure><p>Well, it turns out that we get the best score with <strong>five</strong> cluters. We have also to consider that also the four cluster configuration is almost equally good, if we consider the standard deviation (the ‘error’) of both the configurations. So, this score do not gives us a clear result.</p><h4>Distance between GMMs</h4><p>Here we form two datasets, each with an half randomly choose amount of data. We will then check how much the GMMs trained on the two sets are similar, for each configuration.</p><p>Since we are talking about distributions, the concept of similarity is embedded in the <a href="https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence">Jensen-Shannon (JS) metric</a>. The lesser is the JS-distance between the two GMMs, the more the GMMs agree on how to fit the data.</p><p>All the credits on the (beautiful!) way the Jensen-Shannon metric is calculated go to <a href="http://www.gatsby.ucl.ac.uk/~dougals/">Dougal</a>, and to its post on <a href="https://stackoverflow.com/questions/26079881/kl-divergence-of-two-gmms">StackOverflow</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8qfMomHiHmS2aawUfFcQA.png" /><figcaption>Figure 4: Distance between half data GMMs</figcaption></figure><p>Following this technique, the configuration with three clusters is the most conservative; this do not necessarily means that it’s the good configuration, since we are just talking about reproducibility of the results between the two sets.</p><p>The interesting part of this plot is the sudden change in the distance we see after passing the six cluster configuration: both the mean distance and its associated error show a huge increase.</p><p>This means that starting from seven clusters, the GMMs of the two sets are much more different (since the distance is much bigger), and also less stable (since the error band is much bigger).</p><p>We can say that the good configuration, which takes in account both of the amount of information included (=biggest possible number of clusters) and on the stability of the fitting procedure (=lowest possible GMMs distance), is the one which considers <strong>six</strong> cluster.</p><h4><strong>Bayesian information criterion </strong>(BIC)</h4><p>This criterion gives us an estimation on how much is good the GMM in terms of predicting the data we actually have. The lower is the BIC, the better is the model to actually predict the data we have, and by extension, the true, unknown, distribution. In order to avoid overfitting, this technique penalizes models with big number of clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*360DP4OfT2aIyGPDFQiWEg.png" /><figcaption><strong>Figure 5: </strong>Bayesian information criterion scores as function of the number of normal components (clusters) forming the GMMs.</figcaption></figure><p>Following this criterion, the bigger the number of clusters, the better should be the model. Which means that the penalty BIC criteria gives to complex models do not save us from overfit. Or, in more prosaic terms, this score sucks. At least in this basic form.</p><p>But before screaming and trashing out this technique, we can notice two things. The first is that the curve is fairly smooth and monotone. The second is that the curve follows different slopes in different part of it. Starting from these two observations, the temptation to check where the BIC curve change slope is big. So let’s check it!</p><p>Technically, we have to calculate the <em>gradient</em> of the BIC scores curve. Intuitively, the concept of gradient is simple: if two consecutive points have the same value, their gradient is zero. If they have different values, their gradient can be eighter negative, if the second point has a lower value, or positive otherwise. The magnitude of the gradient tells us how much the two values are different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*_4asd_CvbnUGroC73WBVOQ.png" /><figcaption>Figure 6: plot of the gradients of the curve in <strong>Figure 5</strong></figcaption></figure><p>As expected, all the gradients have negative values. But we see more clearly that starting from a cluster size of seven the gradient become almost constant, i.e. the original function has a more gentle decrease, i.e. there is no much gain in increasing the number of clusters. In short, this technique suggest us to use <strong>six</strong> clusters.</p><h3>Final decision: change model</h3><p>We have explored three different techniques to choose the right number of clusters which can be discerned in this dataset. The results are in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*qmT3TRRgzt8-10dyu-gIUQ.png" /></figure><p>Even if the decisions are similar, there is no a clear value on which all the strategies agree. In this specific case, this means that the GMM is not a good model to cluster our data.</p><p>Another sympton you can catch is that both the Silhouette and the gradient of BIC show a second value which is almost as good as the choose one: 4 is almost as good as 5 for the Silhouette, and 5 is almost as good as 6 for the gradient of BIC scores.</p><p>One could say to just take five (<em>in medio stat virtus</em>) as the right number of clusters, but this could not be the optimal choice. And it turns out that actually it was not for my specific issue.</p><p>This because the clusters do not show a clear symmetric (oval-like) shape, and so they can not be approximated by a model composed of 2-d gaussians like the one you see in <strong>Figure 7</strong>, which instead are symmetric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*hGSRf2PEFXcHqScxCWIneA.png" /><figcaption>Figure 7: a bi-variate normal distribution.</figcaption></figure><p>I hope you enjoy the reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=553bef45f6e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/gaussian-mixture-model-clusterization-how-to-select-the-number-of-components-clusters-553bef45f6e4">Gaussian Mixture Model clusterization: how to select the number of components (clusters)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speeding up your code (4): in-time compilation with Numba]]></title>
            <link>https://medium.com/@vincenzo.lavorini/speeding-up-your-code-4-in-time-compilation-with-numba-177d6849820e?source=rss-f0c2f36e0bc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/177d6849820e</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vincenzo Lavorini]]></dc:creator>
            <pubDate>Tue, 06 Mar 2018 15:38:31 GMT</pubDate>
            <atom:updated>2018-07-06T08:59:42.253Z</atom:updated>
            <content:encoded><![CDATA[<p>From this series:</p><ol><li><a href="https://medium.com/@vincenzo.lavorini/speeding-up-your-code-1-the-example-of-the-mean-shift-clustering-in-poincar%C3%A9-ball-space-d46169bfdfc8">The example of the mean shift clustering in Poincaré ball space</a></li><li><a href="https://hackernoon.com/speeding-up-your-code-2-vectorizing-the-loops-with-numpy-e380e939bed3">Vectorizing the loops with Numpy</a></li><li><a href="https://towardsdatascience.com/speeding-up-your-code-3-batches-and-multiprocess-52d2d34a4091">Batches and multithreading</a></li><li>In-time compilation with Numba (this post)</li></ol><p>In the previous posts we worked with our minds in order to speed up a (relatively) simple algorithm. Probably there are other smart ways to squeeze up more execution time, but nothing very interesting came to my mind.</p><p>So, it’s time to pass to the brute force. But still, I will avoid to use <a href="https://en.wikipedia.org/wiki/Graphics_processing_unit">GPUs</a> or <a href="https://en.wikipedia.org/wiki/Tensor_processing_unit">TPUs</a>. This because, as I already shown in this other <a href="https://towardsdatascience.com/numpy-vs-tensorflow-speed-on-matrix-calculations-9cbff6b3ce04">post</a>, often you loose so much time in moving the data from the system memory to the GPU (or TPU) that, at the end, the whole process will result as slower.</p><p>But there are other ways of exploiting the brute force, i.e. of improving the results without squeezing too much our brains.</p><p>One of them is <a href="https://numba.pydata.org/">Numba</a>. It’s a tool that takes our function and “compile” them, which means that it translate them in a low level and code which (roughly speaking) speak the same language of the CPU. And so it’s faster.</p><h4>Numba at work</h4><p>Asking Numba to compile a function is easy as writing four letters before the definition of the function, “@jit”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d3e81aa635da0753d28bb08897af174/href">https://medium.com/media/4d3e81aa635da0753d28bb08897af174/href</a></iframe><p>The ‘<em>at</em>’ symbol in Python is known as ‘function decorator’. They tell the interpreter to alter the functionality of the defined function. In our case, the decorator tell the interpreter to modify the function following the instructions of Numba. You can find more informations about such niceties <a href="https://www.thecodeship.com/patterns/guide-to-python-function-decorators/">here</a>.</p><p>Actually Numba has lots of very useful tools within. One for all: it can do an automatic parallelization of the code. Of course, an ‘automatic’ tool is in general unable to deal with every kind of possible parallelization in a function, so don’t expect miracles from it. Since we already managed to manually parallelize the code, we will not use this functionality.</p><p>So we will just have to add the decorator before the function definitions? Almost. Since Numba is still in high development, not all the Numpy functions that we use are supported. And so, we have to make some minor modification.</p><p>In particular, the <em>np.tile</em> function is still not supported. An easy workaround is to create a void array of the desired shape, and fill it with the copies of the vectors that we need:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c4ea085a094d874feeca2bf80c872f4/href">https://medium.com/media/9c4ea085a094d874feeca2bf80c872f4/href</a></iframe><p>You can see that we feed the decorator with two parameters:</p><ul><li>The first one, <em>nopython=True</em> is telling Numba to actually compile the function. It may seem redundant, and actually in our case it is. But in the cases where Numba is unable to compile the function, it will be executed in the usual Python interpreted way, and so we will loose the functionality we want to achieve. By adding this parameter, Numba will raise an error in such cases, and so we can dig in to understand where it falls. So it is a good practice to add it anyway.</li><li>The second one, <em>nogil=True</em> tells the Python interpreter to release the <a href="https://docs.python.org/3/glossary.html#term-global-interpreter-lock"><em>Global Interpreter Lock</em></a><em>.</em> A description of the GIL functionality goes beyond the scope of this post, but in short: if we keep it with the compiled code, we loose the parallelization, so we have to release it.</li></ul><p>The rest of the code is exactly as in the <a href="https://towardsdatascience.com/speeding-up-your-code-3-batches-and-multiprocess-52d2d34a4091">previous post</a> , with the only exception of placing the decorator with the two arguments, <em>@jit(nopython=True, nogil=True)</em> in the other two called function (<em>__shift, gaussian</em>). Note that the main one, <em>meanshift_parallel</em>, cannot be compiled in the way it is built.</p><p><strong>Performance improvement</strong></p><p>Now let’s switch to the numbers. How much speed we have gained?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*fzq5WhkdEoJcrG4rLC0bkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*rbBSbBqsv2k5wX9DjB1nGg.png" /></figure><p>Well, we actually gained execution time. But there is a saturation effect: with the growing number of vectors, the two execution speed approach more and more.</p><p>This is the final post from this series.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=177d6849820e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>